Argue with Taylor's formula with remainder that this holds.

Question: I get Taylorpolynomials and that the remainder is of course the difference of the function and its taylorpolynomial to the n'th degree. But the rest is kind of throwing me off and how to use the fact that we know the derivative of n'th degree and that this is true for x bigger than 1.
Comment: Separate to the question, you should be aware that 'Taylor polynomial' should be two words in English; the one-word version is perhaps based on a translation from German or another language where the term is a single word.
Answer: Taylor's theorem says $f(x)-T_n(x)=\frac{f^{(n+1)}(\xi)}{(n+1)!}(x-1)^{n+1}$ for some $\xi$ between $1$ and $x$.  Taking absolute values,
$$
|f(x)-T_n(x)|=\left|\frac{f^{(n+1)}(\xi)}{(n+1)!}(x-1)^{n+1}\right|\leq M\,\frac{|x-1|^{n+1}}{(n+1)!}.
$$
where $M$ is any upper bound on $|f^{(n+1)}(x)|$.
Therefore, your strategy is to show
$$
\frac{|f^{(n+1)}(x)|}{(n+1)!}\leq\frac{1}{n+1},
$$
or equivalently,
$$
|f^{(n+1)}(x)|\leq n!
$$
Plugging in $f^{(n+1)}(x)=(-1)^n n! x^{-(n+1)}$, it should be clear.
Comment: What you cite is Lagrange's form of the remainder. There are several others, which might be useful in different cases.
Comment: Ah I see. So I end up actually just having to show a simple inequality and that x>1 for it to be true?
Comment: But wouldn't it be a < and not <= in the end? I mean it is always going to be smaller for x>1, right?
Comment: $<$ implies $\leq$. It's extremely common to use $\leq$ for this reason. But yeah, assuming $x>1$, it will be $<$.
Comment: and this would be in every step or do we actually need the last calculation to be certain?
Comment: Hmm I have 1 follow up question. Why does the function then behave strangely at x>2 if we look at what we have written so far? How can i extract that?
Comment: @vonbrand Oh so this is wrong using Taylors formula since it is Lagranges? ...
Comment: @vonbrand How would you in that case do it?
Comment: @zugzug I have taken a look at this for a whole now. This is true but it is using the Lagrange formula, though.


Disable Time Synchronization on Ubuntu

Question: I am setting up a development environment with Ubuntu in a virtual machine. The date in the VM must be in 2009 due to some silly timebombing issues, so I want to disable any automatic time synchronization (e.g. ntpdate).
$ sudo apt-get remove ntpdate
...
The following packages will be REMOVED:
ntpdate ubuntu-minimal

Obviously, I don't want to remove ubuntu-minimal. Unfortunately, the machine keeps resetting the time forwards every couple of seconds. How do I disable this or stub out this feature?
Answer: Are you sure ntpdate is your problem?  It does not run as a service and usually only gets run when an interfaces is brought up on recent ubuntu systems.
To disable ntpdate on an Ubuntu system without removing it you could simply update /etc/default/ntpdate and add the word exit as the first line or change the NTPSERVERS variable to be empty.
Are you sure the issue isn't related to your VM tools package?  Are you sure you haven't actually installed a full ntp daemon?
Intentionally keeping time out of sync in a single VM can be somewhat difficult.  The system clock is one of the resources that don't really get virtualized very well.
Comment: Aha! I disabled time synchronization in VMWare (set `tools.timeSync = "0"` in the .vmx file) and my problems are solved! Thanks for pointing me in the right direction!
Comment: So you're right: ntpdate is probably not my problem, because I just tried your suggestion (editing the NTPSERVERS variable to be empty) and the date is still resetting. How can I find this thing?
Comment: For Oracle Linux (and probably any Red Hat Linux flavour) you have to modify the file /etc/ntp.conf and comment the existing NTP servers.
Answer: ubuntu-minimal is the package which provides many other packages in the Ubuntu minimal install. Removing that package does not cause any problems. Later on if you want to get all the packages in a minimal installation then just reinstall ubuntu-minimal.
Answer: I have a ubuntu/trusty64 virtual machine I built with vagrant. I had to turn off the time sync in the virtualbox guest addition on the virtual machine.  To do this I added VBOX_OPTS to /etc/init.d/virtualbox-guest-utils like so:
edit /etc/init.d/virtualbox-guest-utils
insert these lines:
if [ -n "$2" ]; then
VBOX_OPTS="$VBOX_OPTS $2"
fi

modify this line:
start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/VBoxService -- $VBOX_OPTS

Now stop and start the service like so
sudo service virtualbox-guest-utils stop
sudo service virtualbox-guest-utils start --disable-timesync

Now I can set the date to what I need and it stays that way until I reboot the machine.
date -s "2014-02-22 22:41:49,332" && date --rfc-3339=ns
date
Sat Feb 22 23:27:31 EST 2014

Answer: man update-rc.d

The correct way to disable services is
  to configure the service as stopped
  in  all  runlevels  in which it is
  started by default.  In the System V
  init system this means renaming the
  service's symbolic links from S to K.

sudo update-rc.d ntp stop 20 2 3 4 5 .

or put an exit inside:/etc/default/ntp

Disable Time Synchronization on Ubuntu


AWS VPN Client Failed to Work

Question: AWS Client VPN use to work until today. It stop working with the following
-AWS VPN Client Helper Tool is required to establish the connection.-
I've tried reinstalling the Client found here and it still didnt resolve the issue.
I tried to uninstall and i get the same error.
I've restart the mac(M1) multiple times, Reinstall The Monterray OS(didn't removed all applications** don't know why).
I've tried checking the logs and found the following.
<code>❯ tail -f /Users/saviourgidi/.config/AWSVPNClient/logs/aws_vpn_client_20221018.log
2022-10-18 15:36:27.254 +02:00 [DBG] Helper app --init output: Helper failed to install.
2022-10-18 15:36:27.254 +02:00 [DBG] Helper failed to install or was canceled.
2022-10-18 15:36:27.254 +02:00 [DBG] Stopping DNS monitoring thread
2022-10-18 15:36:27.254 +02:00 [DBG] Releasing DNS monitoring lock
2022-10-18 15:36:27.255 +02:00 [DBG] Metric agent started
2022-10-18 15:36:27.255 +02:00 [DBG] Received exception for connection state Disconnected. Show error message to user
2022-10-18 15:36:27.255 +02:00 [ERR] Exception recieved by connection view controller
ACVC.Core.OpenVpn.HelperToolInstallationFailedException: AWS VPN Client Helper Tool is required to establish the connection.
  at ACVC.Core.OpenVpn.OvpnOsxProcessManager.Start (System.String openVpnConfigPath, System.String managementPortPasswordFile, System.Int32 timeoutMilliseconds) [0x001f6] in <122123b2b3914e32b2c06bd2a2d00f27>:0
  at ACVC.Core.OpenVpn.OvpnConnectionManager.Connect (ACVC.Core.Metadata.OvpnConnectionProfile configProfile, ACVC.Core.GetCredentialsCallback getCredentialsCallback, System.Int32 timeout) [0x0020f] in <122123b2b3914e32b2c06bd2a2d00f27>:0
2022-10-18 15:40:00.882 +02:00 [DBG] Clean up connections. Connection state: Connecting
2022-10-18 15:40:00.884 +02:00 [INF] Validating schema for OpenVPN config: /Users/saviourgidi/.config/AWSVPNClient/OpenVpnConfigs/test-eu
2022-10-18 15:40:01.889 +02:00 [DBG] Caught exception when getting connection status. Exception information: System.TimeoutException: The message did not respond within the expected timeframe or was cancelled
  at ACVC.Core.OpenVpn.OvpnConnectionManager.SendMessage (System.String message, System.Int32 timeout, System.Threading.CancellationToken cancellationToken) [0x001ca] in <122123b2b3914e32b2c06bd2a2d00f27>:0
  at ACVC.Core.OpenVpn.OvpnConnectionManager.GetConnectionStatus () [0x0007c] in <122123b2b3914e32b2c06bd2a2d00f27>:0
  at ACVC.Core.Metrics.MetricsClient.RecordBytesMetricsAndAnalytics (ACVC.Core.IConnectionManager connectionManager) [0x00077] in <122123b2b3914e32b2c06bd2a2d00f27>:0
2022-10-18 15:40:01.890 +02:00 [DBG] Stopping DNS monitoring thread
2022-10-18 15:40:01.890 +02:00 [DBG] Releasing DNS monitoring lock
2022-10-18 15:40:01.892 +02:00 [INF] Terminating connection
2022-10-18 15:40:01.892 +02:00 [WRN] Acs did not stop correctly!
2022-10-18 15:40:01.892 +02:00 [DBG]  Ending connection details reporting.
2022-10-18 15:40:01.892 +02:00 [WRN] We are calling GracefulKill in a method that is not supposed to change Connection state.
2022-10-18 15:40:01.892 +02:00 [DBG] GracefulKill
2022-10-18 15:40:01.893 +02:00 [DBG] Cancelling socket listen token
2022-10-18 15:40:01.893 +02:00 [DBG] Dispose socket
2022-10-18 15:40:01.893 +02:00 [DBG] Signal process kill with helper tool.
2022-10-18 15:40:01.893 +02:00 [DBG] Starting process
2022-10-18 15:40:01.926 +02:00 [DBG] Start to read process output
2022-10-18 15:40:01.962 +02:00 [DBG] End reading process output
2022-10-18 15:40:02.028 +02:00 [DBG] Helper app --kill output: Kill success.
2022-10-18 15:40:02.028 +02:00 [DBG] Release process manager start lock
2022-10-18 15:40:02.028 +02:00 [DBG] Release process manager stop lock
2022-10-18 15:40:02.028 +02:00 [DBG] Disconnected
2022-10-18 15:40:02.028 +02:00 [DBG] Stopping DNS monitoring thread
2022-10-18 15:40:02.028 +02:00 [DBG] Releasing DNS monitoring lock
2022-10-18 15:40:06.195 +02:00 [INF] Saving profile store to /Users/saviourgidi/.config/AWSVPNClient/ConnectionProfiles
2022-10-18 15:40:06.197 +02:00 [INF] Connecting /Users/saviourgidi/.config/AWSVPNClient/OpenVpnConfigs/test-eu
2022-10-18 15:40:06.198 +02:00 [DBG] validationString: /Users/saviourgidi/.config/AWSVPNClient/OpenVpnConfigs/test-eu
1666100416
2022-10-18 15:40:06.198 +02:00 [DBG] Shutting down metrics agent
2022-10-18 15:40:06.198 +02:00 [DBG] Metrics agent shut down
2022-10-18 15:40:06.354 +02:00 [INF] Starting OpenVpn process
2022-10-18 15:40:06.354 +02:00 [DBG] Starting process
2022-10-18 15:40:06.375 +02:00 [DBG] Start to read process output
2022-10-18 15:40:10.553 +02:00 [DBG] End reading process output
2022-10-18 15:40:10.617 +02:00 [DBG] Helper app --init output: Helper failed to install.
2022-10-18 15:40:10.617 +02:00 [DBG] Helper failed to install or was canceled.
2022-10-18 15:40:10.617 +02:00 [DBG] Stopping DNS monitoring thread
2022-10-18 15:40:10.617 +02:00 [DBG] Releasing DNS monitoring lock
2022-10-18 15:40:10.618 +02:00 [DBG] Metric agent started
2022-10-18 15:40:10.618 +02:00 [DBG] Received exception for connection state Disconnected. Show error message to user
2022-10-18 15:40:10.618 +02:00 [ERR] Exception recieved by connection view controller
ACVC.Core.OpenVpn.HelperToolInstallationFailedException: AWS VPN Client Helper Tool is required to establish the connection.
  at ACVC.Core.OpenVpn.OvpnOsxProcessManager.Start (System.String openVpnConfigPath, System.String managementPortPasswordFile, System.Int32 timeoutMilliseconds) [0x001f6] in <122123b2b3914e32b2c06bd2a2d00f27>:0
  at ACVC.Core.OpenVpn.OvpnConnectionManager.Connect (ACVC.Core.Metadata.OvpnConnectionProfile configProfile, ACVC.Core.GetCredentialsCallback getCredentialsCallback, System.Int32 timeout) [0x0020f] in <122123b2b3914e32b2c06bd2a2d00f27>:0
