Sistema de Agendamento Exército Brasileiro

Question: Estou com um problema um tanto perturbador, já pesquisei tentei de varias formas, mas não achei solução.
Abaixo a explicação:
Um sistema bem simples, ele parece com um calendário, porem dentro da cada dia do calendário,
existe 3 campos em checkbox para serem clicados, nesses campos usei a nomenclatura de C, A, J (Café, Almoço e Jantar) e também tornei clicável o numero do dia.
ficando da seguinte forma:

Com esse sistema o Militar consegue agendar o dia que ele vai comer na cozinha.
O problema que estou tendo é que quando ele seleciona mais de 1 numero de dia o resultado aparece todo duplicado, assim:

Segue abaixo o código:
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title>Sistema de Arranchamento</title>
    <?php
    /*include "conectando.php"; */
        date_default_timezone_set('America/Sao_Paulo');

         $dates = date('Y/m/d');
         $hoje = getdate(strtotime($dates));
         $ultimoDia = cal_days_in_month(CAL_GREGORIAN,
                                       $hoje['mon'],
                                       $hoje['year']);

        $primeiraSemana = (($hoje['wday'] + 1) -
                          ($hoje['mday'] - ((int)($hoje['mday'] / 6) * 7))) % 7;

    ?>

Estamos em <?= $hoje['year'] ?>

<?= sprintf('Hoje é dia %0d / %0d, agora são %02d horas e %0d minutos.',
                   $hoje['mday'], $hoje['mon'], $hoje['hours'], $hoje['minutes'])
    ?>

            Dom
            Seg
            Ter
            Qua
            Qui
            Sex
            Sáb

    <form action="checkbox.php" method="post">
        <?php
        for($semana = 0; $semana < $primeiraSemana; ++$semana) {
            echo ' 	';
        }
        for($dia = 1; $dia < $ultimoDia; ++$dia) {
            if( $semana > 6 ) {
                $semana = 0;
                echo '

';
            }

            echo "";
            echo "$dia <input type='checkbox' name='dia[]' value='$dia'> <input type='checkbox' name='opcao[]' value='C'>C <input type='checkbox' name='opcao[]' value='A'>A <input type='checkbox' name='opcao[]' value='J'>J	";
            ++$semana;
        }
        for(; $semana < 7; ++$semana) {
            echo ' 	';
        }

        ?>

    <?php
if( !empty( $_POST['dias'] ) ) {
    foreach( $_POST['dias'] as $key => $value ) {
        echo "
Semana $key
";
        foreach( $value as $dias ) {
            echo "$dias
";
        }
    }
}
?>

    <input type=submit value="Arranchar">
       </form>

checkbox.php
<?php
// Verifica se usuário escolheu algum número

if(isset($_POST["dia"])){
   if(isset($_POST["opcao"])){

     echo "Você se arranchou para os dias:
";

     // Faz loop pelo array dos numeros
     foreach($_POST["dia"] as $dia){
       foreach($_POST["opcao"] as $numero){

        echo " - " . $dia . " -" . $numero . "
";
       }
     }
   }
}
else
{
    echo "Você não se arranchou para nenhum dia!
";
}
?>

Comment: Assim que o bloqueio da pergunta terminar, em cerca de 45 minutos, por favor, edite a pergunta para mudar qualquer tipo de informação que lhe prejudique, mas sem que invalide as respostas. Obrigado.
Comment: Dá  um print_r($_POST); pra ver o que retorna pra você...
Comment: O erro está no forach do checkbox.. porque você está fazendo dois foreach.. por isso duplica mesmo :)
Comment: O problema é que os dias têm de estar associados as outras checkbox
Answer: Consegui resolver o seu problema com array bidimensional, porque tens de saber qual o dia escolhido e quis refeições associadas a esse dia.
echo "$dia
<input type='checkbox' name='"; echo "arrachar[$dia][dia]";    echo"' value='$dia'>
<input type='checkbox' name='"; echo "arrachar[$dia][opcaoC]"; echo"' value='C'>C
<input type='checkbox' name='"; echo "arrachar[$dia][opcaoA]"; echo"' value='A'>A
<input type='checkbox' name='"; echo "arrachar[$dia][opcaoJ]"; echo"' value='J'>J	";

E no checkbox.php:
if(isset($_POST["arrachar"]))
{
    echo "Você se arranchou para os dias:
";

    foreach($_POST["arrachar"] as $infos)
    {
        if(count($infos)==1) //verifica se tem alguma refeição marcada
                continue;
        $first = 1;
        foreach($infos as $info)
        {
            if($first == 1) //primeiro elemento do array é o dia.
            {
                echo "No dia $info";
                $first = 0;
            }
            else
                echo "e refeição $info";
            echo "
";
        }
        echo "
";
    }
}

Veja aqui o exemplo
Answer: Elabore o foreach desta forma:
Da forma que você fez, está duplicado... Pode passar um parametro só.
foreach($_POST as $key){
    echo "{$key->dia} - {$key->opcao}";
}

Comment: Acho que assim não funciona...
Comment: Porque cada dia pode ter mais de uma opção...
Comment: Faça o teste. Eu normalmente pego o post e coloco dentro do foreach para buscar as arrays que eu quero, independente de quantas sejam para cada dia..
Comment: http://phpfiddle.org/main/code/uwsx-rcv7
Comment: Tem de ser com array bidimensional para associar as opções aos dias...
Comment: Conseguiu elaborar?


Hide horizontal scrolling bar, But keep scrolling feature

Question: I have a container with some text that has specific width (Less than the content), I want to add horizontal scrolling, But the scroll bar should be hidden.
Here is a fiddle of what I tried:
https://jsfiddle.net/ehp3qnty/576/

.parent {
  width: 400px;
  height: 200px;
  border: 1px solid #aaa;
  overflow: hidden;
}

.child {
  height: 100%;
  margin-bottom: -50px;
  /* maximum width of scrollbar */
  padding-bottom: 50px;
  /* maximum width of scrollbar */
  overflow-y: hidden;
  overflow-x: scroll;
}

p {
  white-space: nowrap;
}

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum.

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum.

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum.

But I can't scroll on mobile by swiping right and left or on desktop, Also wheel is not working.
So how to hide the horizontal bar but keep these features?
The solution should be compatible with most of the browsers and without using any libraries, Just pure CSS/JS.
Answer: css code will help you
              .parent {
               width: 400px;
               height: 200px;
               border: 1px solid #aaa;
               overflow:auto;
               overflow-y: hidden;
                  }

              .child {
                height: 100%;
                margin-bottom: -50px;
                /* maximum width of scrollbar */
                   padding-bottom: 50px;
                 /* maximum width of scrollbar */

                    }

                    p {
                   white-space: nowrap;
                     }

Comment: +1 because this answers the question very well, but it is important to remember a lot of people do not intuitively know to press and hold the middle mouse button to side scroll.  Thus my UI/UX comment to Jesus.
Comment: DO you know how to slow down the scrolling?
Comment: Poor formatting, very little description as to whats happening in your code, and I disagree with using a 'hacky' code `margin-bottom: -50px;`
Answer: You can use this to change the css of the scrollbar :)
/* width */
::-webkit-scrollbar {
    width: 10px;
}

/* Track */
::-webkit-scrollbar-track {
    background: #f1f1f1;
}

/* Handle */
::-webkit-scrollbar-thumb {
    background: #888;
}

/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
    background: #555;
}

What you probably want to do is something like so:
.child::-webkit-scrollbar {
    height: 10px;
}

Or (to make it super unobtrusive without completely hiding it):
.child::-webkit-scrollbar {
    height: 1px;
}

EDIT: Your JSFiddle Example also works fine on my browser (Google chrome on MacOSX) and on my mobile Safari, Iphone X (latest version)
Comment: that should be height for a horizontal scrollbar
Comment: Also, removing the scrollbar entirely from scrollable content is a pretty major UI/UX taboo. Providing cross platform compatibility without them becomes an issue, unless you do some fancy JavaScript to support click-and-drag.  So just as a suggestion if you are only looking for making the scrolling less intrusive, try something like the above CSS but at a height of 5px instead of totally hiding it.
Comment: @Nosajimiki I'd argue it depends on the situation. Sometimes I'd say you can get away with definitely not having one.
Comment: I completely agree, and his may be such a case. I only put that comment out there because many times when people say they don't want a scrollbar, they are really saying, the scrollbar is ugly and taking up too much space. The decision to remove one should always be weighed against the end user's likelyhood to know to interact with it by other means.
Comment: Do you know how to slow down the scrolling?
Comment: @Nosajimiki Ah I see what you're saying now. I think that's a fair comment. Thanks for your input :)
Comment: @maxwell Not quite sure what you mean? Could you explain? If you're quite bothered about all of this scrollbar business I would considering looking into a js alternative, it will allow for a more consistent experience across browsers and will give you more customization options. This might help with scroll speed but it's js only: https://stackoverflow.com/a/26386218/3722330
Comment: @Jesus, I mean to make the scrollbar moving slower on scrolling, I viewed this answer before, It contains Jquery code
Comment: @maxwell unfortunately it's going to have to be done in atleast javascript. There's no pure HTML and CSS way of doing it. You'll either need to do it in javascript or jquery, the jquery way will be a lot easier. You may want to look into the following https://nicescroll.areaaperta.com/, https://stackoverflow.com/questions/17227162/change-scroll-speed-of-specific-element. I'd also appreciate if you marked this as the correct answer if my code/comments were useful :)
Answer: For your use-case, use:
.child::-webkit-scrollbar {
    height: 10px;
}


Removing other windows causes freeze/crash

Question: I want to have a main Window (class MyMainWindow), from which you can launch an undefined number of other Windows (class MyWindow), which you can use to get some information. Each of these other Windows is opened by pressing a button btnWindow in the main window and can be closed (with its (x)-button) when it is not needed any more.
All Windows are inherited from QMainWindow. So I have to keep a variable to point to them; otherwise they would be closed by the garbage collection. For this I use the list self.children. Since the main window stays open for hours and the user opens many windows and closes some of them, I want to keep track of the windows in use. For that I created an eventFilter which removes the windows to be closed from my list.
But unfortunately this causes the entire application to crash with a SIGKILL or a SIGSEGV.
class MyMainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()                         # from QMainWindow
        self.setupUi(self)                         # from Ui_MainWindow
        self.children = []
        self.btnWindow.clicked.connect(self.onWindow)
        self.show()

    def onWindow(self):
        win = MyWindow()
        win.installEventFilter(self)
        self.children.append(win)

    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.Close and obj in self.children:
            self.children.remove(obj)
        return False