2022-10-18 15:40:11.802 +02:00 [DBG] Clean up connections. Connection state: Connecting
2022-10-18 15:40:11.803 +02:00 [INF] Validating schema for OpenVPN config: /Users/saviourgidi/.config/AWSVPNClient/OpenVpnConfigs/test-eu
2022-10-18 15:40:12.806 +02:00 [DBG] Caught exception when getting connection status. Exception information: System.TimeoutException: The message did not respond within the expected timeframe or was cancelled
  at ACVC.Core.OpenVpn.OvpnConnectionManager.SendMessage (System.String message, System.Int32 timeout, System.Threading.CancellationToken cancellationToken) [0x001ca] in <122123b2b3914e32b2c06bd2a2d00f27>:0
  at ACVC.Core.OpenVpn.OvpnConnectionManager.GetConnectionStatus () [0x0007c] in <122123b2b3914e32b2c06bd2a2d00f27>:0
  at ACVC.Core.Metrics.MetricsClient.RecordBytesMetricsAndAnalytics (ACVC.Core.IConnectionManager connectionManager) [0x00077] in <122123b2b3914e32b2c06bd2a2d00f27>:0
2022-10-18 15:40:12.807 +02:00 [DBG] Stopping DNS monitoring thread
2022-10-18 15:40:12.807 +02:00 [DBG] Releasing DNS monitoring lock
2022-10-18 15:40:12.809 +02:00 [INF] Terminating connection
2022-10-18 15:40:12.809 +02:00 [WRN] Acs did not stop correctly!
2022-10-18 15:40:12.809 +02:00 [DBG]  Ending connection details reporting.
2022-10-18 15:40:12.809 +02:00 [WRN] We are calling GracefulKill in a method that is not supposed to change Connection state.
2022-10-18 15:40:12.809 +02:00 [DBG] GracefulKill
2022-10-18 15:40:12.810 +02:00 [DBG] Cancelling socket listen token
2022-10-18 15:40:12.810 +02:00 [DBG] Dispose socket
2022-10-18 15:40:12.810 +02:00 [DBG] Signal process kill with helper tool.
2022-10-18 15:40:12.810 +02:00 [DBG] Starting process
2022-10-18 15:40:12.842 +02:00 [DBG] Start to read process output
2022-10-18 15:40:12.875 +02:00 [DBG] End reading process output
2022-10-18 15:40:12.943 +02:00 [DBG] Helper app --kill output: Kill success.
2022-10-18 15:40:12.944 +02:00 [DBG] Release process manager start lock
2022-10-18 15:40:12.944 +02:00 [DBG] Release process manager stop lock
2022-10-18 15:40:12.944 +02:00 [DBG] Disconnected
2022-10-18 15:40:12.944 +02:00 [DBG] Stopping DNS monitoring thread
2022-10-18 15:40:12.944 +02:00 [DBG] Releasing DNS monitoring lock
</code>
Answer: I just spent about 25 hours trying to debug this, basically in tears. Finally pieced it together so I'm posting the solution here
You have to run
<code>sudo launchctl enable system/com.amazonaws.acvc.helper
</code>
To allow the helper to install. Make sure you are in the PrivilegedHelperTools folder when you run this
Comment: I had to reinstall the Whole OS. Poor me!

AWS VPN Client Failed to Work


Como criar uma tabela com HTML e CSS?

Question: Olá.
Como faço para criar uma tabela responsiva em html e css usando
 ou
 desse jeito:
Comment: Comece criando a estrutura HTML com os elementos `table`, `tr` e `td`. Depois, tente estilizada com CSS. Se não der certo, você pode [edit] a pergunta e adicionar todos esses códigos que você fez, explicando como ficou e como você gostaria que ficasse.
Comment: http://www.leandroguarino.com.br/index.php?p=curso_html5_css&aula=tabelas
Answer: O código HTML para criar esta tabela, seria o seguinte:

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

   Resumo
   2
   3
   4

   5
   6
   7

   Direto
   1
   2
   3

   1 Parada
   4
   5
   6

Espero ter ajudado.

Como criar uma tabela com HTML e CSS?


Comparing kernel density estimates with polynomial functions

Question: I have  kernel density estimates of  survival functions from different datasets. These density estimates are produced just to have smoothed versions of the original survival function which is a step function.
I don't know the functional form of the kernel that was used. I need to compare these kernel density estimated curves - is fitting polynomials to these smooth kernel density estimates a good way to see if they differ from each other much?
Its important that I compare the smoothed curves and not the underlying unsmoothed data.
I am in a way dealing with the same type of problem as here: Fitting a CDF to differentiate symbolically
only I already have the kernel densities, and just need some metrics to compare them.
I already posted this question here Polynomial fit for a kernel smoothed function,
but think this is a better way to phrase it.
Answer: If you want to compare across different settings, then using polynomials might not help much compared to just comparing the raw kernels at different number of periods out. For instance, there is no simple interpretation of the third order term being larger of smaller. You need to plot them together, I suppose.
Moreover, polynomials can look weird in the end points.
Comment: Thanks for the advice. How about if I fitted a mixture of normals to the kernel density estimate ? Would the resulting mixtures help me to differentiate between the kernel density estimates from different portfolios? Thanks again!
Comment: That sounds do-able too. Then you could compare, say, your estimated survival curves so and so many periods out and report that.


Apply condition between two fields in drupal 7 by using JQuery

Question: This is updated JQuery code I have created condition between two fields in drupal 7 i.e. If we select item from first field then as per there selected item, some items of second field is going to hidden. But problem is that : If first I select item from second select field & after that I have select same item in first field then in this condition my created condition is wrong. Please Help to solve this. Thanks
Please check this DEMO
Below is my my updated JQuery code

Answer: I have tried your code and got a quick solution i.e. reset second select box every time first is changed.
look how I have implemented the same:
$(function(){
$("#edit-main-field-i-am-field-und").change(function() {

    $('#edit-main-field-look-for-field-und').val("_none"); // added to reset second select box on chanage of first one

       var value = $(this).val();
       var optionText = $(this).find('option[value='+value+']').text();
    $('#edit-main-field-look-for-field-und').find('option').show();
       if(optionText=="A" || optionText=="C" )
       {
         //alert("12345");
           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).text()=="A" || $(this).text()=="C")
                 return true;
              else
                 return false;
           }).hide();
       }
      else
       {
           //alert("98765");
           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).text()=="B" || $(this).text()=="D")
                 return true;
              else
                 return false;
           }).hide();
       }
    $('#edit-main-field-look-for-field-und option:visible:eq(1)').prop('selected',true);
   // alert($('#edit-main-field-look-for-field-und').val());
    });
});

I have just added $('#edit-main-field-look-for-field-und').val("_none"); in .change function.
Comment: :( it's working on Demo if I make change but I try on my localhost.. It's not working @Ashish
Comment: I have tried it in jsfiddle and its working for me, what issue you are getting?
Comment: try code with slight change
$('#edit-main-field-look-for-field-und').val("");
Comment: It's working now... no need to change any thing.. Thanks alot @Ashish
Comment: I have 1 query what it mean to put this "$('#edit-profile-main-field-look-for-field-und option:visible:eq(1)').prop('selected',true);".. If I remove this.. no issue with jquery.. @Ashish
Comment: I think it was intended to do the same but wrongly placed and coded, I have done same at right place with right code. :)
Comment: Now its working correctly.. I make some changes...
Comment: Please have a look in this link... I have some query related my above question "http://drupal.stackexchange.com/questions/132202/how-to-add-js-file-in-drupal-7"


Wizard or Form to create 5 nodes of 3 content types

Question: I'm building a genealogy site. One of the most important use cases is to create an individual. I want to use a single form to capture information that will be used to create up to five nodes after clicking submit. I've done a bunch of research, and found lots of stuff partially represented by the links below, but I haven't found anything that will do this. Can you point me to any modules to that do this? Or will I need to write my own module for this?
New Individual form captures the following fields:

Birth Given & Surnames
Current checkbox (checked if it's still individual's current name)
End date, if not current name
Current Given & Surnames - if different from birth
Start Date - if applicable
Date of Birth
Place of Birth
Date of Death
Place of Death

The form then creates the following five nodes:

Individual node - with Title
Name node for birth name
Name node for current name (if different from birth name)
Event node for birth
Event node for death

Nodes 2-5 would have ER field_individual, to link back to the individual to which they are related.
Below are links to some of the resources I have found which are similar, but do not actually do what I'm looking to do:

https://www.drupal.org/project/webform_wizard_full_title
https://www.sitepoint.com/building-multi-page-wizard-like-form-drupal/
https://www.drupal.org/forum/support/post-installation/2008-06-06/adding-multiple-nodes-at-once
https://www.webwash.net/create-multiple-nodes-from-a-single-page/
Creating Nodes and Referenced Nodes at Same Time
https://www.drupal.org/forum/support/module-development-and-code-questions/2007-11-18/multiple-node-types-in-one-module
https://www.drupal.org/project/pageroute
Comment: Leymannx - Thanks for feedback. I thought I was being specific about asking if there was a module that does what I need, or if I need to build one. Looks like GiorgosK gave me some valuable guidance below.
Comment: I would start by looking at hook_entity_presave in a custom module. This will save you quite a lot of grief as you can create or update your referenced nodes at the same as editing the "Individual node" (1).
Answer: I think you will need a custom module to do that
An outline of what your module should be doing

Create a simple module using the docs or following a simple module tutorial or by studying the examples module
Extend it by creating a form using drupal 8 form API

Validate on submit that the input fields are filled in properly

On formSubmit you should create your nodes programmatically

Entity references can be created using this as a guide


Select dinâmico com JQuery

Question: Sou iniciante em trabalhar com JQuery, e estou com dificuldade em fazer um select dinâmico funcionar.
Ao escolher no primeiro select um valor o segundo select deve exibir apenas os options com class terminados pelo valor selecionado no primeiro select. O mesmo esquema funciona no terceiro select em relação ao primeiro.
Eu utilizei um script funcional, porem adaptá-lo ele perdeu a funcionalidade, mas ele está escrito mais ou menos como precisaria.

    Instituição

        <select name="instituicao_tur" required="required" class="form-control" id="instituicao_tur">
            <option value="0">Selecione</option>
            <option value="1"/>Instituição 1
            <option value="2"/>Instituição 2
            <option value="3"/>Instituição 3
        </select>

$(document).ready(function() {
   $('#instituicao_tur').change(function() {
        if ($(this).val() == "0") {
            $('.curso_zero').hide();
        }
    });

    $('#instituicao_tur').change(function() {
        if ($(this).val() == '1') {
            $('.id_cur1').show();
        }
    });

    $('#instituicao_tur').change(function() {
        if ($(this).val() == '2') {

            $('.id_cur2').show();
        }
    });

    $('#instituicao_tur').change(function() {
        if ($(this).val() == '3') {

            $('.id_cur3').show();
        }
    });
    });
});

jSFiddle com o código base.
Comment: acredito que deve have algumas instituições, muitos cursos e inumeras turmas.
Neste tipo de cenario, é interresante você consultar os cursos e turmas disponiveis atraves de Ajax.
Comment: Acredito que sim @bfavaretto. Só que o sistema foi feito em ASP e com banco em Access, então apanhei quando tentei fazer o esquema com Ajax. Esse método da pergunta era pra ver se dava pra fazer de uma maneira alternativa sem perder em performance.
Comment: você tambem pode usar datalist para isto. neste caso você coloca na pagina todos os dl esperados, então só alterna eles.
Answer: Este seu esquema de esconder os options por classes não me parece uma boa ideia.
Como não sei exatamente o que você está fazendo não tenho como propor uma solução melhor.
Segue abaixo o código que funciona da forma como você descreveu:

  $(document).ready(function() {
     $('#instituicao_tur').change(function() {
         $('option[class^="id_cur"]').hide();

         var val = $(this).val();
          if (val == 0) {
              $('.curso_zero').hide();
          } else {
              $('.id_cur'+val).show();
          }
      });

     $('#curso_tur').change(function() {
         $('option[class^="id_polo"]').hide();
         $('.id_polo'+$(this).val()).show();
      });
});
#curso_tur option, #polo_tur option{display:none;}

    Instituição

        <select name="instituicao_tur" required="required" class="form-control" id="instituicao_tur">
            <option value="0">Selecione</option>
            <option value="1"/>Instituição 1
            <option value="2"/>Instituição 2
            <option value="3"/>Instituição 3
        </select>

    Curso

        <select name="curso_tur" required="required" class="form-control" id="curso_tur">
            <option class="curso_zero" value="">Selecione</option>
            <option class="id_cur1" value="1"/>Curso 1
            <option class="id_cur2" value="2"/>Curso 2
            <option class="id_cur3" value="3"/>Curso 3
        </select>

    Núcleo

        <select name="polo_tur" required="required" class="form-control" id="polo_tur">
            <option value="polo_zero">Selecione</option>
            <option value="1" class="id_polo1"/>Nucleo 1
            <option value="2" class="id_polo2"/>Nucleo 2
            <option value="3" class="id_polo3"/>Nucleo 3
        </select>

Explicando:
O seletor ^= na linha
$('option[class^="id_cur"]');

pega todos os option cuja classe começa com id_cur e esconde todos.
Na linha
$('.id_cur'+val).show();

val é o valor do option selecionado, logo .id_cur + val é a classe que corresponde aos options que você quer mostrar.
Answer: Como eu comentei em um comentario, tambem é possivel se fazer isto utilizando dataList,
abaixo segue um exemplo:
HTML

    Instituição
    <input id="inst" type="text" list="_000"></input>

    Curso
    <input id="curso" type="text"></input>

    Nucleo
    <input id="nucleo" type="text"></input>

<datalist id="_000">
    <option value="Instituicão 100" data-value="100" />
    <option value="Instituicão 200" data-value="200" />
    <option value="Instituicão 300" data-value="300" />
</datalist>

<datalist id="_100">
    <option value="Curso 110" data-value="110" />
    <option value="Curso 120" data-value="120" />
</datalist>

<datalist id="_200">
    <option value="Curso 210" data-value="210" />
    <option value="Curso 220" data-value="220" />
</datalist>

<datalist id="_300">
    <option value="Curso 310" data-value="310" />
    <option value="Curso 320" data-value="320" />
</datalist>

<datalist id="_110">
    <option value="Nucleo 111" data-value="111" />
    <option value="Nucleo 112" data-value="112" />
</datalist>

<datalist id="_120">
    <option value="Nucleo 121" data-value="121" />
    <option value="Nucleo 122" data-value="122" />
</datalist>

<datalist id="_210">
    <option value="Nucleo 211" data-value="211" />
    <option value="Nucleo 212" data-value="212" />
</datalist>

<datalist id="_220">
    <option value="Nucleo 221" data-value="221" />
    <option value="Nucleo 222" data-value="222" />
</datalist>

<datalist id="_310">
    <option value="Nucleo 311" data-value="311" />
    <option value="Nucleo 312" data-value="312" />
</datalist>

<datalist id="_320">
    <option value="Nucleo 321" data-value="321" />
    <option value="Nucleo 322" data-value="322" />
</datalist>

JS
var inst = $("#inst");
var curso = $("#curso");
var nucleo = $("#nucleo");

inst.bind("input", function () {
    curso.val("");
    nucleo.val("");
    nucleo.attr("list", null)

    var option = $(inst.prop("list")).find("option[value='" + inst.val() + "']");
    if (option != null && option.length > 0) {
        curso.attr("list", "_" + option.attr("data-value"));
    } else {
        curso.attr("list", null)
    }
});

curso.bind("input", function () {
    nucleo.val("");
    var option = $(curso.prop("list")).find("option[value='" + curso.val() + "']");
    if (option != null && option.length > 0) {
        nucleo.attr("list", "_" + option.attr("data-value"));
    } else {
        nucleo.attr("list", null)
    }
});

JSFIDDLE
http://jsfiddle.net/z42yktta/2/

Select dinâmico com JQuery


Como evitar quebra de layout em um projeto PWA?

Question: Ao listar os arquivos que você quer manter no cache com a versão do service worker, na maioria das vezes colocamos o arquivo de estilo, para ser acessível offline.
Com isso, quando há mudança de CSS, em produção a aplicação pode sofrer com essa divergência de cache do "html/javascript" e o css.
Até mesmo quando se tira o arquivo css da listagem de cache, pode acontecer essa quebra.
No cenário com PWA, quais as soluções que costumam utilizar ou a melhor solução que adotam para não haver quebra de layout em uma nova versão de um PWA?
Ex: acrescentar query string, quando há uma mudança com muita chance de quebra e etc...
Answer: Tem um jeito de fazer que acho que pode te atender. Eu esqueci o nome dessa técnica, mas ela faz um "versionamento" da URL do arquivo CSS, isso faz com que o browser sempre faça o download do "novo" CSS. O que se faz na verdade é muda um parâmetro no URL do CSS, assim vc força o browser a refazer o cache com o caminho "novo" do arquivo.
Segue um exemplo repare que inicialmente eu tenho um arquivo css.css e depois eu vou mudando o estilo do background no .css e vou salvando no HTML a URL do arquivo como css.css?v=2 e depois css.css?v=3 e por ai vai. Repare que o arquivo sempre é o css.css e eu só mudo o ?v=xxx que vem após no nome do arquivo, isso funcionaria até para caminhos mais complexos como src\main\webapp\resources\css\css.css?v=1 onde na compilação vc trocaria apenas o final por ?v=2 por exemplo. Só isso já é suficiente para fazer o browser reindexar seu .css

Para automatizar isso eu realmente não sei, mas acredito que algum compilador tipo WebPack para PWA tenha essa funcionalidade.
Comment: Muito obrigado @hugocsl, gostei muito dessa técnica, abriu minha mente para as possibilidades. Pesquisando achei isso com o termo "query strings", e o mais legal, serve para javascript tbm, da mesma forma.
Comment: @David eh isso ai, da pra usar ate com imagem rss, eu mesmo descobri isso para fazer o browser colocar um favicon novo na aba, favicon costuma ficar tão impregnado no cache que só assim consegui resolver.
Comment: Realmente, favicon fica/ficava impregnado kkk vlw  Bro !


Conversion Failed when converting date and/or time