So my questions are:

Why does my application crash?
How can I avoid the crash?
Or is there a smarter way to keep track of the Windows in use and remove unused ones?
Comment: Just do `win = MyWindow(self); win.setAttribute(Qt.WA_DeleteOnClose)`. You don't need `children` (which shadows a built-in method). If you need to get a list of windows, use [QApplication.topLevelWindows()](https://doc.qt.io/qt-5/qguiapplication.html#topLevelWindows) (or `mainwindow.findChildren(MyWindow)`). To close everything, use [QApplication.closeAllWindows()](https://doc.qt.io/qt-5/qapplication.html#closeAllWindows).
Answer: The QCloseEvent is "sent to widgets that the user wants to close". So, not only the event is triggered when the window is still open, but it is also an event that can be ignored.
What happens in your case is that, by removing the only reference to that window, you're destroying it. But, at that point, a reference still exists: eventFilter has not returned yet, you're just removing the object from the list but since obj is within the scope of eventFilter, it's still a valid Qt object.
After that, you're returning False: when the event filter returns False, it means that the event will be handled: this is normally done by the event() of the object itself. Qt will actually send the Close event to the widget, and do other things after that. The problem is that at that point, eventFilter() has already returned, python has lost the last reference to the widget, and then it will destroy it.
So, Qt will be doing those "other" things, while in the meantime the object ceases to exist; this causes the program to freeze/crash because Qt is trying to access an object that has been removed from memory.
The simple solution would be to return True in the filter:
    def eventFilter(self, obj, event):
        if event.type() == QEvent.Close and obj in self.children:
            self.children.remove(obj)
            return True
        return False

This should ensure that the event won't be processed any more, so you don't risk any memory access issue.
Also note that some Qt classes already have an overridden eventFilter(), so it's always good practice to return super().eventFilter(obj, event) when the event is not handled or shouldn't be completely discarded (which doesn't mean it will or won't be ignored).
An important warning, though. Multiple event filters can be added to an object, and that could create a problem: if another filter was already set, you go back to square one, since the object has been destroyed.
A better solution is to not rely on the deletion by the garbage collector, but allow Qt to do it. In your case, it can be done by setting the Qt.WA_DeleteOnClose attribute on the window, and connect to the destroyed signal for the actual removal of the python reference:
    def onWindow(self):
        def removeWin():
            if win in self.children:
                self.children.remove(win)
        win = MyWindow()
        win.setAttribute(Qt.WA_DeleteOnClose)
        self.children.append(win)
        win.destroyed.connect(removeWin)
        win.show()

An alternative solution, if you don't need a reference to those windows, is to set their parent.
For QMainWindow, you can do it just by adding the parent argument in the constructor:

QMainWindow sets the Qt::Window flag itself, and will hence always be created as a top-level widget.

So, the following is quite sufficient:
class MyWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        # ...

class MyMainWindow(QMainWindow):
    # ...
    def onWindow(self):
        win = MyWindow(self)
        win.setAttribute(Qt.WA_DeleteOnClose)
        win.show()

Or just do that in the constructor already:
class MyWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        # ...

class MyMainWindow(QMainWindow):
    # ...
    def onWindow(self):
        win = MyWindow(self)
        win.show()

For any other QWidget, you either set the flag by yourself, or you manually set the parent using the QObject.setParent() function call, since the QWidget.setParent() override automatically resets all window flags (making the widget also a "physical" child, aka: shown inside the parent).
Supposing that MyWindow is just a QWidget subclass:
    def onWindow(self):
        win = MyWindow(self)
        win.setAttribute(Qt.WA_DeleteOnClose)
        win.setWindowFlag(Qt.Window)
        win.show()

# or, alternatively:
    def onWindow(self):
        win = MyWindow() # <- no parent in the constructor
        QObject.setParent(win, self)
        win.setAttribute(Qt.WA_DeleteOnClose)
        win.show()

Obviously, as above, this can also be done in the __init__ of the MyWindow class:
    def onWindow(self):
        win = MyWindow(self)
        win.show()

class MyWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlag(Qt.Window)

# otherwise
class MyWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__()
        QObject.setParent(self, parent)
        self.setAttribute(Qt.WA_DeleteOnClose)

Note: it's normally good practice to not call self.show() in the __init__ of a widget.


VIM jump to the next logical block in a program

Question: Is there a functionality inside VIM or a VIM plugin that lets a user jump to the next blank line ("logical block" inside a program)?
Example:
// cursor is originally here
-> means the next location of jump
#include<stdio.h>
->
main()
{
   ->
   int n;
   ->
   printf("Enter an integer\n");
   scanf("%d",&n);
   ->
   if ( n & 1 == 1 )
      printf("Odd\n");
   else
      printf("Even\n");
   ->
   return 0;
}

Thanks!
Comment: Of course there is! `:help motion.txt` will blow your mind.
Answer: One very simple is to use the paragraph motion with } to jump forward and { to jump backwards.
Comment: It doesn't work for me. } jumps to line before main, then to end of a program. The way I understand { or } jumps to next paragraph - and those "logical blocks" are not paragraphs.
Comment: I take it back. I use a plugin for my IDE and it doesn't do it, but vim inside terminal does exactly the way you described. Sorry.


GlusterFS Mount Keeps Disconnecting Randomly

Question: We are using GlusterFS to provide a distributed file system on 2 web servers which use a shared media directory and cache. So i have created 2 gluster volumes (media and var) and have mounted these in /var/www/site/media and /var/www/site/var/.
Each server is running the gluster server and client so that we have some redundancy and get to keep the data replicated. The var volume is written and read very heavily.
The problem we are encountering is that randomly the mounts will break and when you perform a ls -lah on the directory it is showing as d???????. To resolve the issue all we have to do is umount the directory and remount it.
I have reviewed the glusterfs log files and can see when the mount disappeared
<code>[2013-05-02 11:32:02.105021] I [client3_1-fops.c:502:client3_1_unlink_cbk] 0-site-media-client-1: remote operation failed: No such file or directory

[2013-05-02 11:32:02.105270] I [client3_1-fops.c:502:client3_1_unlink_cbk] 0-site-media-client-0: remote operation failed: No such file or directory

[2013-05-02 11:32:02.105299] W [fuse-bridge.c:911:fuse_unlink_cbk] 0-glusterfs-fuse: 11806336: UNLINK() /catalog/product/cache/1/image/1000x1000/9df78eab33525d08d6e5fb8d27136e95/v/e/some-stuff-0915740$

[2013-05-02 11:32:02.378497] I [client3_1-fops.c:502:client3_1_unlink_cbk] 0-site-media-client-0: remote operation failed: No such file or directory

[2013-05-02 11:32:02.378625] I [client3_1-fops.c:502:client3_1_unlink_cbk] 0-site-media-client-1: remote operation failed: No such file or directory
</code>
We would like to know what is causing these problems and to resolve them to prevent these interruptions to the service.
If you require any more information feel free to ask and I'll provide what i can.
The requested additional information is below, the two servers are identical:
Ubuntu 12.04.2
Linux VDED-XXX-XXX 3.2.0-39-generic #62-Ubuntu SMP Thu Feb 28 00:28:53 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
glusterfs 3.2.5 built on Jan 31 2012 07:39:59
VMWare ESX Servers
Errors From The Brick Logs at the time of the crash/disconnection/problem:
site-media brick log:
<code>[2013-05-02 11:32:00.849296] I [server3_1-fops.c:964:server_unlink_cbk] 0-site-media-server: 9109306: UNLINK /catalog/product/cache/1/image/1000x1000/9df78eab33525d08d6e5fb8d27136e95/v/e/some-stuff-091574183930-box.jpg (0) ==> -1 (No such file or directory)

[2013-05-02 11:32:02.86607] I [server3_1-fops.c:964:server_unlink_cbk] 0-site-media-server: 9109345: UNLINK /catalog/product/cache/1/image/1000x1000/9df78eab33525d08d6e5fb8d27136e95/v/e/some-stuff-091574098692.jpg (0) ==> -1 (No such file or directory)

[2013-05-02 11:32:02.105131] I [server3_1-fops.c:964:server_unlink_cbk] 0-site-media-server: 12553441: UNLINK /catalog/product/cache/1/image/1000x1000/9df78eab33525d08d6e5fb8d27136e95/v/e/some-stuff-091574097992-box.jpg (0) ==> -1 (No such file or directory)

[2013-05-02 11:32:02.485694] W [inode.c:1044:inode_path] (-->/usr/lib/glusterfs/3.2.5/xlator/protocol/server.so(server_resolve+0xf8) [0x7f4534639418] (-->/usr/lib/glusterfs/3.2.5/xlator/protocol/server.so(server_resolve_inode+0x70) [0x7f4534639290] (-->/usr/lib/glusterfs/3.2.5/xlator/protocol/server.so(resolve_loc_touchup+0x105) [0x7f4534638425]))) 0-/var/gluster/wwrd-media/inode: no dentry for non-root inode 184269351: 11a65ece-7b4b-4364-a28c-63df686f5648
</code>
site-var brick log doesnt seem to contain any errors
Comment: Please post which distro, kerenel version, gluster version you are using. Are servers virtual? if yes: ESX, KVM, ??? Thanks
Comment: Ive added the requested information @DanilaLadner
Comment: Please need brick logs as well
Comment: I mean or anything unusual in them.
Comment: Ive added an exert from the site-media brick log which looks fishy and matches with the time of the crash the last line there looks like a possible cause and the others are just symptoms of the crash. The site-var brick log intrigues me as that doesnt seem to have any errors but the mount was broken just the same as the other one @DanilaLadner
Answer: Looking at the logs. It definitely seems like some kind of race condition as there is an intense writing to that folder. There were some bugs reported for these on 3.2.* Gluster Version. I suggest you to upgrade to 3.3.1, which is fully supported on your OS. A lot of bugs and performance issues were resolved. You can also do the upgrade from your version.
Comment: Gluster 3.3 PPA for Ubuntu 12.04 https://launchpad.net/~semiosis/+archive/ubuntu-glusterfs-3.3


Prefetch_related and number of generated queries

Question: I have two models:
class Folder(AbstractName):

    parent = models.ForeignKey('self', blank=True, null=True)
    owner = models.ForeignKey(User)
    typeof = models.ForeignKey(TypeParent, blank=True, null=True)

class File(AbstractName):

    folder = models.ForeignKey(Folder, blank=True, null=True)
    owner = models.ForeignKey(User)
    typeof = models.ForeignKey(TypeChild)

And my folder list (which should display File & folder children, like the explorer file.) generates many queries.
class FolderList(ListView, LoginRequiredView):
    model = Folder

    def get_queryset(self):
        return Folder.objects.filter(owner=self.request.user, parent=None).prefetch_related('folder_set').prefetch_related('file_set')

In my template:
#folder_list
{% include 'core/_folders.html' %}

#_folders
{% if object_list %}
{% for object in object_list %}

{{ object.name }}

        {% for file in object.file_set.all %}

{{ file }}

        {% endfor %}

        {% with filename='core/_folders.html' %}
            {% with object_list=object.folder_set.all %}
                {% include filename %}
            {% endwith %}
        {% endwith %}

{% endfor %}

{% endif %}

Answer: First step: Install django-debug-toolbar so you can see where the queries are being triggered.
Next step: Understand how prefetch_related and select_related work. In a nutshell, select_related does a JOIN query to fetch single ForeignKey models and include them in the results. This gives a slightly longer executing query but is much faster if you're iterating over many items. prefetch_related will work for M2M fields and does the JOIN work in Python code.
Comment: Hi, ddt is alreay installed. But, my select_related doesn't work (model in select_related or model_set ?) Thanks.
Comment: @user3216336 I think you're looking for `.select_related('file')` but you should check if backwards relations work like that because technically it's a one-to-many not one-to-one.


Displaying image from referenced entity in a view

Question: I am trying to create an image albums with the biblio content. These are the steps I have taken:

On the Biblio content type, I added a new field called Image of type Image
Created a new content called Album. Added one field of type Entity reference; and referenced, to the Biblio content, with multiple selection
This is where I'm stuck, creating a view for the albums. I'm not able to display the image content of the biblio entity reference. I have added a relationship to the entity reference: referencing the biblio entity. And added the field Content:Image with a relationship to the biblio entity.

I'm at loss, I know I have a big mistake in the view, but I'm not getting the big picture on how to relate.
Comment: Hi Hicham, welcome to Drupal Answers. Did you use the correct relationship (i.e., in the right direction)? Could you post screenshots of your View configuration?
Comment: Please check the above view configuration screenshot.
Answer: I think you want to display the content of "Album" with the contents reference to "Biblio", first in views follow these steps:

Select the content type of "Album"
Create a relation ship with reference to "Biblio"
Then again select an image in fields and enable the relationship with the same (which you have selected in relationship).
Answer: I think you're reference relationship is in the wrong direction. Using Entity Reference: Referenced Entity as the relationship will provide all fields of the entity (i.e., Biblio content type) that is referenced by your entity reference field (on your Album content type).


Manually changing the color of the dots on a plotted graph

Question: I currently have example code for a PLS-DA plot.
Say if I want to force a change of the colors not by the categorization, but by every three rows from the X data set. So for example, the first three data points (row1-row3) will be blue, then the next three in that X data will be green, and so forth. Is there a way to do that? I know we can use col = c("color1", "color2", etc) as a part of a command, but to my understanding, thats only for coloring the groups.
If there's a clever way to manually change the colors, that would also be super appreciated. I know there's a lot of data points in this example, so an example code just showing the first 3-6 points would be great, cause then I can learn through the rest. (from mixOmics package)
if(!require(mixOmics)) install.packages("mixOmics", repos = "http://cran.us.r-project.org")
suppressWarnings(library (mixOmics, verbose = FALSE))

data(iris)

# Prepare the data
X <- iris[, 1:4]  # Predictor variables
Y <- iris$Species  # Response variable

# Perform PLSDA
plsda <- plsda(X, Y, ncomp = 2)  # Set the number of components as 2

plotIndiv(plsda, ind.names = FALSE, legend=TRUE,
          comp=c(1,2), ellipse = FALSE, pch=16,
          title = "",
          star = TRUE,
          cex = 1.5,
          point.lwd = 1,
          X.label = 'LV1', Y.label = 'LV2')

Comment: Which package is the function `plsda` from?
Comment: @Edward it is from mixOmics. Sorry! Edited it now to fix that part I forgot to add
Answer: It turns out under the hood it's all ggplot, so you can create a grouping column, group by that, and it figures it all out for you:
X$grp <- rep(1:(nrow(X)/3), each = 3)

plotIndiv(plsda, ind.names = FALSE, legend=TRUE,
          comp=c(1,2), ellipse = FALSE, pch=16,
          title = "",
          star = TRUE,
          cex = 1.5,
          point.lwd = 1,
          X.label = 'LV1', Y.label = 'LV2',
          group = X$grp)


Line break in popover/tooltip of kableExtra table in R markdown

Question: I would like to have text in a pop up show upon hovering over a cell of a table. That works, however, I do not manage to get line breaks into that text. My example is adapted from here:https://haozhu233.github.io/kableExtra/awesome_table_in_html.html
---
title: "Line break in popover"
output: html_document
---

```{r echo = FALSE}

knitr::opts_chunk$set(echo = TRUE)
library(kableExtra)

popover_dt <- data.frame(
  position = c("top", "bottom", "right", "left"),
  stringsAsFactors = FALSE
)
popover_dt$`Hover over these items` <- cell_spec(
  paste("Message on", popover_dt$position), # Cell texts
  popover = spec_popover(content = c("line\nbreak", "line<br/>break", "line
break", "line
break")))

kbl(popover_dt, escape = FALSE) %>%
  kable_paper("striped", full_width = FALSE)

```

However, what I do not get to work is to make a line break between line and break in the pop up. I tried \n,
,
, and
. No attempt seems to work. Any idea how to solve that problem?
Comment: Try adding `html: true` in your js, like this: `$('[data-toggle="popover"]').popover({html: true});` then including `` should provide the line break
Comment: @Ben I did, see edited post. However, it still does not work. Did I put the line of course where it belongs? Sorry I have no idea of js. I only used R so far.
Comment: Nope - just add `html: true` to what you have --- here's the whole thing: `` I'll provide an answer to clarify...
Answer: Add html: true to your javascript:

Then
 should provide a line break.
Answer: You could add custom css styling to the document, see this solution :
---
title: "Line break in popover"
output: html_document
---

```{css, echo=FALSE}
div {
  white-space: pre-wrap;
}
```

```{r echo = FALSE}

knitr::opts_chunk$set(echo = TRUE)
library(kableExtra)

popover_dt <- data.frame(
  position = c("top", "bottom", "right", "left"),
  stringsAsFactors = FALSE
)
popover_dt$`Hover over these items` <- cell_spec(
  paste("Message on", popover_dt$position), # Cell texts
  popover = spec_popover(content = c("line\nbreak", "line<br>break", "line
break", "line
break")))

kbl(popover_dt, escape = FALSE) %>%
  kable_paper("striped", full_width = FALSE)

```


In Ubercart, can I make a "View Cart" link appear only when an item is in the user's cart?

Question: Ubercart is only a small part of our site and we only want the default cart block to appear when a user is in that shopping section. Simple enough to do with "Show block on specific pages" rules.
However, when a user navigates away from the ubercart section, the cart block disappears, but I would still want to denote that the active cart exists. I don't want users to think their cart has completely vanished.
Preferably it would be a simple, tiny "View my cart" link to the default Ubercart cart page in the Header Block region. Or even added to the end of the main site navigation menu.
So, to reiterate, how can I make a Block (or menu link) render only when an item is placed in a user's cart?
Answer: Create a block with your "View Cart" html code then set block visisbility to "Pages on which this PHP code returns TRUE (experts only)" with the following:
<code><?php
$items = uc_cart_get_contents();
if (count($items) > 0) {
  return true;
}
return false;
?>
</code>


Entity Framework Generate Database Schema (SQL) with Default Table Values

Question: I am using EF 5 and SQL Server 2005, Model First (sort of).
By sort of, I mean that I typically build my schema in the SQL Server designer, but import the schema into EF so I have a visual view. There is often round-tripping.
However, I noticed that when I try to generate the DB schema based on the EF model, it skips all of the NEWID() default values that I have assigned as default values to my Guid IDs, but it doesn't skip the identity fields of type int.
I found this post explaining the reasoning for this:
Entity Framework 4 and Default Values
However, it doesn't answer my question: How do I get Entity Framework to generate a SQL DDL database schema with default values of NEWID() for my uniqueidentifier types?
NOTE:
I don't care about how to set them from the POCO entities and so forth (there are plenty of posts describing that) - my concern is getting the SQL DDL generated right so I can seed the database without worrying about these values going missing.
Answer: Using Entity Framework Migrations, you can use the GUID column builder and its DefaultValueSql parameter. The value of that parameter can be the string "NEWID()". This should take care of proper DDL generation.
Next you should declare these properties as database-generated using attributes or the fluent model builder, so that EF ignores the values set in your POCOs (which will be null for new objects).
Comment: Thanks. Entity framework migrations is for code first, so I am not sure if it will help anyone who comes across this question. I ended up switching to code first several months ago anyway and more recently to code first migrations. +1 for your effort, but will only accept an answer that is for model first as the correct one.
Comment: You're right, we switched so long ago I didn't even realize. Oh well ;).


Triangle Inequality Theorem

Question: I'm trying to understand the triangle inequality theorem and part of proof contains $$2\textrm{Re}(\left<a|b\right>) \leqq  2\left|\left<a|b\right>\right|.$$ Can someone show me how this is so?
Comment: Would [math.se] be a better home for this question?
Answer: The result of the inner product $\left<a|b\right>$ is a complex number, so let's write it as $c+id$.
$$\textrm{Re}(c+id) = c$$
$$\left|c+id\right| = \sqrt{c^2 + d^2}$$

Triangle Inequality Theorem


Distribution of largest sample from normal distribution.

Question: Given $n$ independent random variables $X_i$ with normal distribution, mean $\mu$, variance $\sigma^2$, what is the distribution of $\max\limits_{i=1}^n(X_i)$ ?
In particular I am interested in whether it would be Normal or close to Normal as well, and what the mean and variance would be.
Answer: The random variable $Z = \max_{i=1}^n(X_i)$ is known as order statistics, and is sometimes denoted as $X_{n:n}$.
The cumulative density function of $Z$ is easy to find:
$$
   F_Z(z) = \mathbb{P}\left(Z \leqslant z\right) = \mathbb{P}\left(\max_{i=1}^n(X_i) \leqslant z\right) = \mathbb{P}\left( X_1 \leqslant z, X_2 \leqslant z, \ldots, X_n \leqslant z\right)