Question: I am running into an issue. I get the Conversion failed error on the code sniped below.
I can't seem to pinpoint why this is happening, in my Dev environment I do not get the error and everything runs smoothly.
<code>  Dim PrdDate As Date
        SQL.ReturnRead = 0
        PrdDate = dtpDataInput.Value.Date
        MsgBox(PrdDate)
        SQL.ReadQuery("SELECT CAST(DATEDIFF(second, TimeDown, TimeUp) / 60 / 60 % 24  AS NVARCHAR(50)) + '.'
               + CAST(DATEDIFF(second, TimeDown, TimeUp) / 60 % 60 AS NVARCHAR(50)) as HrsDown From UDOData
               WHERE (cast(TimeDown AS DATE) = '" & PrdDate & "'
               AND CAST(TimeUp AS DATE) = '" & PrdDate & "') and FleetNo = '" & FleetStr & "'")
        UDOHRS = SQL.ReturnRead
</code>
I have checked the regional settings on the live environment and all seems ok.
Thank you for everyone's help
Comment: Why not just use proper parameters instead of concatenating strings? Creating test scenarios to allow sql injection? [Bobby Tables: A guide to preventing SQL injection](http://bobby-tables.com/)
Answer: When formatting for SQL Server it's better to always format it as YYYYMMDD.
Just use
<code> WHERE (cast(TimeDown AS DATE) = '" & PrdDate.ToString("yyyyMMdd") & "'
</code>


Django: How to properly use the ForeignKey in a modelform?

Question: I'm trying to create a HTML form in Django and I'm using Django modelforms to do this. In my models.py file I'm using a "ForeignKey", this will be converted to a drop-down menu with options in the HTML form. This works, I'm seeing a drop-down in my view.
models.py
class plants(models.Model):
    name = models.CharField(max_length=300, blank=True)
    active_account = models.ForeignKey('accounts')

    class Meta:
        unique_together = ('active_account', 'name')

class accounts(models.Model):
    name = models.CharField(max_length=200)
        url = models.CharField(max_length=200)

class PlantsForm(ModelForm):
    class Meta:
        model = plants
        fields = '__all__'

My_Cool_Django_ModelForm.html
{% for field in form %}
{{ field.label_tag }}
{{ field|addcss:'form-control'}}
{% endfor %}

Problem
So let's say I have 2 accounts in the database called "Mister Foo" and " Miss Bar". If I then load the HTML form I do see 2 options in my dropdown menu but not "Mister Foo" and "Miss Bar". It only drops down with the texts "accounts object" and I want it to display the names.

So my question, how can I display the accounts the dropdown by their name? :( I've tried field.
Answer: Use __unicode__ for your accounts class:
class accounts(models.Model):
    name = models.CharField(max_length=200)
    url = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

By the way, it's bad code style to use accounts as python class name. It should be capfirst and single form like Account. Check pep8 doc for convention details.
Comment: If you are using Python 3, define `__str__` instead of `__unicode__`.


Hidden field value in Stripes (object instead of numeric value)

Question: I have this field in my JSP file:
<s:hidden name="testResult.bottle" value="${testResultsActionBean.testResult.bottle.id}" />

and I get this:
<input name="testResult.bottle" value="package.dto.BottleDto@e8" type="hidden" />

But this line of code returns ID, which I need as value in the hidden input:
<c:out value="${testResultsActionBean.testResult.bottle.id}"></c:out>

How can I get ID as value in input?
Thanks for any advice.
Comment: Could you provide package.dto.BottleDto source
Comment: What gets printed by your  call?
Comment: Duplicate of http://stackoverflow.com/questions/9999397/hidden-field-becomes-null-when-binding-it-in-stripes-actionbean. Look there for answer.
Answer: Stripes always prefers the value from the action bean over anything you put in the value attribute.  (Even if the value in the action bean is null)
Use this:
<s:hidden name="testResult.bottle.id"/>


Two hundred balls into one hundred boxes

Question:
We have distributed two hundred balls into one hundred boxes with the restrictions that no box got more than one hundred balls, and each box got at least one. Prove that it is possible to find some boxes that together contain exactly one hundred balls.

Assume to the contrary that no class of boxes contains $100$ balls. If there is a box with exactly $2$ balls, there is no class of boxes with $98$ balls, which implies that there is no class of boxes with $96$ balls. Continuing this way we see that there is no class containing $4$ balls, so there is no class containing $2$ other than the initial box with $2$ balls, i.e, this box is unique.
Now, if there is a box with $1$ ball, then there is no class of $99$ balls and continuing this way, there is no class of $2$ balls so no box with $1$ ball other than our initial box with $1$ ball. So again, this box is unique. Thus, in the best scenario we have our balls distributed as $1,2,3,...,3$ but this is more than $200$ balls, contradiction.
What do you think? Is this a valid proof now?
Comment: why there's a box with 2 ball?

try this: 99 3 1 1 1 .... 1
Comment: You can only say "if there is a box with 1 ball, then there is no *disjoint* class of 99 balls".
Comment: If there is exactly one box with $2$ balls there could be a collection of other boxes with $96$ balls.  The logic fails at this step.
Comment: You're right, I'm fixing my proof.
Comment: if you'll wait a second, I'll write one for you
Comment: I changed it a little, is it ok now?
Comment: @sucre how do you pass from 98 to 96, and then to 4?
Comment: @Exodd since we assume that there is box B with 2 balls, if there are boxes together containing 96 balls then these balls and B together contain 98 balls, that's why there is no class of boxes with 96 balls. Same goes for 94, 92,...,4
Comment: Found this question while reading 'A walk through Combinatorics' by Bona. Is my solution correct?
Answer: if there's a box with 2 balls, surely there won't be any disjoint class of boxes with 98 balls, but you can't say now that there's no class with 96, since if you add the box with 2 balls, it is not disjoint from itself
Let's prove a more generalized version.
Given $2n$ balls distributed in $n$ boxes, with $n>1$ and even, such that every box is not empty and has at most $n$ balls in it, then there exists a subset of the box whit exactly $n$ balls.
First of all, if all the boxes contains exactly 2 balls, it's easy, so let's assume there's a box with more than 2 balls, and consequentially one with 1 ball.
Order the boxes in decreasing order and start picking them from the first. Continue until the balls count get over $n$.
 Let's say you've picked the first $k$ boxes, $a$ is the number of balls in them, and $b$ is the number of balls in the $k+1$-th box, with $\;a<n\;$ but $\;a+b>n\;$ (if it's equal to $n$, you've finished).
Surely $b>1$, and if $b=2$, then $a=n-1$, and we can add a box with a ball.
If $b>2$, it's easy to show that there are at least $b-2$ boxes with exactly 1 ball, so if $a+b-2\ge n$, we've finished, by picking the right number of boxes with 1 ball.
The only case left is $a+b-2=n-1$, that is $a+b=n+1$.
If $a\ne 0$, then $k>0$, and so there's surely at least another box with 1 ball (different from the $b-2$ ones), and we're done.
If $a=0$, then $b=n+1$, impossible.
Answer: We can show the more general result for $2n$ boxes and $4n$ balls. (Note that the corresponding problem with an odd number of boxes cannot be solved because it might happen that all boxes contain two balls thus making odd sums impossible)
Let the largest boxes contain $u$ and $v$ balls, respectively, with $u\ge v$.
If $u=2$, then all boxes contain two balls and we are done. This means that we may assume wlog. that
Observation 1. At least boxes has only one ball.
If $u>v=2$, there must be exactly $u-2$ boxes with one ball and $2n+1-u$ boxes with two balls. Hence if $u\le n+1$, we can obtain a sum of $2n$ using $n$ of the $2$-boxes only; and if $u>n+1$, we can obtain $2n$ from the $u$-box together with $2n-u< u-2$ of the $1$-boxes.
Assume therefore that at $u\ge v\ge 3$. Then there are at least $u+v-4\ge u-1$ boxes with only one ball. Consequently, we may assume that
Observation 2. If any box contains $w$ balls,  there are at least $w-1$ boxes with only one ball.
Assume that $2n$ cannot be obtained. Let $s$ be the best approximation to $2n$ that we can get as a sum of a subset $S$ of the boxes (i.e. we minimize $|s-2n|$). Since the complement set gives us $4n-s$, we may assume wlog. that $s<2n$, say $s=2n-d$ with $d> 0$. Let $a$ be the smallest size of a box $\notin S$. Then $a\ge 2d$ as otherwise adding an $a$-box to $S$ would give us a better approximation. And if any box $\in S$ contains $b<a$ balls, or if there is a subset of $S$ that adds up to $b_1+\ldots +b_r=b<a$, then we conclude $a\ge 2d+b$ as otherwise again we easily find a better approximation by adding $a$ and removing $b_1, \ldots, b_r$.
Let $r_1$ be the number of boxes in $S$ with one ball. From $d\ge 1$ we conclude that $a\ge 2$ so that all $1$-boxes belong to $S$, hence by observation 1,  $r_1\ge 1$. This allows us to obtain $b=1,2,\ldots , r_1$, hence $a\ge 2d+1, 2d+2,\ldots$ and finally $a \ge 2d+r_1$. By observation 2, we have $r_1\ge a-1$, hence $2d\le 1$, contradiction.
Comment: From Observation 2: Start taking boxes from smallest to largest, hoping to get exactly $2n$ balls. At the moment your total is at least $2n$ balls, stop. If you have exactly $2n$, you're done. If not, and you have $2n+k$, the box you just took has at least $k+1$ balls in it, with $k\ge1$. Thus there are at least $k$ boxes with one ball each, which you already took. "Untake" $k$ such boxes, and you're done.
Comment: @SteveKass Nice explicit strategy
Answer: If all the boxes had $2$ balls, we'd be done.
Let $a_i$ be the number of balls in box $i$. We can choose $a_1\neq a_2$, without generality loss.
Look at the set of $100$ numbers: $\lbrace a_1,a_2,a_1+a_2,\dotsc,a_1+a_2+\dotsb+a_{99}\rbrace$. If one of these is $0\mod100$, we'd be done. Else, either there are 2 numbers $i,j$ such that $a_1+\dotsb+a_{i+j} \equiv a_1+\dotsb+a_i \mod 100$, or there exists some $i$ such that $a_1 + \dotsb + a_i \equiv a_2 \mod 100$. This could only mean that either $a_{i+1}+\cdots+a_{i+j}=100$ or $a_1 + a_3 + \dotsb + a_i = 100$.
Comment: This is a neat argument. I've suggested an edit fixing a missing case (notice that it really is needed, because your argument otherwise suggests that we could make do with just the set $\{a_1,a_1+a_2,\dotsc,a_1 + \dotsb + a_{99}\}$, but that's not right: this is a set of only 99 numbers).


Program isn't giving me the desired outcome

Question: My program is only allowing me to enter 3 characters into the array and not five. Why is that so?
import java.io.*;
public class Prog{

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char c[] = new char[5];

        for(int i=0;i<-4;i++){
          c[i]= (char) br.read();
        }

    }
}

Comment: How are you entering the chars?.. one by one by pressing enter?
Comment: remove the minus from your loop first
Answer: From the Javadoc for BufferedReader#read():

Reads a single character

In other words, this will read in each character one by one.  The reason it appears that you can only enter three characters is because you are pressing enter after each character:
first character
ENTER
second character
ENTER
third character

Use readLine():
public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    char c[] = new char[5];

    for (int i=0; i<=4; i++) {
        c[i] = br.readLine().charAt(0);
    }
}

This approach will read in one line at a time, in this case a line being defined as a single character followed by a newline.  If you enter more than one character in a given line input, then only the first one will be used.


When can I start to let my child attend to archery course?

Question: I don't have skills in archery but I am interested in introducing my children to archery via archery schools. I heard that archery is a good sport that will increase our focus power and our control power to emotion. I don't know when is exactly the right time to introduce my son to learn archery. Are there any good references about this?
Answer: If you live in the United States, you can check out the Junior Olympic Archery Development (JOAD) website, which is affiliated with USA Archery. For other countries, a visit to FITA (Federation Internationale de Tir a l'Arc) site might be a good starting point.
The JOAD site contains a FAQ that describes aspects of the program. The JOAD site itself notes:

JOAD is open to any youth archer aged 8 to 20 and is designed to grow
  with the youth archer. Introductory JOAD classes teach the
  fundamentals of proper shooting form; as the young archer develops,
  they will learn more advanced techniques.

From that description, it appears that children that are at least eight years old can start training. Of course, parents know their children best and may be able to start them off at a younger age.
Comment: Some area 4-H clubs also have archery elements. The one I grew up in did.
Comment: @JW8 thank you for the explanation, I hope my son will like this sport
Comment: some boyscout clubs also do archery


Why is Java11 keeping java.util.zip.ZipFile$Source on heap?

Question: Can somebody help me understand if what I see is deliberate, correct behaviour or some kind of leak in Java11? Let's take a stupid-simple hello world app:
package com.example;

public class HelloWorld {
    public static void main(String[] args) throws InterruptedException {
        for( int i =0 ; i < 50; i++){
            Thread.sleep(1000);
            System.out.println("hello " + i);
        }
    }
}

The only interesting part is a jar dependency. It can be any jar, but to make the problem more spectacular let's use a big one - old gwt-user jar, which weigh 30MB:
plugins {
    id 'java'
}

group 'com.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    // https://mvnrepository.com/artifact/com.google.gwt/gwt-user
    compile group: 'com.google.gwt', name: 'gwt-user', version: '2.7.0'
}

Run the app, open the jvisualvm, make a dump and look for retained set of java.util.zip.ZipFile$Source:

That jar from classpath (never used, actually) occupies 1.5MB of heap. It doesn't go away during GC, it doesn't go away when you are short of memory, I even saw these entries in OutOfMemory heapdumps.
The entry is obviously kept by a map java.util.zip.ZipFile$Source.files. From the source I can tell that this theoretically should be cleaned by a Common-Cleaner thread from InnocuousThreadGroup, but I don't see it happening.
I encountered this problem when migrating a small, lightweight Java app from JDK8 to JDK11.
With low Xmx settings those jars use up significant portion of my heap as compared to JDK8.
So is it a bug or a feature?
Comment: This data gets cleaned when the associated ZipFile is closed or garbage collected, but, of course, a class path entry gets never closed nor garbage collected.
Comment: It seems JDK8 also keeps the ZipFiles opened, but it has opened streams, not some eagerly read byte[].
Answer: This is deliberate.
The observation that memory use seem to increase
is caused by moving from a native to pure java-based implementation[1]
for zip/jar files in JDK 9. Mainly for stability purposes.
I'll note that the native implementation allocates similar and similarly
sized data structures, but they were hidden out of sight from tools
inspecting the java heap.
But even though total memory footprint should be more or less neutral, there might be a need to increase the java heap size to encompass the increased java heap usage.
[1] https://bugs.openjdk.java.net/browse/JDK-8145260


Rails: preventing spec files from being initialized during rake tasks

Question: I have a Rails app with a spec folder full of rspec tests. Many of them reference resources in my app, such as the 'User' resource. Everything is fine on my machine, but when I try to setup the app on a new machine and build the database with rake db:setup, it starts the whole Rails app, and for some reason, parts of the rspec tests get evaluated. Since one of them is referencing the 'User' resource, for which a database table has not been created yet, the rake task fails with relation "users" does not exist.
I can easily solve this my moving the spec folder out of the parent directory, running the setup, and then moving it back, but this is annoying. Obviously, I'd like for the spec files to be ignored during rake tasks like this. Any ideas?
Comment: I can't try it right now to verify it, but I guess you should be able to remove the spec folder from `config.autoload_paths` in application.rb
Answer: This SO Answer helped me: FactoryGirl screws up rake db:migrate process.
This is the specific solution that worked for me.
In your gemfile, change factory_girls_rails so it isn't required
gem 'factory_girl_rails', :require => false

Then require it in your spec helper
require 'factory_girl_rails'


Why jQuery trigger function deletes data from array?

Question: Please look at this jsfiddle.
Here's the code:
$(function() {
    $('#click').click(function() {
    $(document).trigger('clicked', [1,2]);
  })

  $(document).on('clicked', function(event, data){
    console.log(data);
  });
})

If you see the code, what we get in console is 1 only.
It seems that jQuery strips the array and only shows the first element.
How should I fix this?
Comment: Your fiddle link is missing your code
Answer: According to .trigger() you pass parameters with an array, but receive them with separate parameters.
Example from jquery.com:
$( "p" )
  .click(function( event, a, b ) {
    // When a normal click fires, a and b are undefined
    // for a trigger like below a refers to "foo" and b refers to "bar"
  })
  .trigger( "click", [ "foo", "bar" ] );

Applied to your code:

$(function() {
  $('#click').click(function() {
    $(document).trigger('clicked', [1, 2]);
  })

  $(document).on('clicked', function(event, data1, data2) {
    console.log(data1, data2);
  });
})

<button id='click'>
Click
</button>

As an extra, you can always use arguments which ignores the parameters and provides you with the arguments that were called.
Applying to your case, to get the original back as an array:
let data = [...arguments].slice(1);

The slice(1) is to remove the event parameter.
Updated snippet:

$(function() {
    $('#click').click(function() {
    $(document).trigger('clicked', [1,2]);
  })

  $(document).on('clicked', function(event){
    let data = [...arguments].slice(1);
    console.log(data);
  });
})

<button id='click'>
Click
</button>


Can I use log and without any transformation variables in the one model for the independent variables?

Question: Can I use log-log/linear regression models by taking the natural logarithm of some variables?
Imagine I have a dependent variable $y$ and independent variables $x_1$, $x_2$, and $x_3$. Can I run the following regression:
$$\log(y) = \log(x_1)+\log(x_2) + x_3$$
Comment: What is name of that model?log(y)=log(x1)+log(x2)+x3
Answer: You can absolutely mix logged and unlogged variables on the right hand side. For example, one never logs dummy or negative variables for obvious reasons.
However, I do think it is good to have principled reasons for doing this in your analysis.


Cannot read properties of undefined (reading 'excluirTask')

Question: Estou querendo implementar a funcionalidade de excluir individualmente o itens de uma lista, mas quando chamo a função excluirTask (ainda não implementada) ocorre o erro Cannot read properties of undefined (reading 'excluirTask').
App.js:
import React, { Component } from "react";
import uniqid from "uniqid";
import Overview from './components/overview';

class App extends Component {
  constructor() {
    super();
    this.state = {
      task: {
        text: '',
        id: uniqid(),
        num: 1
      },
      tasks: []
    };
    this.excluirTask = this.excluirTask.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.onSubmitTask = this.onSubmitTask.bind(this);
  }
  handleChange = (e) => {
    this.setState({
      task : {
        text: e.target.value,
        id: this.state.task.id,
        num: this.state.task.num,
      }
    });
  };
  onSubmitTask = (e) => {
    e.preventDefault();
    this.setState({
      task: {
        text: '',
        id: uniqid(),
        num: this.state.task.num+1,
      },
      tasks: this.state.tasks.concat(this.state.task),
    });
    console.log(this.state.tasks);
  };
  excluirTask = (e) => {
    e.preventDefault();
    console.log("Excluir a tarefa: " + this.task.id);
  };
  render() {
    const { task, tasks } = this.state;
    return (

        <form onSubmit={this.onSubmitTask}>
          Enter task
          <input
            onChange={this.handleChange}
            value={task.text}
            type="text"
            id="taskInput"/>
          <button type="submit">
            Add Task
          </button>
        </form>
        <Overview tasks={tasks} />

    );
  }
}
export default App;

overview.js:
import React from "react";

const Overview = (props) => {
  const { tasks } = props;

  return (

      {tasks.map((task) => {
        return (

{task.num} - {task.text}

                    <button key={task.id} onclick={this.excluirTask}>Excluir</button>

            );
      })}

  );
};

export default Overview;

index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Comment: já tentou passar o evento no click? assim por exemplo: `onClick={ e => this.excluirTask(e)`
Comment: Retorna o erro: this.excluirTask is not a function
Comment: Eu editei o arquivo overview.js, transformando a função Overview numa classe e adicionando dentro dela a função excluirTask. Isso resolveu o erro, aparentemente não da pra chamar a função excluirTask dentro de overview.js se ela estiver declarada em App.js. Mas ocorre outro erro, ela é executada automaticamente todas as vezes que é digitado conteúdo dentro do input.
Comment: Usando a notação de seta () => this.excluirTask(task.id) e a função declarada dentro de Overview da tudo certo.
Answer: Resolvi o problema, o método excluir teve que ser declarado dentro da classe Overview e ele foi chamado usando declaração por chaves, pois continha um argumento:
import React, { Component } from "react";

class Overview extends Component{
    excluirTask = (id) => {
        console.log("Excluir a tarefa: " );
        console.log(id);
      };
    render(){
        return (

            {this.props.tasks.map( (task) => {
                return (

{task.num} - {task.text} <button onClick={() => this.excluirTask(task.id)}>Excluir</button>

                    );
            })}

        );
    }
}

export default Overview;

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Powershell error Add-PSSnapin "Microsoft.SharePoint.PowerShell"

Question: I am getting an error when I run below command from sharepoint 2010 managment shell using admin rights.
Add-PSSnapin Microsoft.Sharepoint.Powershell

Add-PSSnapin : Cannot add Windows PowerShell snap-in Microsoft.Sharepoint.Power
shell because it is already added. Verify the name of the snap-in and try again

Comment: The SharePoint management shell already loads that plugin on startup. What problem are you trying to solve by loading it again?
Comment: Add-PSSnapin : Cannot add Windows PowerShell snap-in Microsoft.SharePoint.Power
Shell because it is already added. Verify the name of the snap-in and try again
.
At line:1 char:13
+ add-PsSnapin <<<<  Microsoft.SharePoint.PowerShell
    + CategoryInfo          : InvalidArgument: (Microsoft.SharePoint.PowerShel
   l:String) [Add-PSSnapin], PSArgumentException
    + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.Ad
   dPSSnapinCommand
Comment: getting error in below function error details:The term 'Reset-SPContext' is not recognized as the name of a cmdlet                                                                                Function CreateSiteCollections([xml]$xmlinput)
{$CreateApplicable = $false
 Write-Host -ForegroundColor White " - Creating Site Collections..."
 If ($xmlinput.Configuration.WebApplications)
{ForEach ($webApp in $xmlinput.Configuration.WebApplications.WebApplication){if ($webApp.SiteCollections){Reset-SPContext #only reset if we are deploying sites.}
Comment: I have no idea what that code snippet is supposed to tell us. Or why you didn't put it in your actual question.
Comment: i think this is the issue with powershell 2.o which does not contain cmdlet. do you know why this error comes
Comment: I suspect `Reset-SPContext` isn't part of anything native to SharePoint or PowerShell.  This really doesn't seem relevant to the current question and should probably be a separate one. Likely sources of the cmdlet in question [here](http://www.codefornuts.com/2009/10/forcing-sharepoint-tool-to-reload-12.html) and/or [here](https://social.msdn.microsoft.com/Forums/office/en-US/5ea46e07-a4b0-4bab-b698-9b6eeb695607/sitedefinitions-installed-within-the-same-powershell-session-not-available-upon-site-collection?forum=sharepointgeneralprevious).
Answer: Check to see if module is already loaded:
if (Get-Module -ListAvailable -Name SomeModule) {
  Write-Host "Module exists"
} else {
  Write-Host "Module does not exist"
}

Source: How do I check if a powershell module is installed?
UPDATED:
Try {
    if((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null){
        Add-PsSnapin Microsoft.SharePoint.PowerShell
    }
}Catch{

}

Comment: Snapins are not the same as modules. This is a much better answer http://stackoverflow.com/a/1478221/299327.
Comment: Slight wording concern about `-ListAvailable` "ListAvailable does not return information about modules that are not found in the PSModulePath environment variable, even if those modules are loaded in the current session." Probably not an issue for the SharePoint snap-in, but could affect others who are loading modules from custom or remote sources. [More details from the Get-Module help.](https://technet.microsoft.com/en-us/library/hh849700(v=wps.620).aspx)
Comment: Excellent. I do prefer that second option. It is more specific to the snap-in vs module situation in question and is a more thorough solution.
Comment: Getting below error                                                                                Add-PSSnapin : Cannot add Windows PowerShell snap-in Microsoft.SharePoint.Power
Shell because it is already added. Verify the name of the snap-in and try again
.
At line:1 char:13
+ add-PsSnapin <<<<  Microsoft.SharePoint.PowerShell
    + CategoryInfo          : InvalidArgument: (Microsoft.SharePoint.PowerShel
   l:String) [Add-PSSnapin], PSArgumentException
    + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.Ad
   dPSSnapinCommand


Programmatically set the value of a date/Time field

Question: I am trying to copy the value of a Date/Time Webform element to a Date/Time field set on the article node.
Below is the source code of the Date/Time Webform element:
expiry_date:
  '#type': datetime
  '#title': 'Expiry Date'
  '#title_display': before
  '#required': true
  '#required_error': 'You must add an expiry date'
  '#date_date_format': ''
  '#date_year_range': '2019:2100'
  '#date_time_format': ''

Below is my custom handler:
// Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get 'Expiry Date' Value.
    $ExpiryDate = $values['expiry_date'];
    date_default_timezone_set('UTC');   // Sett the time to 'UTC' time zone.

    // Format the "Expiry Date" to return "Y-m-d\TH:i:s".
    //$FormattedExpiry = date('Y-m-d\TH:i:s', $ExpiryDate);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
    // Set the node field values.
        'title' => $Title,
        'langcode' => 'en',
        'uid' => $CurrentUid,
        'status' => '1',
        'created' => $current_time,
        'field_expiry_date' => $ExpiryDate, // $FormattedExpiry,
        ]);

// Save the created node.
    $article->save()

But I am facing the below error:
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'field_expiry_date_value' at row 1: INSERT INTO {node__field_expiry_date} (entity_id, revision_id, bundle, delta, langcode, field_expiry_date_value) VALUES (
:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5);
Array (
[:db_insert_placeholder_0] => 84
[:db_insert_placeholder_1] => 88
[:db_insert_placeholder_2] => article
[:db_insert_placeholder_3] => 0
[:db_insert_placeholder_4] => en
[:db_insert_placeholder_5] => 2021-05-25 11:26:02 +03:00
)
in Drupal\Core\Entity\Sql\SqlContentEntityStorage->saveToDedicatedTables() (line 1414 of /home/username/public_html/example.com/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Answer: The expiry_date from webform return something like 2021-05-25 11:26:02 +03:00 so you should to format it before you passe it to create like the following:
// Get 'Expiry Date' Value.
$ExpiryDate = $values['expiry_date'];
// Format the "Expiry Date" to return "Y-m-d\TH:i:s".
// Here use strtotime to format date correctly
$FormattedExpiry = date('Y-m-d\TH:i:s', strtotime($ExpiryDate));

Then passe $FormattedExpiry instead of $ExpiryDate:
$article = \Drupal\node\Entity\Node::create([
    'type' => 'article',
   // Set the node field values.
    'title' => $Title,
    'langcode' => 'en',
    'uid' => $CurrentUid,
    'status' => '1',
    'created' => $current_time,
    'field_expiry_date' => $FormattedExpiry,
    ]);

Update: your date already has +3h, if you want to not add 3 hours to your time there is two options i guess:

Change you webform field settings to work with UTC to get the value of $values['expiry_date'] something like 2021-05-25 11:26:02 without +03:00
Remove the +03:00 before date conversion from $values['expiry_date'] by change the line $ExpiryDate = $values['expiry_date']; with something like:
$ExpiryDate = explode('+', $values['expiry_date'])[0];
Comment: Finally it is working when I used `date_default_timezone_set('UTC');   // Sett the time to 'UTC' time zone.`, check the updated question
Comment: Thank you your code is working ! However, I am getting the time added by 3 hours (UTC Time). How to change the time zone or maybe use the timezone of the site ?
Comment: You need to store the time as UTC and store the offset for your time zone separately. See my answer here: https://drupal.stackexchange.com/a/273372/80164
Comment: Actually your expire date in the webform stored with +3h, look in the error message the date is `2021-05-25 11:26:02 +03:00 ` so i guess, check how to make webform use the time zone of your site or UTC
Comment: check my update, the suggested method by @ hotwebmatter will not work, because date it will calculated before based on `+03:00`
Comment: @berramou 1) I don't think there is a setting in webform field about Timezone (Or at least I am unable to find it) 2) Using `$ExpiryDate = explode('+', $values['expiry_date'])[0];` did not change anything and still the date is displayed + 3 Hours in advance... Thank you
Comment: P.S: If I removed `$FormattedExpiry = date('Y-m-d\TH:i:s', strtotime($ExpiryDate));` and added `$ExpiryDate = explode('+', $values['expiry_date'])[0];` instead, the date is successfully copied to the article with no errors but still with +3 Hours in advance
Comment: can you dump the value of `$ExpiryDate` after `$ExpiryDate = explode('+', $values['expiry_date'])[0];`
Comment: if the value of `$ExpiryDate` is something like `2021-05-25 11:26:02` without trailing `+03:00` it will work, debug the `$ExpiryDate`
Comment: Both `$ExpiryDate = explode('+', $values['expiry_date'])[0];` and `$FormattedExpiry = date('Y-m-d\TH:i:s', strtotime($values['expiry_date']));` gave me the same output: `2020-04-26T19:55:02 `
Comment: This was helpful for me but when I edit the node I've created, the date fields are empty. I'm sure it has something to do with the way Drupal is accessing the DB stored date.


How to hide menu bar in virtualbox?

Question: I mean it hides automatically, but I can still see it as a white line in the bottom which is annoying in fullscreen mode. Is there any way to completely remove it from the screen? I still can reach it with ctrl + home, so I don't need it to popup on mouse hover
Answer: Open the command prompt, navigate to the folder where vboxmanage is and execute the code below.
<code>VBoxManage setextradata global GUI/Customizations noMenuBar,noStatusBar
</code>
Comment: I do not recommend this because it is a permanent setting on VirtualBox. To undo run: "VBoxManage setextradata global GUI/Customizations".
Comment: Hey Diego. I think it depends on user's preference. I still prefer it to be "permanent settings". and then I made a small gui app with checkbox to toggle the showing.
Answer: You don't have to fool with VBoxManage if you'd rather use CLI. If you launch your VM with the VBoxSDL command, then the VM is displayed in a simple window without any pretty icons.
VBoxSDL --startvm
Reference:
http://www.virtualbox.org/manual/ch09.html#vboxsdl
Comment: VBoxSDL is not available on the Mac OS X host platform

How to hide menu bar in virtualbox?


How do I restrict a user to visit a particular page only certain no of times?

Question: How do I restrict a user (role) to visit a particular page only certain number of of times? I am using Drupal 6. It is for premium content. I just want to give 5 premium content views for free.
Comment: It's actually not a duplicate.  This is about Drupal 6, and the linked question is for Drupal 7.  The answer on the linked question will also only work for Drupal 7, as that hook doesn't exist in Drupal 6.
Comment: @MPD It does exist, it's just named [hook_access()](https://api.drupal.org/api/drupal/developer!hooks!node.php/function/hook_access/6) instead.
Comment: @MPD Same hook, same question, no version tags on neither, just one little rename in API - I don't think it should be 2 questions. I updated my answer there.
Comment: Can you try to use: Rules module and PHP filter. After determine the view count for the node you can redirect or limit user for view that node. That's my idea
Comment: Already answered: http://drupal.stackexchange.com/questions/73397/block-node-access-after-a-certain-amount-of-views/73399#73399
Comment: @Mołot No, it's not the same hook. With Drupal 6, only the modules defining a content type can use `hook_access()`. In Drupal jargon, such modules are called _node modules_.
Comment: @kiamlaluno - OK, corrected my answer there to use hook_nodeapi(). All in all, it's still the same solution, just different function called.
Comment: @Mołot Uhmmm, no. If you are using a different hook, the solution is not the same, especially if the code used to implement those hooks would be different.
Comment: @kiamlaluno Only differences are in the way current user is inputed and forbidden outputted. all the logic, including switch($op), stays the same. Does `drupal_access_denied()` vs `return false` really makes solution so different it deserves to be a separate question? I don't believe it does. And that's the only significant code change in implementation.
Comment: @Mołot Apart that I doubt `hook_nodepi()` should be calling `drupal_access_denied()` or redirecting the user in anyway, the code used for `hook_nodeapi()` is not the same code used for `hook_node_access()`, and not only for the returned value.
Answer: If you want to restrict a casual user to only 5 views of ANY premium content, versus restricting his/her looking at the same piece of content 5 times, you might want to consider storing this information in the user's data field.
In broad strokes, you could in a custom module's nodeapi hook, do something like this:
<code>if op is view
  if type is premium
    if user doesn't have a premium role assigned
      load the full user object
      if s/he has seen 5 pieces of content
        drupal_goto signup page
      else
        increment count of free page views
        save user
        if this is the 5th view
          tell user this is the last freebie
        fi
      fi
    fi
  fi
fi
</code>
Look into user_save() and user_load() for how to save and load serialized information into and from the data field/column of the user.  Also look into hook_nodeapi() for how to intercept these views.
Also caveats you will have to be aware of is cron and search, you probably don't want them to be limited by this, and that drupal_goto in there might/will reek havoc if it isn't trapped for these purposes.


Placing XML buttons on top of java buttons?

Question: Is there an XML code that will allow me to always have my XML buttons on top of the buttons I've created with java? Because right now it will only display my XML button when my java buttons are disabled.
XML Button:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_student_menu"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="blah.Blah">

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        app:fabSize="normal"
        app:srcCompat="@android:drawable/ic_input_add"
        android:id="@+id/floatingActionButton"
        app:backgroundTint="?attr/colorBackgroundFloating"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"/>
</RelativeLayout>

Comment: view.bringToFront()
Comment: @EliasFazel I'm trying to bring the XML to the front, is there an XML code? I don't see a bringToBack() function to use to put my java buttons in the back.
Comment: in class after findViewById()
Answer: android:id="@+id/floatingActionButton"

this is the ID of FloatingActionButton so declare it in this way
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.floatingActionButton);
fab.bringToFront();

Comment: If I do this then it still shows only the button, is there a way to make them both visible? This just completely overrides the buttons I've created with java, and only shows the XML button on the screen.
Comment: change position of view in xml
Comment: It's in the bottom right corner and the java buttons don't go that far down so there isn't anyway they would overlap.


Standard deviation of revenue where numbers are only positive

Question: Is there a way for standard deviation to ignore negative numbers? In other words, how can you make it so that 2 or 3 deviations do not extend into negative territory?
When looking at a set of only positive numbers, within one or two standard deviations, I end up with negative numbers. It's essentially impossible for a data point to be negative.  Am I doing something wrong?
Also, when using deviations from the mean, do you add or subtract the full deviation from the mean or divide by two and plus and minus that to get one deviation from mean
I'm sure this embarrassingly simple for this group but this is not my strong point!
Please let me know if I can clarify.  My recent experience with statistics is relatively limited.
Thanks!
Comment: Have you tried using the natural log of price data instead? Often that will help with negative range issue.
Answer: Standard deviation is kind of a unit of distance your numbers are from the mean. The problem with standard deviation is that when it's introduced it's usually done assuming a bell shaped curve. From that it's easy to see what 1 standard deviation means ( 68% of the data is within 1 standard deviation ). It sticks in your head easily. Problem is, when we observe counts, or other types of data values(like blood pressue, failure times, etc) their set of observed values dont follow a bell shaped curve. In those contexts the easy to understand idea you were given for the sd doesn't work as intuitively as you would hope.
   My best advice is to use other measures then a standard deviation. Learn about a concept called percentiles. For example the 25th percentile is the count for which 25% of your data falls beneath it. So if the 25th percentile was 8, then 25% of your data has 8 or less. In other words I'm telling you to find a different statistic to use to classify where your numbers fall, instead of using a standard deviation.
This was asked awhile ago and had some good answers as well:
How to interpret  two standard deviations below the mean of a count variable being less than zero?
Comment: This is an excellent and very important lesson. Thank you.


Reason for segmentation fault despite using equivalent statements

Question: I wrote a function for implementing merge sort on singly linked list, where every element has an integer and a next pointer.
One of the function splitlist is used to split the given linked list into two linked lists
void splitList(struct node* source, struct node** frontRef, struct node** backRef)
{
    struct node *s, *f;
    s = source;
    f = s->next;
    while(f && f->next)
    {
        s = s->next;
        f = f->next->next;
    }
    *frontRef = source;
    f = s->next;
    s->next = NULL;
    *backRef = f;
}

Here source is a pointer to given linked list and frontRef and backRef are references to pointer which need to be assigned through this function. fronRef should refer to first linked list and backreef should refer to second one.
This code gives segmentation fault when the lines

*frontRef = source;
  *backRef = f;

are replaced by

frontRef = &source
  backRef = &f

I fail to understand the reason for this as both set of statements are equivalent to each other
Comment: @user200783 how is that relevant?
Comment: 'Both statements are equivalent'. Clearly they are not. When working with pointers you must keep in mind the difference between copying the pointer and copying what is being pointed at.
Comment: `source` and `f` are local variables, keeping a reference to them is not going to work well
Comment: @user200783 That was a part of some debugging statements that I removed before posting. I removed it now.
Answer:
as both set of statements are equivalent to each other

They absolutely aren't.

*frontRef = source means dereference frontRef and invoke operator= on the returned lvalue expression of type node.
frontRef = &source means take the address of source and assign it to frontRef.

If frontRef is uninitialized or null, (1) is undefined behavior, but (2) is fine.
Comment: but the fault occured in case of (2).
Answer: *frontRef = source; *backreef = f;

and
frontRef = &source; backreef = &f;

are not equivalent:

One correctly assigns front and back to two linked lists, one doesn't, which leads to segmentation fault.
Answer:
*frontRef = source; *backRef = f;
frontRef = &source; backRef = &f;

These aren't equivalent.
Second one just updates local variable frontRef with another local variable source's address, so it actually does not affect anything for the the caller side. You probably meant frontRef to be an out argument but it is not updated at all. (And same for backRef.)


How to display dataset in windows form?

Question: My application takes any database as its input, it then detects the tables in that database and then fill all the tables into a DataSet. Now I have image of database in the dataset. Now my question is how to display this dataset into windows form.
DataSet is dynamic because everytime it will have n number of tables and each of these tables can have any number of rows and any number of columns.
Please read this question for context.
compare databases (tables only) using C# and Ado.net
Comment: Are you trying to build a Database application?
Comment: @Steve Yes, I am trying to build a Database application.
Answer: The best way of displaying a table is with a DataGridView (DGV from now on). The thing is that the dgv is able to show one table, and only one.
So how do you do it? You need to have more than one DGV (one for each table of the dataset) or have some way of changing the table the DGV is showing.
Lets say you decide to have multiple DGV. I will not cover how to add them dinamically to the form, if you want to know ask for it and I will edit the answer.
You create one DGV for each table on the dataset:
List<DataGridView> DGVs = new List<DataGridView>();
foreach (DataTable DT in DS.Tables){
    DataGridView DGV = new DataGridView();
    DGV.DataSource=DT;
    DGVs.Add(DGV);
    //Add code for adding them to the form
}

Now you have one DataGridView for each table on the dataset.
If you prefer to have one DGV and be able to choose what table you want to show let me know

How to add controls dinamically
You need to decide how do you want to add them, in this case it will be one bellow the other.
For making them visible you need to:

Add them to the father control
Locate them
Make them visible.

Adding to the father controls is a simple:
form1.Contols.Add(DGV)

Locating them is a bit more tricky, because you want each one of them in a diferent position, but relative to the previous one. To do this you need to create a Point and after that moving it X pixels down. so:
Point p = new Point(0,0); //Position of the first DGV, choose the one you want
p.Y += DGV.Height + 10; //Margin that you want

And then seting the DGV position to the point
DGV.Location = p;

And then just need to show the DGV
DGV.Show();

You can do it all in the for each loop, it will be something like:
List<DataGridView> DGVs = new List<DataGridView>();
Point p = new Point(0,0); //Position of the first DGV, choose the one you want
foreach (DataTable DT in DS.Tables){
    DataGridView DGV = new DataGridView();
    DGV.DataSource=DT;
    DGVs.Add(DGV);
    p.Y += DGV.Height + 10; //Margin that you want
    DGV.Location = p;
    this.Controls.Add(DGV);
    DGV.Show();
}

Note that if you dont need the list of DGV (It can be usefull in some cases) you can ignore the first and DGVs.Add(DGV); lines.
Comment: Thanks for answering. I have updated the question. Could you tell me how to add them dynamically?
Comment: Ok, I would edit the answer, comne back in some minutes
Comment: @TemporaryNames Edited
Comment: Thank you so much. I am developing a database comparator tool. May I have your assistance on that project? May I have your email id?
Comment: @TemporaryNames I'm no expert, not even close. I'm glad to help you with what I can, but there will be a lot (like a lot) of things that I will not know. If you know how. Email me at email@example.com if you want

How to display dataset in windows form?


Useful matrix inner products

Question: What are some interesting/useful examples of matrix inner products on square complex matrices, other than $\langle A, B \rangle = Tr(A^{\dagger}B)$?
Comment: The Killing form on a Lie algebra of square matrices, given by $\langle A,B \rangle =Tr(ad(x)ad(y)$.
Comment: @DietrichBurde The Killing form is bilinear rather than biHermitian over complex spaces, and it fails to satisfy $B[x,x] > 0$ for $x \neq 0$.  So, calling it an inner product seems like a bit of a stretch.
Answer: It's hard to find anything as useful as the one you mention, but this might be of interest.
https://mathoverflow.net/questions/115192/power-log-distance-between-matrices/115227#115227
(ps. again I would have made this a comment rather than an answer, but I still can't do that)

Useful matrix inner products


How can i extrude a stl with python

Question: I am trying to convert png images to 3d stls. I finally found a way to do that. But there is a problem. Now the exported image has no z value no thickness. The way I am doing it is for the white pixels on the image I draw triangles to a surface.
def define_faces(numpy_array, column_number, row_number, z_value):
    print("Vertices Initializing.")
    vertices = np.zeros((row_number , column_number , 3))
    for x in range(0, column_number):
        for y in range(0, row_number):
            z = z_value
            vertices[y][x] = (x,y,z)
    print("Vertices Initialized")
    faces = []
    print("Initializing Faces.")
    for x in range(0, column_number - 1):
        for y in range(0, row_number - 1):
            if numpy_array[y][x] >= PIXEL_COLOR_FILTER:
                vertice1 = vertices[y][x]
                vertice2 = vertices[y+1][x]
                vertice3 = vertices[y+1][x+1]
                face1 = np.array([vertice1, vertice2, vertice3])

                vertice1 = vertices[y][x]
                vertice2 = vertices[y][x+1]
                vertice3 = vertices[y+1][x+1]
                face2 = np.array([vertice1,vertice2,vertice3])
                faces.append(face1)
                faces.append(face2)
    print("Faces Initialized")
    return np.array(faces) , faces

and
def create_mesh(faces_numpy, faces, output_name):
    print("Creating Mesh.")
    surface = mesh.Mesh(np.zeros(faces_numpy.shape[0], dtype = mesh.Mesh.dtype))
    for i ,f in enumerate(faces):
        for j in range(3):
            surface.vectors[i][j] = faces_numpy[i][j]

    surface.save(output_name)
    print("Mesh created succesfully.")

These are the core functions of this code. Code is originally for Lithophane generation. I have an idea on instead of giving triangles and making them an stl, directly generating cubes on intended pixels. so it becomes 3d. But before that any ideas on how to extrude the final stl?
This is the png:

This is the stl:
Comment: You need two z values.
Comment: Hi. I tried to give two z values. I called the define_faces function twice and initialized their outputs to 4 separate variable. Then I tried to combine those outputs with append function. But it raise this error. "IndexError: index 20506 is out of bounds for axis 0 with size 20506" in 6th line of create_mesh function. This line: "surface.vectors[i][j] = faces_numpy[i][j]".
Answer: You can use open source library MeshLib with python bindings to solve your task.
Then the code for extrusion is as follows:
import meshlib.mrmeshpy as mr
# load image as Distance Map object:
dm = mr.loadDistanceMapFromImage(mr.Path("your-image.png"), 0)
# find boundary contour of the letter:
polyline2 = mr.distanceMapTo2DIsoPolyline(dm, isoValue=127)
# triangulate the contour
mesh = mr.triangulateContours(polyline2.contours2())
# extrude itself:
mr.addBaseToPlanarMesh(mesh, zOffset=30)
# export the result:
mr.saveMesh(mesh, mr.Path("output-mesh.stl"))

The result will look as
Comment: it doesn't work at all, see https://stackoverflow.com/questions/74862109/extruding-an-stl-from-a-binary-png-image-with-python
Comment: The answer [there](https://stackoverflow.com/a/75066059/7325599) states that it does work, and the error comes from failed file opening.
Comment: The relevant method addBaseToPlanar did work for me. I did something slightly different, but related.

How can i extrude a stl with python


How are diminished 7th passing chords notated?

Question: If I am in the key of D major and I use a passing diminished 7th chord between D major and E minor, the resulting chord is an Ebdim7 or D#dim7? When I spell the chord using sharps it makes more sense: D#, F# A, B#? Would this be right?
Answer: The chord should be notated as D#o7, because it is functioning as the leading-tone chord moving to E minor. It is spelled D#-F#-A-C.
Ebo7 (Eb-Gb-Bbb-Dbb) is the leading-tone chord for Fb major and minor.
Comment: Acceptance after an hour and with only two answers so far wouldn't be too prudent. Always best to wait until there is a better choice.
Comment: Ok thanks. Is there such a key as Fb major or minor? Also, shouldn't it be Dbb not Db?
Comment: @armani And, yes, theoretically there is such a thing as Fb major/minor. It could show up as the bII key of Eb, but in practice would likely be rewritten as E for each of reading.
Comment: @Tim I was actually wondering if "asking for acceptance" is alright… It is sure annoying when OP do not care about the future of its question but at the same time it puts some kind of disturbing pressure… Might be a good question for Meta!
Comment: @Tom - there have been questions that I've posed, and no-one - yet - has been given an acceptance for an answer. Sometimes it's that all answers are excellent, sometimes it's that none is exactly what I'm looking for, or doesn't give me information I'm not aware of. It would be annoying if I was requested to accept, though.
Comment: @Tim same here, to a less extend obviously. I was just wondering…
Comment: @Tom Regarding your comment that this would make for a good Meta question, it's been asked several times. It appears that this one is [the canonical answer](https://meta.stackexchange.com/questions/14994/do-you-feel-dirty-if-you-nudge-new-users-to-accept-your-answer-when-they-indicat). IMO, it's not something to be done frequently, but accepting and upvoting answers are the ways to say "thank you" on SE sites. So, when I see a "thank you" comment, whether my own or someone else's, I reply with something to that effect.
Comment: Thanks for the link! However, as I would understand encouraging this behavior for new contributors I personally find it a bit misplaced when the OP is obviously an experienced user and especially after such a short time. Anyway, this is just a personal point of view ;).
Comment: @Tom Thanks. I shouldn't have [needed that](https://www.youtube.com/watch?v=j3n-P0vrdZU) pointed out to me.
Answer: To keep things simple it's best to stick with whatever is prevailing. Key D has sharps, so D♯ is a better root note than E♭.
Could even be construed as B7♭9 - which is a favourite to move to Em from.
Can't always be so, although often a chord is 'spelled wrongly' to make it easier to read and understand, even though it may be technically the wrong name.
But E♭ wouldn't be technically correct anyway - that belongs to a flat key.
Comment: What if you re-harmonize the chord by adding notes from the D half-whole diminished scale - then there's a D _and_ ... an Eb or D#? With eight notes at the same time, the seven-note letter naming system doesn't feel like a good fit. AFAIK some jazz people think about dim7 chords as being a part of a fuller diminished sound where you can play all notes from the diminished scale. Maybe in different octaves but still.
Comment: @piiperiReinstateMonica - why would one use all of those notes from that scale in a chord - that's pretty pointless. One may use them to solo with, but as a chord..?
Comment: It's a nice chord IMO, if you spread the voices into different octaves https://www.youtube.com/watch?v=nO_xkm9s3rU&t=66s
Answer: The first response is correct, but you can write it a number of ways.  I've written the two most common ways you will see the chords below, with their corresponding notes:
D7      D F A   C
E7      E G B (or A)  D (or C)
Of course, I've seen everything from D#dim7 to D7/Eb.  Take your pick.


How to execute ajax into block view

Question: I'm in Drupal 7. I would like to execute an ajax function in my front-page. I've defined the block view in my ".module" file. When I change the selected option, the log gets two errors:
1.

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'test_services_search_form' not found or invalid function name in drupal_retrieve_form() (line 842 of /var/www/html/test/html/includes/form.inc).

2.

Notice: Undefined index: test_services_search_form in drupal_retrieve_form() (line 807 of /var/www/html/test/html/includes/form.inc).

test.module
function test_services_block_info() {
  $blocks['test_services_search_form'] = [
    'info' => t('Plan your trip'),
  ];
  return $blocks;
}

function test_services_block_view($delta = '') {
  $block = [];
  switch ($delta) {
    case 'test_services_search_form':
      module_load_include('inc', 'test_services', 'includes/test');
      $form             = drupal_get_form('test_services_search_form');
      $block['content'] = render($form);
      break;
  }
  return $block;
}

test.inc
<?php

/**
 * @file
 * TEST - File search inc.
 */

/**
 * Implements hook_form().
 */
function test_services_search_form($form, &$form_state) {
  $form['search'] = [
    '#type' => 'container',
  ];

  // Transfer.
  $form['search']['transfer'] = [
    '#ajax'       => [
      'callback' => 'test_services_search_transfer_callback',
    ],
    '#attributes' => [
      'class'    => ['js-select2', 'cancel'],
      'required' => TRUE,
    ],
    '#title'      => t('Transfer'),
    '#options'    => [
      0 => t('Direct trip'),
      1 => t('Stopover trip'),
    ],
    '#type'       => 'select',
  ];

  return $form;
}

/**
 * Callback handler for the direct/transfer trip select.
 */
function test_services_search_transfer_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

/**
 * Callback function.
 */
function test_services_search_form_callback($form, &$form_state) {
  return $form;
}

The point is disable three fields if option two is selected, It's possible execute AJAX into a block view, and if so, what is going on? Why Drupal is not going into the function of the AJAX callback?
Comment: The code from test.inc needs to be in test.module. This will fix error 1 and may also fix error 2
Comment: I'm gonna try it, but i'm calling test.inc with "module_load_include" in my block view hook, it should works anyways.
Comment: Ok. You are right, i don't understand how, but it works. So I can not split the form code in other file?
Comment: Yes it possible, but your module_load_include call is incorrect, I believe from you oiriginally posted it should be module_load_include('inc', 'test', 'test'), take a look at https://api.drupal.org/module_load_include
Comment: Are you sure? $type (inc) | $module_name (test_services) | $path_to_file (includes/test). I mean, that's the way i was trying to execute ajax, but only works if the form is in the ".module" idk why.
Comment: No I'm not sure, but what you've posted in your last comment is not the same as your initial post. I would suspect you've got different names as the module and the files which is why it's not working. I suggest removing all reference to test as it's confusing, try using foo instead as it's obvious and easily replaceable
Comment: Yes, It's a little messy. I've changed the original proyect name to "test" and it's unclear, but file/module names are ok, they are being called. The only problem is that if the form and ajax call are in test.inc instead of ".module", it fails.
Answer:
I've defined the block view. When I change the selected option, the log gets two errors.

It seems the error happens after you submitting the block. So the file loads fine on view, but not when the form is processed which should have information where to look for it.
So you should define your form using hook_forms.

By default, when drupal_get_form() is called, the system will look for a function with the same name as the form ID, and use that function to build the form. If no such function is found, Drupal calls this hook.

Also, when you working with the forms, instead of drupal_get_form($form_id), you can consider using form_load_include() to make sure the include file is loaded whenever the form is processed.

Use this function instead of module_load_include() from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using module_load_include() directly, form_load_include() makes sure the include file is correctly loaded also if the form is cached.

How to execute ajax into block view


How to oversample only the training set when using cross validation in sklearn

Question: I have an imbalanced dataset, and using oversampling to make it balanced. I am working on a regression problem. For testing purposes I am applying cross validation on the same dataset for now, using scikit-learn's LassoCV().
However, if I do oversampling before CV, then my model easily overfits since the oversampled items will be distributed over training and testing sets during cross validation. I wonder if there is a way to apply oversampling only on the training set after cross validation makes the split. I prefer to use a scikit-learn method, e.g., cross_val_predict. I wonder if it is possible? Or, do I need to write my own code for this task?
Comment: maybe this should have been asked on [Stack Overflow](https://stackoverflow.com/).
Answer: I would argue that you should perform no oversampling at all.
Oversampling almost always arises from using accuracy as a performance metric, since class imbalance can mean that your model with an impressive-looking $98\%$ accuracy is outperformed by a model that predicts the majority class every time and scores $99\%$ accuracy. This is related to my discussions here and here about comparing classification accuracy to the accuracy of such a baseline, "must-beat" model, and I believe that discussion to expose accuracy as being less useful that it might first seem.
However, accuracy is problematic even when the classes are balanced, and metrics like $F_1$ score, sensitivity, and specificity offer minimal improvement. This is because most models do not make hard classifications. They make predictions on a continuum (typically on the interval $[0,1]$), and the hard classifications come from applying some kind of threshold. This is troubling for multiple reasons.

The typical software default of $0.5$ might be wildly inappropriate (even for balanced classes, as Stephan Kolassa explains in his explanation about why accuracy is a problematic performance metric). If there is a small probability of something happening that would lead to a disaster if you miss it, you might be inclined to proceed as if that event will happen, even if it is unlikely. If this sounds silly, perhaps an example will help. There is (hopefully) a pretty small probability of being in a car accident, but there is so little cost to buckling when there is no accident and such a potential cost to not buckling when there is a wreck that most people buckle their seat belts.

It might be that multiple decisions can be made, despite there being only two categories. For instance, an extreme prediction either way might be taken as predicting a categorical outcome, but a prediction in the middle might be more of a signal to collect more information.

Hopefully, some of the below links can convince you of the probabilities being useful and that you need not mess with the data by oversampling in order to get accurate predicted probabilities.
Cross Validated: Why is accuracy not the best measure for assessing classification models?
Cross Validated: Are unbalanced datasets problematic, and (how) does oversampling (purport to) help?
Cross Validated: Academic reference on the drawbacks of accuracy, F1 score, sensitivity and/or specificity
Cross Validated: Calculating the Brier or log score from the confusion matrix, or from accuracy, sensitivity, specificity, F1 score etc
Cross Validated: Upweight minority class vs. downsample+upweight majority class?
Cross Validated Meta: Profusion of threads on imbalanced data - can we merge/deem canonical any?
Frank Harrell's Blog: Classification vs. Prediction
Frank Harrell's Blog: Damage Caused by Classification Accuracy and Other Discontinuous Improper Accuracy Scoring Rules
These links are (shamelessly) taken from an answer I posted in the past few days. I bring this up because class imbalance and what models output seem to be poorly understood by many machine learning practitioners.
Comment: If you insist on oversampling (contractual requirement, reviewer expectation, just want to try it and find out what happens) and just want to know how to do that in Python, then this is really a programming question and is off-topic on Cross Validated.