$$
using independence:
$$
   F_Z(z) = \left(F_X(z)\right)^n
$$
Thus the density function is
$$
    f_Z(z) = n f_X(z) F_X^{n-1}(z)
$$
In particular, it follows that $Z$ is not normal.
Expected values of $Z$ are known  in closed form for $n=1,2,3,4,5$ (asking Mathematica):
<code>In[31]:= Table[
 Mean[OrderDistribution[{NormalDistribution[m, s], n}, n]], {n, 1, 5}]

Out[31]= {m, m + s/Sqrt[Pi], m + (3 s)/(2 Sqrt[Pi]),
 m + (6 s ArcTan[Sqrt[2]])/Pi^(3/2),
 m - (5 s)/(2 Sqrt[Pi]) + (15 s ArcTan[Sqrt[2]])/Pi^(3/2)}
</code>
Large $n$ asymptotics is discussed here.


how to list all Domain Controllers in a forest based on domain name given using java?

Question: For a domain name given, need to list out all the Domain controllers that can be contacted. currently i am able to get only DCs for the domain i am connected right now. Some one can help me with this using JAVA?
Comment: What have you written so far? What parts work? Which do not work? Are there any errors?
Comment: No errors i discovered dcs for the domain my machine connected. but unable to discover dcs for other domain in the network.
Answer: Finding the list of domain controllers for an Active Directory domain is a task that can be accomplished in several ways, of which the main ones are DNS and LDAP queries; if you are developing a Windows application, there also various API calls that can help you with that.
If you want to do this from Java, there are no native APIs you can use; thus you'll have to implement in Java one of the other available methods. A LDAP query would probably be the easiest solution.

Update:
You said in your comment you want to find DCs for any domain, given the domain name; in this case, a LDAP query could not be feasible if you can't log in to the target domain (i.e. there is no trust relationship with it and you don't have a valid user account for that domain). This leaves only DNS queries as a valid solution, assuming of course you have DNS resolution in place for the target domain.


Survivor function for log-normal from flexsurvreg output

Question: I am trying to plot/generate a survival curve in Excel using the output from flexsurvreg in R. The below is a snapshot from R with the corresponding estimates (y axis values) for the time (x axis values). What I am trying to workout here is to find the formula (survivor function) so that I can utilise the meanlog and sdlog est, and input them in the formula with the x time to derive the survival probability (est). Any help is greatly appreciated, thanks.
I have the below formula but couldn't seem to work it out. What do I use in Excel for Φ, mu and sigma?

> model <- flexsurvreg(Surv(times_start, times_end, type="interval2")~1, dist="lnorm")
> model
Call:
flexsurvreg(formula = Surv(times_start, times_end, type = "interval2") ~
    1, dist = "lnorm")

Estimates:
         est     L95%    U95%    se
meanlog  2.6263  2.4568  2.7957  0.0864
sdlog    1.1380  0.9969  1.2991  0.0769

N = 225,  Events: 0,  Censored: 225
Total time at risk: 2734.501
Log-likelihood = -497.8637, df = 2
AIC = 999.7274

> summary(model)

      time       est       lcl       ucl
1   0.0001 1.0000000 1.0000000 1.0000000
2   0.7500 0.9947757 0.9871133 0.9981939
3   1.5000 0.9745022 0.9556606 0.9870252
4   2.2500 0.9446680 0.9165437 0.9666503
5   3.0000 0.9102695 0.8754248 0.9395832
6   3.7500 0.8741708 0.8355812 0.9097379
7   4.5000 0.8379620 0.7962243 0.8778450
8   5.2500 0.8025201 0.7585844 0.8444564
9   6.0000 0.7683175 0.7223318 0.8122682
10  6.7500 0.7355924 0.6877659 0.7821786
11  7.5000 0.7044459 0.6558354 0.7534993
12  8.2500 0.6748975 0.6243500 0.7261655
13  9.0000 0.6469193 0.5961911 0.7004432
14  9.7500 0.6204563 0.5685930 0.6745498
15 10.5000 0.5954384 0.5421064 0.6514573
16 11.2500 0.5717888 0.5174307 0.6294487
17 12.0000 0.5494284 0.4940210 0.6070700
18 12.7500 0.5282787 0.4725858 0.5865717
19 13.5000 0.5082639 0.4512857 0.5665737
20 14.2500 0.4893115 0.4324061 0.5480763
21 15.0000 0.4713531 0.4137265 0.5301801
22 15.7500 0.4543244 0.3964777 0.5132348
23 16.5000 0.4381654 0.3790013 0.4982930
24 17.2500 0.4228201 0.3625291 0.4830236
25 18.0000 0.4082367 0.3475374 0.4685829
26 18.7500 0.3943669 0.3337319 0.4543229
27 19.5000 0.3811658 0.3201412 0.4416411
28 20.2500 0.3685921 0.3072418 0.4293680
29 21.0000 0.3566073 0.2954934 0.4172957
30 21.7500 0.3451756 0.2846739 0.4057205
31 22.5000 0.3342639 0.2731213 0.3949677
32 23.2500 0.3238415 0.2629543 0.3839551
33 24.7500 0.3043525 0.2441482 0.3647242
34 26.2500 0.2865035 0.2271337 0.3464885
35 27.7500 0.2701166 0.2116445 0.3297161
36 29.2500 0.2550376 0.1965890 0.3142766
37 30.0000 0.2479457 0.1895891 0.3073740
38 34.5000 0.2107609 0.1563823 0.2693629
>

Answer: I've just done exactly the same thing. Through trial and error I figured it out. In Excel, you can use:
1-lognormdist(t,meanlog,exp(sdlog))
I don't know why you have to exponentiate sdlog and not meanlog, but this produces the same survival predictions as R. Hope this helps :)
Comment: This doesn't appear to work for me when I test it. However simply `1-LOGNORMDIST(A1, 2.6263, 1.1380)`  does appear to work (where A1 is the time column)
Comment: Or alternatively you can use: `1-NORM.DIST(LN(A3),2.6263, 1.138, TRUE)`
Answer: If you don't care about the formula and all you want is the predicted survival probability, you could just use the predict() method. Alternatively, if you are inlcluding covariates and you want the marginal survival probability for some covariate values you could use g-computation with the predict() method, or use implementations in packages like the adjustedCurves or contsurvplot packages.


Red Hat installation on HP ProLiant does not detect hard drive

Question: I have an HP ProLiant BL460C Gen8 having real hardware RAID.
I am trying to install Red Hat Enterprise x86_64 bit on an HP ProLiant (iLO 4) server with an Array of 2 hard drives configured as RAID1.
The built in server manager (intelligent provisioning
) allows me to change the setting and configuration of the storage array between RAID0 and RAID1
But RED HAT starts the process of the clean install, and i get to select the time, language, etc. but it stops because it could not detect a storage disk. All it can see is the virtual boot drive that it creates while booting to allow it to run (capacity 256 MB).
I tried to manually/custom add the storage setting but again, all available storage is 250 mb and all found devices is 1.
What am I doing wrong?
Comment: Can you clarify which specific RAID controller is installed in this system? Can you also tell us which version and release of Redhat Linux you're trying to install?
Comment: No response to this?
Comment: @ewwhite I found another version that had no issues with the hard drive
Comment: Another version of what?
Comment: Another version of Red Hat. @ewwhite
Comment: Please share the details.
Comment: @ewwhite I installed Red Hat 6.3 instead of 6.0 and it recognized the hard drive with no problems
Answer: HP ProLiant server hardware evolves throughout the lifecycles of long-running Operating System distributions like Red Hat Enterprise Linux.
In your original post, I specifically asked what version of RHEL you were attempting to install. This is important information because Red Hat 6 was introduced well before Generation 8 ProLiant servers. There are standards that apply and also an extensive and annotated HP/RHEL compatibility matrix that provides guidance on what combinations of hardware and OS work properly.
For your specific case, you need at least RHEL 6.1 in order to use this server.

A larger issue here is trying to install old software on modern equipment. RHEL 6.0 is from 2010. It's 2015 now. In your comments, you mentioned installing RHEL 6.3. That's from 2012. Also a bit of a bad choice.
Is there any reason you're not using the current release of Red Hat?

Also see: RHEL 5.5 server has most devices listed as "Unknown Device"
Comment: @AhmadAl-Mutawa It is not acceptable to run an out of date release of RHEL unless you have an extended update support contract for that server. It puts you at risk due to the lack of drivers, critical bug fixes and security updates.
Comment: That answer is very well organized and conclusive. I don't have the decision to choose which version of RH to Install. There are requirements by another team to install 6.0, we told them it wont work so they accepted to install 6.3
Comment: @MichaelHampton thanks. I will forward this to our DBA. Much appreciated.
Answer: The RAID controller should present the virtual volume to the BIOS once it's configured. If you go into the BIOS do you see the volume listed in the list of boot devices? If not then there's a problem with the raid configuration.
If the volume is visible in the BIOS then the problem is probably related to missing drivers (although that's unlikely for something as common as HP RAID config). One thing to try is to boot from a Live CD and see if that can detect the volume.
Comment: The boot sequence/order menu does not show hard drives among possible options. Does that mean: I need to install drivers? If so, then is there a step-by-step procedure to do that? Advanced thanks
Comment: If the raid controller came with the system then you should absolutely not need any drivers for the BIOS to see the volume. Has this system ever had an OS on it using that same raid controller? Have you made sure that you've followed all of the steps for the raid config, especially initializing the volume after creating it?
Comment: Depending on your hardware this guide might be useful: http://h20000.www2.hp.com/bc/docs/support/SupportManual/c01608507/c01608507.pdf (especially pages 43-46)


Using Checksum and XOR together

Question: Please have a look at the SQL below:
<code> create table ChecksumTest (id int not null identity, string1 varchar(10),
string2 varchar(10), string3 varchar(10), string4 varchar(10), checksumvalue int)

insert into ChecksumTest (string1,string2,string3,string4) values ('Ian', 'Marie', 'Sharon', 'Mark')
insert into ChecksumTest (string1,string2,string3,string4) values ('Steven', 'Robert', 'Amy', 'Andy')
insert into ChecksumTest (string1,string2,string3,string4) values ('Sharon', 'Mark','Ian','Marie')

select distinct checksum1 ^ checksum2 As xor from (
select CHECKSUM(string1,string2) as checksum1, CHECKSUM(string3,string4) as checksum2
from ChecksumTest) As Checksums
</code>
The select statement returns two distinct XOR values because row one and row three in the table contain the same values.  This is what I expect.
I have run the SELECT statement across about one million rows and the number of distinct XOR values is less than I thought.  I realise that CHECKSUM is not always unique, but is it safe to use it like this when two different CHECKSUM strings (with multiple parameters e.g. CHECKSUM (String1, String2) can generate the same XOR value?
Is it safer to concatenate the strings together like this: CHECKSUM (String1 + String2) or perhaps a binary CHECKSUM?
Update
Every combination of four values contains two rows:
Row1: String1, String2, String3,String4
Row 2: String3,String4,String1,Strin2
I only want to return one row for each combination.
Comment: What are you trying to accomplish?  Fast comparison of different rows?  How many fields are you considering?
Comment: You may have a look at http://www.sqlservercurry.com/2009/06/generate-hash-value-using-sql-server.html to build a hash value. But only concatening the strings can lead to same hash with different values, so you have to use a delimter
Comment: @Sir Rufo, thanks.  Could you explain what adding a hash value will achieve? Will it be unique for every row?
Comment: Hash values are big checksums and can be seen as unique in most cases.
Comment: @Gordon Linoff,thanks.  I have updated my question.  Does it make the problem any clearer?
Answer: My solution was found here: How to do bitwise exclusive OR in sql server between two binary types?.  It involved splitting every 8 bytes into binary(8).

Using Checksum and XOR together


Somar valores de uma coluna na tabela

Question: Preciso selecionar os 3 usuários com maior receita. Antes na tabela cde_usuario havia uma coluna chamada qtdreceita, sendo bem simples de fazer essa consulta, utilizava esse sql:
<code>$sql = "SELECT * FROM cde_usuario ORDER BY qtdreceita DESC LIMIT 3";
</code>
Porém, essa coluna foi removida, pois agora existe a tabela cde_venda_detalhe, sendo umas das colunas id_cliente e valor. Agora preciso somar todos os números da coluna valor de todos os clientes com compras, e no final selecionar os 3 clientes que resultaram no maior valor.
Sei que para somar o valor total de todas as compras de um usuário específico é assim:
<code>$sql = "SELECT SUM(valor) as total FROM cde_venda_detalhe WHERE id_cliente = $idCliente";
</code>
Porém não sei como "unir" esses SELECTs, se alguém puder me ajudar agradeço.
Answer: Avalie se é isto o que deseja:
<code>SELECT id_cliente, SUM(valor) as total FROM cde_venda_detalhe GROUP BY id_cliente ORDER BY total DESC LIMIT 3;
</code>
Comment: Sim, funcionou perfeitamente, obrigado!

Somar valores de uma coluna na tabela


Onde ficam armazenados os objetos criados em Python?

Question: Fiz um pequeno script para registrar dados dos alunos onde trabalho. Eu consigo instanciá-los e consigo ver os dados logo após. Mas, após sair do programa, estes dados se perdem.
Estes objetos só ficam armazenados na memória enquanto o programa está aberto? Eu teria que criar um dicionário dentro do programa para armazenar estes dados? Pode parecer uma pergunta simplória, mas não consigo achar resposta.
Segue abaixo o construtor que criei:
class Diploma:

    def __init__(self):

        self.nome = input("Aluno: ")
        self.curso = input("Curso: ")
        self.registro = int(input("Registro: "))
        self.sistec = input("SISTEC: ")
        self.livro = int(input("Livro: "))
        self.pagina = int(input("Página: "))

Logo após seguem os getters e setters.
Comment: Objetos são sempre criados em memoria, se os quer persistir precisa de os guardar em algum lado como banco de dados ou arquivo. Agora se a pergunta é se o objeto que representa cada diploma se perde enquanto o programa está a executar, já tem a ver com o seu código e se você o guarda em alguma coleção
Answer: Sim, todos os objetos criados somente existem na memória RAM, e a mesma é desalocada quando se fecha o programa. Se quiser persistir os dados, é necessário armazená-los em um tipo de armazenamento persistente, como o HD ou o SSD.
Porém, estas formas de armazenamento não armazenam objetos, e sim bytes, sendo assim, é necessário converter os objetos que você quer armazenar em bytes, de uma forma que seja possível convertê-los novamente de volta nos objetos em um outro momento da execução do programa. Esse processo é chamado de serialização.
Existem vários módulos para auxiliar neste armazenamento, de funções simples de manipulação de arquivos até ORMs que são modelos relacionais de objeto, podendo armazenar em um banco de dados com serialização automática dos objetos.
No caso da sua classe, você colocou a leitura dos dados a partir do usuário, no __init__ - isso não é muito prático, pois significa que a sua classe não pode ser instanciada sem pedir dados para o usuário. Seria ideal mover a leitura do usuário para uma função separada, para facilitar a leitura dos dados de outro lugar que não seja input.
Outro detalhe é que você mencionou getters e setters porém no python eles não são uma boa prática como no java. Você os usa raramente em forma de property, mas só quando eles forem realmente necessários.
Finalizo a resposta com um exemplo simples para armazenar sua classe em um banco de dados SQL usando a biblioteca sqlalchemy:
from sqlalchemy import create_engine, Column, Unicode, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///escola.db', echo=True)
Base = declarative_base(bind=engine)
Session = sessionmaker(bind=engine)

class Diploma(Base):
    __tablename__ = 'diplomas'

    id = Column(Integer(), primary_key=True)
    nome = Column(Unicode(200))
    curso = Column(Unicode(200))
    registro = Column(Integer())
    sistec = Column(Unicode(200))
    livro = Column(Integer())
    pagina = Column(Integer())

    @classmethod
    def ler_do_usuario(cls):
        d = cls()
        d.nome = input("Aluno: ")
        d.curso = input("Curso: ")
        d.registro = int(input("Registro: "))
        d.sistec = input("SISTEC: ")
        d.livro = int(input("Livro: "))
        d.pagina = int(input("Página: "))
        return d

Base.metadata.create_all()

if __name__ == '__main__':
    s = Session()
    # cria um diploma a partir do usuario:
    d = Diploma.ler_do_usuario()

    #armazena o diploma no banco de dados:
    s.add(d)
    s.commit()

    # le o primeiro diploma a partir do banco de dados:
    d2 = s.query(Diploma).get(1)
    print(d2.nome)


Interest rate compounded continuously (pre-calculus)

Question: (a) Suppose you deposit $P$ dollars into a bank that pays an interest rate $r$ compounded continuously. How long does it take to double your original deposit $P$.
(b) Suppose you deposit $P$ dollars into a bank that compounds interest continuously. What is the interest rate $r$ that doubles your original investment $P$ after the first year.
The equation for continuous compound interest is $A = Pe^{rt}$ where $P$ = principal value, $r$ = interest rate per year, $t$ = time in years, $A$ = amount, and $e$ = the mathematical constant $e$
I've been working on this question for hours now, but I don't know if the answers I got are correct so I would appreciate some confirmation
The answer I got for a. is $t = (\ln2A/P)/r$
The answer I got for b. is $r = (\ln2A/P)/t$
Comment: Indeed, you should start by setting $A = 2P$ to represent doubling your investment.  Then $A/P$ simplifies to just $2$.  You should also learn how to format your questions so that they are more readable.
Comment: The amount A is just 2P for case (a). You're solving Pe^(rt) = 2P so t = (ln 2)/r.
Comment: Presumably in (b) you have $t=1$
Answer: EDIT1:
a. Time to double the principal P:
The results  you obtained after infinitesimal time compounding in exponential form is correct. Now after cancelling $(A,P)$ magnitudes its quotient is 2,
$$e^{rt}=\dfrac{A}{P} =2$$
or simply (you need to plug in A/P value!)
$$ rt =\ln2,\, t=\dfrac {\ln 2}{r}  $$
b. Humongous interest rate to double the principal in one year itself
Now doubling the principal in one year needs an exorbitant charging (so least it deserves is representation with a capital $R$!)
$$ e^{\,1\cdot R}= \dfrac{A}{P}= 2 \rightarrow R = ln\,2 \approx 0.69315 $$
so the rate  of interest would be a whopping
$$ R \approx 69.315\text{ % }.$$
Comment: In question a) the question is time, not interest rate, so in the last step you need t = ..., not r = ... .
Comment: Thanks, fixed it,


Was the proposed swimming caps for black hair rejected by the International Swimming Federation because it provides some unfair performance?

Question: I read on https://www.theguardian.com/sport/2021/jul/02/swimming-caps-for-natural-black-hair-ruled-out-of-olympic-games-alice-dearing (mirror):

International Swimming Federation rejects use of Soul Cap, saying it does not 'fit the natural form of the head'. Swimming caps designed for natural black hair created by a black-owned brand will not be allowed at the Olympics.

Was the proposed swimming caps designed by Soul Cap for natural black hair rejected by the International Swimming Federation on the grounds that it provides some unfair performance, or simply because of how it looks like? If the latter, why would the International Swimming Federation care about how a swimming cap looks like?
Answer: FINA have had regulations since 2017 (or maybe earlier) which specify that

The shape [of the cap] shall follow the natural form of the head

(Section 4.3.1) You can see reason for this - they don't want caps which  do in fact give a dynamic advantage (see teardrop-shaped helmets for time trial cyclists, etc). If you are being excessively pedantic, you could argue that the Soul Cap does not follow the natural form of the head as voluminous hair itself does not follow the natural form of the head; therefore it is in breach of the regulations and should be banned.
This argument is (in my never humble opinion) a very silly argument for FINA to be making. The Soul Cap is clearly within the spirit of the rules and FINA should have found a way to allow it.
(Update as of September 2022: FINA found a way; the Soul Cap is now competition legal)


Which ANOVA test to use in this experimental design?

Question: I have an experimental design as follows:
Three groups of cakes: treatment A, treatment B, control;
Three replicates per cake.
They are observed during 10 days for microbial growth.
My interest is in evaluate their resistance to microbial growth, that is, if they differ in the amount of microbial growth during the experiment.
My question is:
To evaluate that which statistical analysis strategy must I use? (and would you check my suggestions of R code as well for the given options?)

two-way ANOVA (cake treatment (means of replicates) vs. days);
[equivalent in R: microbial_amount ~ treatment*days]
three-way ANOVA (cake replicate vs. cake treatment vs. days) or
[equivalent in R: microbial_amount ~ treatment*days + replicate]
Another type of ANOVA (nested ANOVA, repeated measures ANOVA, I'm not sure yet...)
Answer: I wouldn't use any kind of ANOVA.  I would use a multilevel model or possibly generalized estimating equations.
If you, for some reason, have to use an ANOVA, then repeated measures is the only reasonable one, but it makes unrealistic assumptions.
Comment: Thanks for the quick reply, Peter! Would you please clarify why ANOVA is not the best option in this case? I never used multilevel models... What should I take into account if I am to choose between a multilevel model and generalized estimating equations?
Comment: Regular ANOVA is wrong because it assumes that the errors are independent and yours will not be.  RM ANOVA is not wrong, but it assumes sphericity, which is almost never there.  GEE vs. MLM is complicated. See http://stats.stackexchange.com/questions/16390/when-to-use-generalized-estimating-equations-vs-mixed-effects-models


Busca em tempo real economizando servidor?

Question: Olá, criei um script em jQuery que efetua consulta no banco de dados, baseando-se no que a pessoa digitou em um campo input. A cada tecla que o usuário digita, o script faz um novo requerimento para a minha API e isso é um problema, já que pretendo contratar uma hospedagem barata. Portanto, eu queria saber como posso melhorar o seguinte script para que não precise ficar perguntando toda hora pro servidor e gastando os recursos do servidor que pretendo contratar:
$(document).ready(function() {
    $('#input').keyup(function(event) {
        var t = $('#input').val();
        $.getJSON('api', {word: t}, function(json, textStatus) {
            // Em caso de sucesso, essa função será ativa
        });
    });
});

Comment: Qual é a quantidade de registros no banco de dados que o servidor pode retornar? Se não for muito grande, você pode transferir todos na primeira requisição e apenas filtrá-los com o JavaScript.
Comment: O site que estou desenvolvendo é um site de conteúdo dinâmico, ou seja, sempre terão novas atualizações, consequentemente um banco de dados grande...
Comment: Então você pode estipular um mínimo de caracteres para começar a buscar no banco e refazê-la a cada 2 ou 3 novos caracteres.
Comment: cria uma função `on click` em vez de `keyup` e assim a consulta só será feita quando o usuário acabar de digitar e clicar num botão, ou clicar `enter` para avançar.
Comment: Você quer reduzir o número de consultas ao servidor, mas não disse os criterios que precisam ser seguidos para isso. Existem várias formas de reduzir o número de requisições, algumas vão te atender muito bem, outras não tão bem. Lembre-se que se você chega ao ponto de prejudicar a usabilidade do usuário para ganhar performance, você está fazendo errado. Se não tem mais o que melhorar (sem prejudicar o usuário) no código, então você tem que contratar mais hardware ou buscar outras tecnologias. E não se engane, os bancos de dados suportam muito mais "tranco" do que você imagina.
Comment: [Essa solução](https://pt.stackoverflow.com/a/210855/11886) serviu para você @AndersonSantos ?
Answer: Cria uma função on click em vez de keyup e assim a consulta só será feita quando o usuário acabar de digitar e clicar num botão, ou clicar enter para avançar com a pesquisa.
$(document).ready(function() {
    $('#botao-pesquisar').click(function(){
        var t = $('#input').val();
        $.getJSON('api', {word: t}, function(json, textStatus) {
            // Em caso de sucesso, essa função será ativa
        });
    })
    $('#input').keypress(function(e){
        if(e.which == 13){ // Tecla Enter primida
            $('#botao-pesquisar').click(); // Dispara o evento click no botão de pesquisa
        }
    });
});

Pode não ser a maneira mais perfeita, mas já reduz consideravelmente a consulta constante em cada tecla primida.


IOS/Objective-C: retrieving ManagedObjectID within loop error

Question: I am having trouble setting and retrieving a managedObjectId within a loop.  First problem, I can't find in the docs what the parts of the MOID mean.  So first question, are the following moids unique? The only way that they are different is in the last digit after the entity name, Item. If not, that could be the issue.
0xd000000054200000 <x-coredata://10EC1628-A6D4-487B-BF5C-61EAD9838132/Item/p5384>
0xd000000054240000 <x-coredata://10EC1628-A6D4-487B-BF5C-61EAD9838132/Item/p5385>

Second question, if they unique, when I retrieve the record associated with these ids, I end up retrieving the same record. So maybe there is a problem in the loop below.
Here is my code simplified slightly as there is a sync to server that I have not included.
//NSArray * myItems is an array of items to be saved
 for (i=0;i<max;i++)
 {
     currentItem = myItems[i];
     // Create Entity
     NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:self.managedObjectContext];
    // Initialize Record
        NSManagedObject *record = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
        // Populate Record
        [record setValue:currentName forKey:@"name"];
          // Save Record
        NSError *error = nil;
        if ([self.managedObjectContext save:&error]) {
            //Set moID in ivar of saved record
           self.moID = [record objectID];
[self syncAndMarkSynced];
}
}//close loop

-(void) syncAndMarkSynced{
//sync to server omitted
 Items *object = [self.managedObjectContext objectRegisteredForID:self.moID];
object.synced = @1;
}

Answer:
First problem, I can't find in the docs what the parts of the MOID mean.

That's because they are not documented. The object ID is unique; the details are not explained because the parts of the URI are not intended to be meaningful on their own.

Second question, if they unique, when I retrieve the record associated with these ids, I end up retrieving the same record.

That's expected. A managed object has a unique ID. When you look up a managed object by ID, you're requesting the same entry from the persistent store. Each entry has a unique ID, so if you use the ID, you get that entry.

So maybe there is a problem in the loop below.

It's not clear to me what the loop is trying to do. Hopefully the information above will help you work it out.
Comment: Are the two ids shown above the same or are they different?  I would have thought if different they would have a very different set of characters, but they differ only in the last digit.  Second, unless, I am misunderstanding something, I would think that a unique MO id would return a unique MO.  Instead, giving it two different MOIDs--if the two ids above are different--I get only one (identical) MO.  I guess I should double check, a managed object is the same as a record, correct?
Comment: "Record" is not a term used in Core Data, but in general a single managed object corresponds to a single SQLite record. Any chance you just have two managed objects with identical fields? That's what your symptoms seem to indicate.
Comment: No.  absolutely different MOs.  They display as two different items with different names etc. in tableview and detail view.  Can you clarfiy that the two objectids above are in fact different:  vs. . Note they differ only in p5384 vs. p5385


Forbidden/shunned harmonic progressions in 18th cent. counterpoint

Question: I'm going through Kent Kennan's book on 18th century counterpoint, and early on he touches upon some finer points concering agreeable or not-so-agreeable chord progressions. Only a handful of progressions, I gather, are considered "bad" — so weak as to be entirely avoided, perhaps:
Note: there is no distinction made by Kennan between major and minor here, I think (?), major is only suggested for the sake of convenience.

V to IV, both chords in root progression — because this progression is "generally heard as a reversal of normal harmonic progression" (p. 24, 3rd edition) — alright, fine.

ii to I, also when both are in root position. No reason explicitly given, for why this is weak. "The ii should either progress to a V before going to I or move to a I 6/4 if a cadence is involved" (p. 24). I suppose this may be a variant of the "V - IV" rule. Can this be confirmed? Anything more to say on the matter, besides the notion of a "reversal" of normal harmonic evolution?

The first inversions of the vi and iii chords (vi6 and iii6): to be avoided unless one uses them by way of a stepwise bass: "Employed in that way [with the bass passing stepwise], they do not actually express the degree function of vi or iii but are what might be called "contrapuntal chords." (p. 24)

Not an explicit reason provided for the third rule, either. And this is the more intriguing one. Are there any underlying principles that can be elucidated here, beyond what were the conventions established by Bach?
I would guess that this has something do with the vi6 chord and the iii6 chords being so similar to root position I and V chords, respectively, sounding like embellishments of them. But it seems like there's something more to be said here. Is the "stepwise bass"-exception tied to more specific voice leading figures, similar to the various "passing 6/4-chord" idioms that also apply to this style? I intuit that this is so, but Kennan doesn't go into any further details.
Comment: On point 1, there's a fabulous instance of the progression `V7 IVmaj7 I6/4 V I` in Handel's Solomon (I suppose the penultimate chord is V7 but I don't remember).  Yes, it's unusual, but it was far from forbidden.  Also I would take issue with "established by Bach" -- these practices were established long before Bach.
Comment: Yes of course — I think I apprehend Kennan's presentation of "do", "do not" "do sometimes, in some circumstances", etc., as more or less leaning on Bach as a final arbiter, of the strictures of the style in question. Not least when arriving at fine-grained details such as the viabilty of a vii6 chord. So, "conventions" here could even mean an easing up of stricter practices established in earlier times, I guess.

I'll look into the Handel tip! Yes, it seems reasonable that "V - IV" and so on would be only unusual and/or uncharacteristic, not "anathema" to a rich and varied musical epoch.
Comment: Solomon is long.  The progression I have in mind is the final cadence of _Praise the Lord With Harp and Tongue,_ which is near the end, or, if you've got the John Eliot Gardiner or Thomas Beecham recording, _at_ the end.
Answer: Your intuition is exactly right on all fronts!

Yes, ii not moving to I in this style is similar to the guideline forbidding V moving to IV. Since ii has predominant function, it wants to move to the dominant (hence "predominant," or "before the dominant"). Moving to I bypasses this dominant function and confuses the role of this ii chord. (IV is also a predominant, which is why it coming after V is so rare in this style.)

As you surmised, the first-inversion vi is too close to I and the first-inversion iii is too close to V; they often come across as being one of those chords but with a wrong note somewhere. They can, however, be used as contrapuntal chords.

The only other instance I can think of where I may encounter a vi6 that isn't a part of a larger prolongation of vi would be around the nexus point of a common-chord (or "pivot-chord" modulation). Here, it's common for, say, the vi6 of a major key to become a ii6 in a modulation to the dominant. But because it's approaching a modulation, composers seemed to feel comfortable using it.
Comment: Thanks! I remain slightly puzzled, though, about how one thinks of a situation where vi6 (for instance) is used as a "contrapuntal" chord. If we are in C major, and the bass goes either B - C - D or  D - C - B (i.e. passing over the third factor of vi), I suppose we are very likely to be in some dominant configuration on the first note in both scenarios. The bass goes B - C - D, corresponding to v6 - vi6 - ii, for instance. What does it mean for vii6 to be a "contrapuntal chord" here, exactly? Is this a term that enters in light of our inability to call the chord either "I" or "vi"?
Comment: And, what does careful stepwise movement do, exactly, in relation to the problem of having a chord sounded which the ear takes as "5/3 tonic with a wrong note to it?" I think I almost have this in hand — at the tip of the tongue, so to speak — reflecting on the label "contrapuntal".. But I can't quite seem to reach a strong formulation of it, for myself!
Answer: As well as Richard's explanation; there are possible parallel fifths and octaves in moving V to IV in root position; one can easily go move from V6 to IV6 though. Most stepwise motions of 63 chords are fine


SQL Insert without knowing all of the values for a new row

Question: I have a table with 5 columns and I'd like to insert a new row. The problem is, I do not yet have the values for all 5 columns.
Is it possible to add information to the first and third columns and add the rest later?
This is not referring to a specific database management system. I'd just like to know if it's possible.
Comment: Yes, you can set the columns that you want to leave empty to be nullable. Then you can insert a new row with their values set to NULL. When you have the values for them you can just run an update query.
Comment: Yes it is possible to insert only first and third columns if remaining columns are nullable then you could use null for those columns while inserting and update them later when you get the actual values for these columns.
Comment: `insert into the_table (column_two, column_five) values ('two', 'five');`
Answer: It depends on your table definition, if column accept null value you don't have to provide a value for it in insert statement.
Answer: It depends on table definition.
Some tables require value by design, other not.
It is also worth to mention, that database may be configured to throw error when required fields are not set. In other cases there is only warning and fields are initialized by NULL value despite being defined as "NOT NULL".
Some of fields cannot be omitted at all. Those are mainly primary key fields.
Answer: Technically, it's not.
However, you can insert dummy values (like NULLs or defaults) into the problem columns and then update them later when you know the correct values.
Answer: Yes u could do that as follow (MS SQL Server):
CREATE TABLE #TM
([ID]   INT IDENTITY(1, 1),
 [Col1] INT,
 [Col2] VARCHAR(MAX),
 [Col3] VARCHAR(MAX),
 [Col4] VARCHAR(MAX),
 [Col5] VARCHAR(MAX)
);
INSERT INTO #TM
([Col1],
 [Col3]
)
       SELECT '1',
              '2';

Later, you could update the Data in rest of columns with help of ID Column (i.e. unique identity column) which is auto increment.
However, it would insert NULL values in other columns which are not defined in column list.


Arithmetic Progression of 3 numbers which are neither multiples of 2 nor 3

Question:
$a, b, c$ are three numbers in AP which are neither multiples of 2 nor multiples of 3. Obtain an expression for the common difference of these three numbers.

This question came in a test today (it was an MCQ along the lines of which one of these options is a possible value of common difference, but I forgot the options).
I am clueless on how to formally solve this. To start off, $a,b,c$ belong to the set $S = \{x : x \not\equiv 0 \ \mathrm{mod\  2}, x \not\equiv 0 \ \mathrm{mod\ 3} \}$. I now have to find two numbers $a, c$ in $S$ such that $\frac{a+c}{2} = b \in S$. I could not proceed beyond this step. Any hints/solutions are appreciated.
Comment: You can easily show that the common difference must be a multiple of $6$.
Comment: @Peter nevermind, got it. Thanks! I'll write an answer up for this now.
Comment: @Peter how so? can you elaborate a bit more?
Comment: Begin with the eaiser part. What, if the common difference is odd and the first number is odd as well ?
Comment: As peter said : $(6k-1), (6k+5), (6k+11)$
Answer: Thanks to the hints in the comments, here's an answer:
As said in the question above, $S = \{x : x \not\equiv 0 \ \mathrm{mod\  2}, x \not\equiv 0 \ \mathrm{mod\ 3} \}$.
Let $b \in S$, then $b \equiv u \ \mathrm{mod \ 2}$ and $b \equiv v  \ \mathrm{mod \ 3}, v, u \ne 0$. We have $b + 6k \equiv u \ \mathrm{mod \ 2}$ and  $b + 6k \equiv v \ \mathrm{mod \ 3}$. Similarily, $b - 6k \equiv u \ \mathrm{mod \ 2}$ and  $b - 6k \equiv v \ \mathrm{mod \ 3}$.
Thus, $b-6k,\ b,\ b+6k$ all belong to $S$ and are in AP, which means that the common difference must be of the form $\boxed{6k}$, or a multiple of $6$.
Comment: Yes, this is correct and makes sense.
Comment: This isn't quite enough to prove it. You've shown that there _is_ a sequence with common difference $6k$, but this doesn't actually show that the common difference **must** be of that form. (To see this, imagine skipping any discussion of $b-6k$; the same argument would claim that any two numbers in $S$ must have common difference $6k$, which is false.)


Why is my adaptive quadrature worse than the composite Simpson rule?

Question: I wrote a basic adaptive quadrature that uses the difference between trapezoidal and Simpson rule to estimate the error on each intervall and makes the mesh finer if needed:
def adaptQuad(f, Meshes, tol):
 M = Meshes[-1]
 h = np.diff(M) #Calculate intervall lengths h_i
 mp = (M[1:]+M[:-1])/2 #calculate midpoints
 fx = f(M); fm = f(mp) #evaluate f(x)
 trp = h*(fx[:-1]+2*fm+fx[1:])/4 #evaluate trapezoidal (on each interval)
 simp = h*(fx[:-1]+4*fm+fx[1:])/6 #evaluate Simpson (on each interval)
 err = abs(trp-simp) #Difference between the rules
 if sum(err) > tol: #are we done?
    ref = np.nonzero(err > sum(err)/len(err))[0] #Refine mesh where needed
    Meshes.append(np.sort(np.append(M,mp[ref])))
    return adaptQuad(f, Meshes, tol) #recursion
 return sum(simp), Meshes #return composite simpson

I wanted to compare it to the composite simpson rule:
def compSimpson(f,a,b,N):
 x,h = np.linspace(a,b,N+1,retstep=True)
 midP = (x[1:]+x[:-1])/2
 x = x[1:-1]
 return h/6 *(f(a) + 2*sum(f(x))+4*sum(f(midP))+f(b))

But when I tried it on:
f = lambda x: 1/(1+25*x**2)

with the following:
Q,M = adaptQuad(f,[np.linspace(-1,1,5)],0.001)
Q_simp = compSimpson(f,-1,1,len(M[-1])-1) #Try Comp. Simpson with as many intervals
I = integrate.quad(f,-1,1)[0]
print("Error composite Simpson: ", abs(Q_simp-I))
print("Error adaptive quad: ", abs(Q-I))

I get:
Error composite Simpson:  5.274740111360643e-08
Error adaptive quad:  1.2452016172281866e-05
I tried some different total tolerances and most of the time the composite simpson rule outperforms the adaptive quadrature? This shouldn't be possible but I can't find my error in the implementation either, I'd be glad for some help:)
Edit: Here an illustration of how the Mesh evolves over time (the nodes are the dots, each line of same coloured dots shows one Meshes[i])
Comment: How far from uniform do your nodes actually end up being? This rule of only demanding that the apparent error is bigger than the average in order to choose to refine in those locations seems a bit pessimistic to me.
Comment: You're right, but I think it should still work, shouldn't it? I added a picture that shows the "node-evolution" over time, to me is seems as if the final mesh should definitely be better then equidistant one.
Comment: Have you tried with a nonperiodic function? There is some extra theory where some methods perform unexpectedly well on periodic inputs.
Answer: As commented, your refinement strategy is skewed. It prefers small intervals over large, or in other words, it is too eager to split large intervals.
What you really should want is that each interval contributes to the error according to their length, that is, a constant error density. For that purpose I would change your code to
def adaptQuad(f, Meshes, tol):
  M = Meshes[-1]
  h = np.diff(M) #Calculate interval lengths h_i
  mp = (M[1:]+M[:-1])/2 #calculate midpoints
  fx = f(M); fm = f(mp) #evaluate f(x)
  trp = h*(fx[:-1]+2*fm+fx[1:])/4 #evaluate trapezoidal (on each interval)
  simp = h*(fx[:-1]+4*fm+fx[1:])/6 #evaluate Simpson (on each interval)
  err = abs(trp-simp) #Difference between the rules

  ref = err > tol*h
  if not ref.any():  #are we done?
    return sum(simp), Meshes #return composite Simpson

  Meshes.append(np.sort(np.append(M,mp[ref])))
  return adaptQuad(f, Meshes, tol) #recursion

This equalizes the results somewhat,
Error composite Simpson:  1.4457746544405126e-07
Error adaptive quad:  7.845544380824521e-07

Both are far below the desired error bound 1e-3. But already for tol=1e-4 there is again the marked difference towards the composite method,
Error composite Simpson:  1.935168691957756e-10
Error adaptive quad:  3.361578637672835e-08

The second point to consider is a little more subtle, the adaptive strategy produces a subdivision for the error of the trapezoidal method, but returns the result for the Simpson method. While the result is better, the error bound tol*interval_length is not valid or very pessimistic.
Another effect is that a greater density of small segments is required for the trapezoidal method in "stiff" regions than for the Simpson method. This means that the adaptive strategy has unnecessary computations in these stiff regions, while the equidistant composite Simpson still has sufficient segment density there, and greater density in more flat regions, thus giving an overall better result.
Or in other words, if you want a fair comparison, take the composite trapezoidal method with the same number of function evaluations.
See Saving nodes in iterative Adaptive Simpson quadrature method (Matlab) for another approach where the recursion actually splits the interval and the requested error bound.
Comment: +1. A few actual comments: 1. Your description of the effect I noticed explains it a lot better; I just had the more rough intuition that this rule would probably trigger refinement in something like half of subintervals which seemed wasteful.
Comment: 2. To the OP, I suggest looking into the theory of Richardson extrapolation if you haven't already. From this point of view, this setup of comparing the trapezoidal and Simpson rules should be used to detect when the result of the adaptive trapezoidal rule is good. For a smooth enough integrand, you can do further Richardson extrapolation to detect when the result of adaptive Simpson is good.
Comment: 3. It is not super important, but I would suggest normalizing the stopping criterion, since as it is, if you have uniform error density, you would stop when the apparent error estimate falls below tol * (b-a) rather than tol.


Salvar automaticamente no banco após trocar o valor do select

Question: Estou usando o DataTable para mostrar uma tabela para o usuário com algumas informações, em uma das colunas (Status) é exibido um select com opções. Quero que, ao selecionar outra opção do select, ela fique salva no banco automaticamente.
Não estou usando forms.
<code>.table-wrapper-tabs id="tab-#{realty.id}"
        table.general-table id="#{realty.id}-table" cellspacing="0" width="100%"
          thead
            tr
              - if browser.device.mobile?
                th
              th.col-md-2 Nome
              th.col-md-2 Telefone
              th.col-md-2 Email
              th.col-md-2 Origem
              th.col-md-1 Status
              th.col-md-1 Data
          tbody
            - if realty.leads.any?
              - realty.leads.each do |lead|
                tr
                  - if browser.device.mobile?
                    td
                      i.fa.fa-arrow-circle-down
                  td #{lead.name}
                  td #{lead.phone.empty? ? "Não informado" : lead.phone}
                  td #{lead.email}
                  td #{lead.origin}
                  td
                    select#leads-status
                      <option value='0' #{lead.status == 'new_lead' ? 'selected':''} >  Novo Lead </option>
                      <option value='1' #{lead.status == 'interest' ? 'selected':''} >  Interessado </option>
                      <option value='2' #{lead.status == 'visit' ? 'selected':''} >  Visita Feita </option>
                      <option value='3' #{lead.status == 'proposal' ? 'selected':''} >  Proposta Feita </option>
                      <option value='4' #{lead.status == 'no_interest' ? 'selected':''} >  Sem Interesse </option>
                  td #{lead.created_at.strftime("%d/%m/%Y")}
</code>

Sei que provavelmente terei q usar um change em JS
Comment: Veja essa pergunta: https://pt.stackoverflow.com/questions/336526/onchange-disparar-em-todo-clique
Answer: É exatamente isso que você ta pensando, no método onchange, você vai pegar o valor e enviar para o seu backend, para uma rota espéfica, de preferência usando AJAX, para não ter que recarregar toda a tabela novamente.
<code> function saveLeadStatus ( valorDoSelect) {
     let data = { select: valorDoSelect }
     $.post('/form.php', data, function(response) {
         // aqui vai voce faz a logica de sucesso ou erro
         console.log("Response: "+response);
     }
});
</code>


Pegar valor de um $.get()

Question: Tenho uma pequena função jQuery que checa qual é o último ID registrado em uma tabela do banco de dados.
Porém, preciso guardar os valor em uma variável e eu percebo que não consigo pegar o valor gerado pelo $.get, o máximo que consigo é um [object Object].
Esta foi uma tentativa de várias;

var ultimoRegistro = $.get("./core/consulta-unidades.php", function(data){
        return data;
    });
alert(ultimoRegistro);
Comment: Recomendo que leia [O que é callback?](https://pt.stackoverflow.com/q/27177/3635) e [Qual a vantagem real de usar um CallBack e o que é thread/multithread?](https://pt.stackoverflow.com/q/45706/3635)
Answer: O $.get() não retorna o valor da função callback e a operação é assíncrona. Talvez seja uma chave dentro do objeto.
$.get("./core/consulta-unidades.php", function(data){
    console.log(data);
});

Pegar valor de um $.get()


Inverse euler totient procedure

Question: Given that if $n = p_1^{\alpha_1}\cdots p_r^{\alpha_r}$ we know that $$\phi(n) = p_1^{\alpha_1 -1}(p_1 - 1) \cdots p_r^{\alpha_r -1}(p_r-1). \quad (1)$$
So, if $\phi(n)$ was given, the method of searching for all $n$ first finds the list of prime factors of $\phi(n)$, then we just have to shortly play with the primes to find the numbers.
Unfortunately, using this method, I'm not able to find all of the numbers $n$.
Example.
Given $\phi(n) = 42 = 2\cdot 3 \cdot 7$, using $(1)$ I can find a set of primes $p_i \in \{2,3,7,43\}$, looking at the primes if $43$ is taken into consideration it is obvious that number $n = 43k$ where $k=2^\alpha 3^\beta 7^\gamma$, then $$\phi(43k) = \phi(43)\phi(k)$$ and since $\phi(43)=42$ it is obvious that $k \in \{1,2\}$. Two numbers found!
How to find the rest?
This is where I get stuck...
Now, if we say that $$n=2^\alpha 3^\beta 7^\gamma \implies \phi(n) = 2^{\alpha-1} 3^{\beta-1}7^{\gamma-1} \cdot 1 \cdot 2 \cdot 2 \cdot 3,$$
so, $$2^{\alpha+1} 3^{\beta}7^{\gamma-1} = 2 \cdot 3 \cdot 7 = 42, $$
solving the equation I get $n = 147$ which isn't correct.
Where's my mistake, if there is one?
Thank you!
Answer: All of $2,3,7$ cannot be in the prime factorization of $n$ since then, as you noted, we have $(3 \cdot 2 \cdot 2) = 12$ in our phi calculation but $42/12$ is not an integer!
Do casework on which two primes, or one prime, are represented.
(Also, Wolfram Alpha gives lets you calculated phi values. Just type $\phi(n) = 42$ and it returns all possible $n's$.)

Inverse euler totient procedure


Trouble making background image for a div auto-resize

Question: I've been wresting with this for a couple of hours now and am not making progress. Thought I would come here for help.   My task is simple and common.  Using BS3, I am trying to have a full page container have a background image which will resize when you resize the browser.  Seems simple enough but the few solutions I've found on here simply don't work.  Here's where I'm at:

            <%--Visible in small, med, large devices.--%>

                ...content...

                ...content...

            <%--Visible in xs devices only.--%>

            ...content...

...and my css....
.LandingRowWrapper
{
    border-width: 1px;
    border-top-style: solid;
    border-bottom-style: solid;
    border-color: #bbd8e7;
    background-color: #ffffff;
    background-image: url('../images/slider3.jpg');
}

Much appreciated!!
Comment: Is that what you're trying to do is have your image cover the background on all size devices?
Answer: If you want the background to cover both the height and width of the container, I would use background-size: cover;. If you want it to just scale horizontally and keep the height proportionate background-size: 100;% should do the trick.


How to write rspec test for custom routes

Question: I have the following custom route:
match '/boeing-737', controller: :planes, action: :display, id: 1000

The 'get' method in rspec only accepts action name, but doing this:
get :display, id: 1000

I am getting:
RoutingError: No route matches {:id=>"1000", :controller=>"planes", :action=>"display"}
And there is no option to do get '/boeing-737' in the test.
Comment: Please post your controller code.
Answer: Found the solution, the id has to be string value, I will post it here since I think this use case is not documented enough in rspec:
match '/boeing-737', controller: :planes, action: :display, id: '1000'


Will my voice get any higher?

Question: I am 14, I'm a mezzo soprano but I really want to be a soprano (like in opera terms). Will my voice get any higher?
Answer: Emily, great question and welcome to the stack. In order to answer your question, there are some truths that you'll need to understand / accept:
1.) 14 is quite, quite young. Like it or not, your voice will very likely not reach full maturity until your early-mid 30's. There is tremendous pressure / expectations from the internet, tv, and music for young people to have incredibly big and powerful voices. This is wrong, for too many reasons to expand upon here. Vocal teachers counsel their students of taking their voices to maturity the proper way, and singing music that is "too big" for a person's voice is the surest sign of immaturity. People who sing too big too soon do not have long careers - they might sound terrific for 20-30 years, which to you might sound like a long time, but a properly maintained voice still sounds incredible after 50 years of singing professionally.
2.) I mention all that for context of my second point: choose your music carefully. You should know that when composers write vocal music, they write for the person (or they should anyway, if they're a good composer and decent human). Over time, we start to see trends in ranges, and from those trends, develop rough ideas about voice-types. Not all ranges are the same. Not all people are the same. I say this because you might really want to be a soprano, but that just might not be your voice-type. If it's not, it is wrong, and can even be damaging to your voice. However...
3.) Know that just because you or your music teacher classify you as a mezzo now doesn't mean you're locked-in for life. Perhaps your music teacher just has too many sopranos and needs lower-voices to fill out the sound. Maybe you just have a very intuitive lower-range. Doesn't matter. Many vocal students are re-classified during their collegiate / conservatory training as their voices develop and their voices mature. Classification, like your vocal range, is fluid (i.e. not set in stone).
4.) Over time, as your voice matures, you can undertake exercises and techniques to broaden your range and strengthen your sound. This should be done with a vocal teacher for guidance.
In sum, don't be in a rush. If you take care of your voice, your voice will take care of you. Always choose music that fits your voice; you shouldn't try and squeeze your voice into a piece just to have the satisfaction of squeaking out a couple of high notes. It looks immature, no one wants to hear it, it doesn't feel good for your voice, and prolonged use could even lead to vocal damage.
Comment: Labels are just that, labels. I know an amateur singer who would label herself as a contralto, with a range down to E below middle C, but she can also hit a top B flat bang in the middle every time "from cold", and on a good day even a top C - which is higher than many who call themselves sopranos are comfortable with. But she's 40 years older than you - just give it time, as jjmusicnotes said!
Comment: Great advice. Your point about composers reminds me of the story of Puccini making a couple of changes in one of his arias to better suit Caruso's voice.

Will my voice get any higher?


Using "Or" opertor in EntityFieldQuery

Question: could you help me to fix my problem?
note:
each user have two field (fields are taxonomy reference)
I want to get two fields with OR condition
the output of my code returns in the shape of AND result
here is my code :
 $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_software_abilities', 'tid', $abilities, 'IN')
    ->fieldCondition('field_other_abilities', 'tid', $abilities, 'IN');
    $result = $query->execute();

I read an article about using addtag and hook_query_tag_alter()
but I can't use it
Answer: EntityFieldQuery does not support 'OR' operators. There is a workaround presented here 'OR' Queries with EntityFieldQuery  where an 'OR' operator is added.
Comment: thank you for your answer I read this article but I can't use it in my code   would you please tell me how I can use that?

Using "Or" opertor in EntityFieldQuery