JMeter Maven disable log

Question: I am facing a matter that I do not success to solve.
I am running JMeter on Jenkins using JMeter Maven Plugin.
When JMeter is started it run the non UI mode and always setup the argument -l to log infos.
That log load of lines and reach giga byte of logs. Resulting disk space to end full.
I wonder how to disable the argument -l. I found no way the control the argument JMeter is launched with.
Through the pom.xml fil I can overwrite jmeter.properties but found no tag to set up the argument for launching.
Thanks in advance.
Answer: As per Basic Configuration page of the plugin documentation:

The following properties files will be used if they are found in ${project.base.directory}/src/test/jmeter:
jmeter.properties
saveservice.properties
upgrade.properties
system.properties
user.properties
global.properties

So you can totally suppress JMeter output like:

Add user.properties file to ${project.base.directory}/src/test/jmeter folder (the same location where your script lives)
Add the following lines to the user.properties file
jmeter.save.saveservice.output_format=csv
jmeter.save.saveservice.assertion_results_failure_message=false
jmeter.ave.saveservice.assertion_results=none
jmeter.save.saveservice.data_type=false
jmeter.save.saveservice.label=false
jmeter.save.saveservice.response_code=false
jmeter.save.saveservice.response_data=false
jmeter.save.saveservice.response_data.on_error=false
jmeter.save.saveservice.response_message=false
jmeter.save.saveservice.successful=false
jmeter.save.saveservice.thread_name=false
jmeter.save.saveservice.time=false
jmeter.save.saveservice.subresults=false
jmeter.save.saveservice.assertions=false
jmeter.save.saveservice.latency=false
jmeter.save.saveservice.connect_time=false
jmeter.save.saveservice.samplerData=false
jmeter.save.saveservice.responseHeaders=false
jmeter.save.saveservice.requestHeaders=false
jmeter.save.saveservice.encoding=false
jmeter.save.saveservice.bytes=false
jmeter.save.saveservice.url=false
jmeter.save.saveservice.filename=false
jmeter.save.saveservice.hostname=false
jmeter.save.saveservice.thread_counts=false
jmeter.save.saveservice.sample_count=false
jmeter.save.saveservice.idle_time=false

Just in case you will need some metrics (i.e. if you decide to perform results analysis) you can enable individual lines.
See Apache JMeter Properties Customization Guide for more information on JMeter properties and ways of setting/overriding them.
Comment: Thank you very much for that clear help. Veru much appreciated.
Comment: It still does produce a .jtl file logging load of lines.
Answer: Have a look at the project wiki:
https://github.com/jmeter-maven-plugin/jmeter-maven-plugin/wiki/Log-Levels
I would guess you probably want this:
<project>
[...]
    <build>
        <plugins>
            <plugin>
                <groupId>com.lazerycode.jmeter</groupId>
                <artifactId>jmeter-maven-plugin</artifactId>
                <version>1.10.1</version>
                <executions>
                    <execution>
                        <id>jmeter-tests</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jmeter</goal>
                        </goals>
                        <configuration>
                            <overrideRootLogLevel>error</overrideRootLogLevel>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
[...]

Comment: I tried it too but it still produce the log with the .July file.
Comment: So you are trying to not create the log file at all, rather than reduce the amount of data that is put in it?

JMeter Maven disable log


How to perform paired sample t-test when the standard error of the difference is zero?

Question: I ran a paired T-test to determine the mean difference between pre and post intervention of one of the variables in my study. However the test was not run as the SPSS output showed "the correlation and t cannot be computed because the standard error of the difference is 0".
What should I do to get the p-value of the mean difference for that variable?
Comment: Is the value of the paired difference exactly the same for every pair? That is what **"the standard error of the difference is 0"** seems to mean.
Comment: I think the difference between your two columns is a constant. Constant has no variability and thus no test can be done.
Comment: Of *course* a test can be done, @ttn: just not a t test!
Comment: Please add some information on what kind of data you have... do you meet the assumptions of the t-test?
Comment: Sorry, @whuber, I meant "no t test..." or "the t-test can't..."
Comment: Thanks Mr Jeromy. I did non parametric test (sign rank) for this variable. In fact, some other variables have the similar results (pre-intervention values = post-intervention value, no different), but I got their p-values. Could anyone help me how to explain "standard error of the difference is 0" and no p-value as in my initial question?
Answer: When the standard error of the difference is 0 then you might go with a non-parameteric test.  A sign test would be good.  Rather than give you the probability on a t-distribution, it gives you the probability of that many successes (differences in the same direction).  That would typically be a meaningful and useful kind of p-value to describe.
The variance of 0 means that all of the differences were the same.  This can happen for a variety of reasons, for example, insensitive measurement, or genuinely extremely low variance of the effect.  Perhaps you even rounded off the variability.  It's very rare though, if you have data that follow the assumption of the t-test.  Your data probably require a non-parametric test in the first place.
Comment: @whuber - the differences aren't 0, they are all the same.  Having said that, unless the sample size is very small, I have a hard time believing this isn't due to a data entry error of some sort, e.g., coding "Yes, this is a pre-intervention observation!" or "No, this isn't a pre-intervention observation!" instead of the variable itself.
Comment: Isn't the situation much, much simpler even than this? Is there *any* admissible test, parametric or not, that would reject a null hypothesis of equal means when every one of the differences equals zero? Whence, to answer the original question directly, why wouldn't the reply "your p-value is 100%" be adequate?
Comment: But the sign test allows you to assume that there is some probability the difference could go the other way.  It's not really a test of equal values but a test of equal probability of the value in a given direction.  It's certainly possible it's much simpler.  I'm all for saying there is no variability in the effect from what we've been given.  However, it's also possible that a sign test is appropriate in the case.  I was considering starting with an answer similar to what you say.  But I was leaving that for someone else.
Comment: yes jbowman, that's a likely cause as well
Comment: @jb Good point! I had blithely assumed all the differences were zero (because almost any other constant value seems so unrealistic). +1.


How to list items in combobox?

Question: I have created a UserForm with an empty ComboBox to be populated with a list of formulated (basic concatenate) text for user to select. I got the below code but failed.
Private Sub specList_change()
    Dim i As Integer
    Dim ListSpec As String
    'Clear whatever in listbox
    Me.specList.Clear
    Me.lineText = ""
    Me.partText = ""
    'Get none empty data from P6:Pxx
    i = 5
    Do
        DoEvents
        i = i + 1
        ListSpec = Sheets("SPEC CHART").Range("P" & i)
        'Add data into the listbox till all data in SPEC CHART worksheet is empty
        If Len(ListSpec) <> 0 Then specList.AddItem (ListSpec)
    Loop Until ListSpec = ""
End Sub

Appreciate your guidance.
Answer: Use UserForm_Initialize event instead.
Private Sub UserForm_Initialize()
    Dim r As Range, lr As Long
    With Sheets("SPEC CHART")
        lr = .Range("P" & .Rows.Count).End(xlUp).Row
        If lr > 5 Then
            Set r = .Range("P6:P" & lr)
            Me.speclist.RowSource = r.Address(, , , True)
        End If
    End With
End Sub

Aslo if the source is a Range, you can use RowSource property.
You can also use the List property like this:
Me.speclist.List = Application.Transpose(r)

That is in place of me.speclist.RowSource = r.Address(, , , True). HTH.

How to list items in combobox?


Changing background image position on hover using javascript

Question: I have 10 links. I am using a separate sprite sheet for a single link which consist of active, hover and inactive link image. I want to know how can i change the background-postion from javascript. I know how to do this in css but for 10 different links i think javascript will a better option as i can use the same code for every link. Waiting for your suggestions.
Comment: Can you show us your HTML and CSS, it's hard to answer otherwise.
Comment: Are you using any JavaScript library?
Answer: you are mistaken: this should be done in CSS, its the fastest to render, even though it takes more initial declarations.
Just make sure your CSS is optimized.
.links{
background:transparent url(sprite.png) 0 0;
}

#link1{
background-position: 0 0;
}
#link1:hover{
background-position: 0 -50px;
}

#link2{
background-position: 100px 0;
}
#link2:hover{
background-position: 100px -50px;
}

And the HTML:
link 1
link 2

If you really, really want to do it in javascript, you're looking for the style() method. See W3Schools on style() and backgroundPosition
Comment: typo in css `#link12` sould be `#link2`
Answer: The best is to use css, even for multiple images.
If the sizing is the same for the sprites of the 10 links, you can make a rule that is agnostic of the image and just repositions the background image
a.someclass:hover{
  background-position:Xpx Ypx;
}

and apply the someclass (or whatever you name it) to all your links...


Integration of Mathjax and JadeJS

Question: I have a problem integrating Mathjax and Jade in Express. I need to show formulas inside a 'pre', so I am trying to configure Mathjax through a script. This is my code:
script(type="text/x-mathjax-config")
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [['$','$'], ['\\(','\\)']],
            skipTags: ["script","noscript","style","textarea","code"]
            }

    });

My problem is that when I try to see the page it throws this error:
SyntaxError: Unexpected token {
at Object.Function (unknown source)
at Object.exports.compile (/home/andres/web/node-login/node_modules/jade/lib/jade.js:176:8)
at Function.exports.compile (/home/andres/web/node-login/node_modules/express/lib/view.js:68:33)
at ServerResponse.res._render (/home/andres/web/node-login/node_modules/express/lib/view.js:417:18)
at ServerResponse.res.render (/home/andres/web/node-login/node_modules/express/lib/view.js:318:17)
at Promise.module.exports.app.get.Pregunta.find.exec.questions (/home/andres/web/node-login/app/server/router.js:240:16)
at Promise.addBack (/home/andres/web/node-login/node_modules/mongoose/lib/promise.js:128:8)
at Promise.EventEmitter.emit (events.js:88:17)
at Promise.emit (/home/andres/web/node-login/node_modules/mongoose/lib/promise.js:66:38)
at Promise.complete (/home/andres/web/node-login/node_modules/mongoose/lib/promise.js:77:20)

Does anyone know what might be happening?
Thank you.
Answer: The issue appears to be with the type='text/x-mathjax-config'. If I remove that, the view renders fine. If I leave it as it is, jade interprets the script contents as jade tags. I don't think this is a bug in jade, since text templates should be able to be able to be written in jade as well.
In any case, it looks like mathjax requires the type in order to execute the configuration properly, so we need to work around that issue. The easiest solution is simply to keep everything as it is but add a . at the end of the script tag. This will make everything under it a text literal.
script(type="text/x-mathjax-config").
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [['$','$'], ['\\(','\\)']],
      skipTags: ["script","noscript","style","textarea","code"]
    }
  });

Alternatively, maybe you could configure mathjax after the page is loaded, as seen here. Note that I know nothing about mathjax, I just glanced at the documentation.

Integration of Mathjax and JadeJS


How to use regex to match a group multiple times

Question: Sorry for the bad title, I didn't know how to word this properly.
I have a URL such as /colour-white/size-large/, and I need to rewrite it in htaccess.
String should look like &colour=white&size=large after regex.
I don't want to have to make multiple rewrites for colour, size, colour and size.
I've come up with (colour|size)-(.*?)\/ on string colour-white/size-large/ with a substitution of $1=$2& which returns colour=white&size=large&, but it breaks when there's a / at the start, and I don't want the final string to have a trailing &.
Edit: \/*(colour|size)-(.*?)\/ &$1=$2 works, but it breaks once there's other text before it, I guess because with the global option it tries to match the before text each time it looks for colour or size.
Comment: What are the URLs you need to rewrite from/to? Is there always a set number of parameters? Or could this vary? In a specific order?
Comment: It will always be colour, then size. URL example would be example.com/(dresses)/colour-white/size-large/. That URL currently has a rewrite of `^dresses\/colour-(.*?)\/rarity-(.*?)\/?$ ?category=$1&colour=$2&rarity=$3 [NC,L]`. Doing a rewrite for each time I have a different filter (colour/size) will just exponentially add more lines to the htaccess.
Answer: It is pretty common to add multiple rewrite rules for different numbers of parameters.  This works, including what comes before it ("dresses") for up to three parameters.  Adding a 4th parameter is just a fourth line.  The number of rules needed increases linearly with the number of parameters, not exponentially.
RewriteEngine on
RewriteRule /?(.*/)?(colour|size|rarity)-([^/]+)/(colour|size|rarity)-([^/]+)/(colour|size|rarity)-([^/]+)/ $1?$2=$3&$4=$5&$6=$7 [L]
RewriteRule /?(.*/)?(colour|size|rarity)-([^/]+)/(colour|size|rarity)-([^/]+)/ $1?$2=$3&$4=$5 [L]
RewriteRule /?(.*/)?(colour|size|rarity)-([^/]+)/ $1?$2=$3 [L]

Another approach is to pass all of it as a single parameter and parse it in your handler.  It is much cleaner to do parsing of arbitrary parameters in PHP, Java, Perl or whatever your back end language happens to be. This code would put an arbitrary number of them into the "options" parameter to be parsed on the back end:
RewriteEngine on
RewriteRule /?(.*/)?(colour|size|rarity-[^/]+/)+ $1?options=$2 [L]

You should also take a step back and ask if this is something you actually want or need to be doing.  Sticking arbitrary parameters into the URL path is no more SEO friendly than having them in the query string.  Your best URL may actually be /dresses?size=large&colour=blue  You can read my full reasoning in my answer to SEO-friendly way to pass multiple values in a URL parameter


How can I make my Player jump when I press a UI button? (Unity)

Question: I'm having a bit of a issue on one of my projects. So I'm trying to make my character jump when I press a UI button, but I haven't been able to make it work thus far. I tried adding a Rigidbody to my Player and just doing:
<code>public Rigidbody rb;
public void onJumpButton()
{
rb.AddForce(Vector3.up* jumpForce);
}
</code>
and this is on my buttons On Click () function but that didn't work.
I already have jumping figured out on the pc and for pc my code is:
<code>   if (controller.isGrounded)
    {

        verticalVelocity = -gravity * Time.deltaTime;
        if (Input.GetKeyDown(KeyCode.Space))
        {

            verticalVelocity = jumpForce;
            animator.SetBool("is_in_air", true);
            jump.Play();

        }

    }
    else
    {
        animator.SetBool("is_in_air", false);
        verticalVelocity -= gravity * Time.deltaTime;
    }
</code>
and this works fine when i press space on PC but I need to incorporate this into a UI button for Cellphone use. If anyone has any tips on how I can do this that would be greatly appreciated.
Thanks for your time!
Comment: Rigidbody can not work with CharacterController
Comment: Yes I noticed that, I removed the rigidbody and that piece of code after trying it and seeing that it didnt work.
Comment: If you remove the rigidbody then what's in `onJumpButton` method?
Comment: Well right now it woulld be nothing. That is what I need help with, I can't figure out how to make it jump when pressing the button since the Rigidbody didn't work. The jump method I have for Space works fine, but I don't know how to make that work in the `onJumpButton`
Answer: Why don't you just use the same function if it works ? Move all your jumping code in a function, then call that function on user input and in the OnClick() of your button
Comment: I tried using the same code in the function and the OnClick() of my button but it did not work the same way, my Player just ends upp jumping constantly in a loop.


Android data backend one way synchronisation

Question: I create a monitoring application who :

if there is a network connection available : she sends periodically
measurement data to the server using json
if there is no network available, she stores the data in the sd card and sends it when the network connection is back.

Actually I use a circular buffer in memory that I empty when data are sent
Is there already something usefull in the framework or I have to write that completly ?
Thanks
Answer: I would check tape library from square. I've never tried it but looks what you are looking for.


Visualizar no browser arquivo pdf com url no database

Question: Olá!
Possuo uma aplicação que faz o upload do arquivo PDF cuja url está salvo no banco e o arquivo em uma pasta. Ao clicar no botão view o arquivo pdf abre no navegador.
<button type="button" class="button btn btn-link">View</button>

Este é meu view.php:
  <?php
      header('Content-type: application/pdf');
      echo $row['arquivo'];
  ?>

Não sei o que fazer. Alguém pode me ajudar?
Answer: Está fazendo um pouco de confusão no código.
O seu link deve abrir uma URL tipo esta:
http://seusite/view.php?pdf_id=24
Na sua página de exibição view.php:
$pdf_id= $_REQUEST['pdf_id'];
AQUI VAI A CONSULTA SQL para recuperar URL e arquivo.

Comment: Como ficará o View.
Answer: Olá.
No caso, meu arquivo view.php ficaria assim? :
<?php
  $pdf_id = $_REQUEST['arquivo'];

  header('Content-type: application/pdf');
  echo $pdf_id;
?>

e meu button como ficaria?
<button type="button" class="button btn btn-link">View</button>


How do I know what each hand should play when I only have chord names

Question: I have self taught how to play  a few of elevation worship song on the piano by watching someone play. I have had no formal music training but learning as I go.
So this is my basic question: when looking at a chord sheet
VERSE 1:
               F                             Bb
When the weight of life begins to fall
           F                           Bb
On the Name of Jesus I will call
          F                            Bb
For I know my God is in control
            F                        Bb
and His purpose is unshakable
Since it show a F and a Bb  I assume that you play a F octave with the left hand and a F chord/triad with the right hand. Then for the Bb play a B octave with the left and a Bb with the right.
Is this how I should read and play the above for all music?
Since the "F" does not say exactly what each hand does?
Answer: You're right that the chords don't say exactly what each hand should do. You are free to play the chords as you see fit as along as you stay within the boundaries of the chord. The way you described is one very simple way to do it, except that you would play a B flat in your left hand for the B flat chord instead of a B (was that a typo?). There are many variations and embellishments you could use to make that pattern more interesting, as you no doubt have learned. It would not be a very sophisticated accompaniment if all you played were the tonic in the base and triad with your right hand.
Answer: Octave with the left and triad with the right is typical (you can also experiment with adding the fifth with the left hand, e.g. F C F). Also experiment with different inversions of the right hand triad - you may want to have the highest note of the triad correspond with the sung note at the point you play the chord.
Answer: Octave in the left hand and triad in the right hand is a good starting point, it will work fine most of the times, but eventually you will want to do something different or more sophisticated.
Here are some things you can think of:

Adding notes to the chords, like 7th, 9th, 6th..
Playing arpeggios with the right hand, using the notes of the triad;
Playing a second voice, or the melody, with the top notes of the right hand, like @MotherBrain suggested;
Applying rhythm to the left hand, using the notes of the octave and maybe the fifth, like @MotherBrain said;
Playing a bass line with the left hand, if there is a nice one in the song for example;

To start, you could try to apply some of these separately in this song, then try some combinations, and maybe other songs. With time you will come up with other cool stuff to do.


New Relic performance monitoring and the Features Module

Question: We've just started using New Relic to monitor our D6 sites, and are also taking advantage of New Relic's ability to report on Drupal module performance.
Our sites contain several modules with configuration exports that are controlled by Features (views, content types, etc).
New Relic's module performance page shows features.module as being the slowest and as having the highest function call count.
It was my understanding that Features doesn't do too much of anything except for when you are creating/updating/reverting your features, so I'm confused as to why New Relic would report it as being such a drag in terms of site performance.
Can anyone confirm that Features does indeed significantly impact site performance? Or confirm that it doesn't (in which case this seems like a New Relic issue).
Comment: I do have seen Features doing crazy things as well. Not sure if on normal page requests but certainly on cache clears. It seems to be doing crazy things like re-saving fields and field instances. I have not found time yet to look into it, however.
Answer: By design, Features shouldn't induce any performance hit besides what is inherent to any Drupal module.  It doesn't implement hook_init() or hook_boot(), nor does it implement any hook_form_alter()s or Node API hooks, so there should literally be no Features activity on most page loads.
However, every time caches are cleared, Features does some heavy work — it interrogates all Feature modules and rebuilds Faux-Exportables.

There are two kinds of Features Components: Exportables and Faux-Exportables.
Exportables
Anything that is a CTools Exportable is also a Features Exportable, such as Views, Contexts and Panels.
On this issue thread, one of the Features maintainers says:

Generally speaking a View in the database and a View in code perform exactly the same. There are some slight differences in loading methodology (it helps to have a good PHP code cache like xcache or APC when using exportables as the data lives in code), but other than that you shouldn't see any differences.

Faux-Exportables
Faux-Exportables include content types, CCK fields, taxonomy, roles, and permissions.
Faux-Exportables are by definition stored in the database, so they do not require any intervention from Features.  Features only touches Faux-Exportables when rebuilding (as mentioned above).


How can I hide the "Actions" panel / tab / pane in Windows "Event Viewer"?

Question: I want to get rid of the "Actions" panel in the Event Viewer.  It doesn't help me. I've made it as small as possible but I just want to hide it.
Answer: Click View>Customize and uncheck the Action pane checkbox.
Answer: Just uncheck "Display Action Pane"


Se usar libs "provided" no servidor de aplicações (wildfly), eu ganho performance?

Question: imaginem o seguinte cenário. Eu tenho um servidor de aplicação WildFly 8.0.0 rodando com configurações default de "fábrica". Nesse servidor eu rodo 4 aplicações web simples. Essas aplicações usam algumas libs iguais como:

Spring Framework;
Primefaces;
Spring Security;
...

Só que cada aplicação empacota as libs que ela própria usa. Então ela empacota os jars do spring, do primefaces, alguns commons e assim vai. Na verdade todas as aplicações fazem esse empacotamento em WEB-INF/lib. Inclusive elas empacotam a mesma versão do Spring, do Primefaces...
Agora vem algumas dúvidas:

Se eu retirar as libs comuns entre as aplicações e colocar no WildFly /standalone/lib e setar essas libs como provided eu ganharia performance nessas apps?
Caso haja versões diferentes empacotadas nas aplicações, isso pode dar problema? Por exemplo: em uma aplicação eu coloco o Spring 3.0 e na outra empacoto o Spring 4.0. Isso pode gerar conflito em alguma das aplicações ou o WildFly isola essas libs para uma não interferir na outra?
Answer: Em tese você pode ter vários benefícios ao usar compartilhar as mesmas bibliotecas entre as diversas aplicações:

Menor uso de memória, já que haverá apenas uma instância de cada classe, no Classloader das bibliotecas compartilhadas, ao invés de uma para cada cada aplicação, no Classloader particular criada para cada uma delas.
Menor tempo de inicialização, pois o servidor de aplicação não precisará carregar todas as classes novamente no deploy.
Menor uso de banda e deploy mais rápido, pois o pacote fica bem menor. Aplicações Java que tenho visto possuem pacotes na faixa de 50 a 100MB, só que o código da aplicação em si tem em geral 10% desse tamanho, sendo o resto apenas composto por bibliotecas de terceiros.
Melhor desempenho, se considerarmos a maior possibilidade de utilização de cache que a JVM e o sistema operacional podem fazer já que as classes executadas são as mesmas.

Porém, existem também algumas desvantagens:

Todas as aplicações precisam estar atualizadas para usar as mesmas versões de todas as APIs, o que é frequentemente inviável num ambiente corporativo.
A atualização de uma API precisa ser sincronizada com a atualização de todas as aplicações, o que dificulta muito a administração dos servidores.
A montagem do pacote WAR ou EAR das aplicações deve ser cuidadoso, pois se uma aplicação contiver as mesmas dependências da lib compartilhada, poderão ocorrer os "temidos" conflitos de Classloader, que geram erros bizarros e difíceis de identificar.

Falando mais especificamente sobre os problemas de classes diferentes em Classloaders diferentes, isso não dignifica que sempre ocorrerão problemas. Mas se houverem duas versões da mesma biblioteca, pode ocorrer do Wildfly carregar as classes que você não gostaria que ele carregasse.
Isso ocorria muito comigo comigo no Tomcat. A regra geral é: o container sempre vai carregar a versão incorreta da classe!
Outra abordagem que daria um pouco mais de flexibilidade é o uso de módulos. Você poderia empacotar cada framework em um módulo customizado e fazer suas aplicações dependerem desses módulos. Esta é uma alternativa interessante porque permite cada aplicação usar apenas as libs necessárias e inclusive versões diferentes do mesmo framework.
A criação de módulos é uma técnica comum para adicionar novos drivers de bancos de dados, como descrito neste link.
Comment: Exatamente o que eu precisava. Então, se teoricamente, eu estabelecer uma arquitetura bem definida de componentes em versões entre as aplicações além de definir um desenvolvimento "estrito", vai tender a facilitar depois a atualizações de componentes. Porém esse cenário nunca é perfeito. Obrigado!


Background images using Breakpoints and Picture

Question: I want to serve my background images by breakpoints.  I can't seem to find an out of the box way to do this using the Breakpoints and Picture modules, which I'm using for some node images.
Has anyone implemented this using Picture/Breakpoints?
Comment: What do you mean by "serve images by breakpoints"?
Comment: And is there any theme you use like Omega or Zen? Please explain better what you try to do and what you have so far.
Comment: I'm using Omega 3.  Currently I use a background image for the front page, and they are high def images.  So, I want to use a version of the image according to the size of the browser display.
Answer: My solution was to use Group Background Image with the patch that you can get here. This allows background images, through the integration of the Picture and Breakpoints modules. The configuration is super easy, and you can change existing div field groups into background images in a split second.


Simple web server using C programming

Question: I need to develop a web server using c in Linux. Using that we need to start and configure services. is their any help like pseudo code or sample programs like that.
Comment: Can you elaborate more on those services :) Also is this an academic project ?
Comment: its not an academic project. actually i am doing an embedded web service.. but i am new to this so i started with a simple one.
Comment: services like starting Apache and configuring it using this webservice
Answer: http://www.gnu.org/software/libc/manual/html_node/Server-Example.html
This is a simple multi-user web server built in C. I had to do one of these last year for a class, and I find it quite cool, though a little bit frustrating.
Answer: The Apache HTTP server, the world's most popular HTTP server, is written in C.  Its documentation, and source downloads are located here

Simple web server using C programming


Puppet agent cannot find environment

Question: Puppet master can find the environment,
<code>[user@puppetmaster]$ sudo puppet agent --configprint modulepath
/etc/puppet/environments/development/modules:/etc/puppet/modules:/usr/share/puppet/modules
</code>
but the agent cannot:
<code>[user@puppetagent]$ sudo puppet agent --configprint modulepath
/etc/puppet/modules:/usr/share/puppet/modules
</code>
puppet.conf
<code>[main]
environmentpath = $confdir/environments

[agent]
environment=development
</code>
Answer: Are both pieces of output from different hosts?  They both say "user@host".
If the second is from another server, which is a client of the Puppet master, then this seems entirely fine.  The agent doesn't know or care about the modulepath, it's part of the master configuration only, which compiles the manifests into a catalog for the agent.
If you're experiencing a problem that's led you to look at this setting, perhaps re-post with details of that issue.
Comment: Pieces are from different hosts. As a workaround a `basemodulepath` has been overwritten in the puppet.conf that resides on the agents. The expectation was that changing it on the master would be sufficient for agents to find the right environment.

Puppet agent cannot find environment


Erro ao tentar salvar registro no banco

Question: Após preencher o formulário e clicar em Salvar, está ocorrendo o erro abaixo:
mai 20, 2016 7:14:52 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: javax.el.PropertyNotFoundException: /web/crud/cadastrar-habilidade.xhtml @16,80 value="#{habilidademb.habilidade.nome}": Target Unreachable, 'habilidade' returned null
    at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
    at org.primefaces.util.ComponentUtils.getConverter(ComponentUtils.java:144)
    at org.primefaces.renderkit.InputRenderer.getConvertedValue(InputRenderer.java:171)
    at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1045)
    at javax.faces.component.UIInput.validate(UIInput.java:975)
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1248)
    at javax.faces.component.UIInput.processValidators(UIInput.java:712)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1260)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1260)
    at org.primefaces.component.panel.Panel.processValidators(Panel.java:287)
    at javax.faces.component.UIForm.processValidators(UIForm.java:253)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1260)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1260)
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.el.PropertyNotFoundException: Target Unreachable, 'habilidade' returned null
    at org.apache.el.parser.AstValue.getTarget(AstValue.java:124)
    at org.apache.el.parser.AstValue.getType(AstValue.java:58)
    at org.apache.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:168)
    at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
    ... 38 more

Minha classe bean:
package br.com.evolutionary.controle;

import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import br.com.evolutionary.modelo.Habilidade;
import br.com.evolutionary.negocio.HabilidadeDAO;

@SessionScoped
@ManagedBean(name = "habilidademb")
public class ControleHabilidade {

    private Habilidade habilidade;
    private HabilidadeDAO dao;
    private Logger log;
    // Variáveis para receber o valor booleano do atributo habilidadeHidden
    private boolean habilidadeHidden;

    public Habilidade getHabilidade() {
        return habilidade;
    }

    public void setHabilidade(Habilidade habilidade) {
        this.habilidade = habilidade;
    }

    public HabilidadeDAO getDao() {
        return dao;
    }

    public void setDao(HabilidadeDAO dao) {
        this.dao = dao;
    }

    public boolean isHabilidadeHidden() {
        return habilidadeHidden;
    }

    public void setHabilidadeHidden(boolean habilidadeHidden) {
        this.habilidadeHidden = habilidadeHidden;
    }

    public void salvar() {
        habilidade = new Habilidade();
        FacesMessage facesMsg;
        try {
            if (habilidade.getId() == null) {
                dao.insert(habilidade);
                facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Habilidade cadastrada com sucesso!", "");
                FacesContext.getCurrentInstance().addMessage("messagePanel", facesMsg);
            } else {
                dao.update(habilidade);
                facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Habilidade alterada com sucesso!", "");
                FacesContext.getCurrentInstance().addMessage("messagePanel", facesMsg);
            }

        } catch (Exception e) {
            facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro:" + e.getMessage(), "");
            FacesContext.getCurrentInstance().addMessage("messagePanel", facesMsg);
            log.warning("Erro: " + e.getMessage());
            return;
        }
    }

    public void novo(){
        habilidade = new Habilidade();
    }

}

Minha entidade:
package br.com.evolutionary.modelo;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotBlank;

@Entity
@Table(name="tb_habilidade")
public class Habilidade implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    @Column(length=20,nullable=false)
    private String nome;

    @NotNull
    @Column(length=150,nullable=false)
    private String descricao;

    @Column(name="efeito_secundario",nullable=true)
    private String efeitoSecundario;

    @Column(length=20,nullable=true)
    private String habilidadeHidden;

    @Column(length=150,nullable=true)
    private String descricaoHA;

    public Habilidade() {
        super();
    }

    public Habilidade(String nome, String descricao, String efeitoSecundario) {
        super();
        this.nome = nome;
        this.descricao = descricao;
        this.efeitoSecundario = efeitoSecundario;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEfeitoSecundario() {
        return efeitoSecundario;
    }

    public void setEfeitoSecundario(String efeitoSecundario) {
        this.efeitoSecundario = efeitoSecundario;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public String getHabilidadeHidden() {
        return habilidadeHidden;
    }

    public void setHabilidadeHidden(String habilidadeHidden) {
        this.habilidadeHidden = habilidadeHidden;
    }

    public String getDescricaoHA() {
        return descricaoHA;
    }

    public void setDescricaoHA(String descricaoHA) {
        this.descricaoHA = descricaoHA;
    }

}

E o meu xhtml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <title>Cadastro</title>
</h:head>
<h:body>
    <h:form id="cadastro">

            <h:panelGrid columns="3">
                <h:outputLabel value="Nome: " rendered="true" />

                <h:outputLabel value="Descrição: " rendered="true" />

                <h:outputLabel value="Possui efeito secundário? : "/>

                <h:outputLabel value="Efeito Secundário: " rendered="#{habilidademb.habilidadeHidden == true}"/>

            </h:panelGrid>

    </h:form>
</h:body>

Onde estou errando?
Answer: Sua classe Habilidade possui dois construtores, conforme você declarou, porém, no método Salvar, você instanciou em habilidade somente pelo construtor padrão, que no caso, não atribuiu qualquer valor as propriedades da classe.
Inclusive, o atributos nome e descrição não aceitam nulo. Conforme declarou na classe Habilidade.
Quando fizer get em habilidade, ela estará null.
Utilize:
public void salvar() {
    habilidade = new Habilidade(nome, descricao, efeitoSecundario);

Erro ao tentar salvar registro no banco


Nested Repeaters Using Table Tags

Question: I am using the following code to try and use nested repeaters in WinJS:

            

However, it is not rendering any results for the 2nd repeater.
When I use the same data source and similar markup using DIVs, it works:

I don't really want to use Divs as this is tabular data. Any idea why using table tags behaves differently?
Answer: Did you assign give data to your outer repeater?
The following works in a blank project for me:

Answer: Try replacing
data-win-bind="winControl.data: ch"

with:
data-win-options="{data: ch}"

Comment: Unfortunately this results in a runtime error:
Unable to get property 'render' of undefined or null reference

I don't think the data-win-bind syntax is the problem as it works when using a div solution rather than tables

Nested Repeaters Using Table Tags


How to active payment pane in Commerce Kickstart?

Question: I am using Commerce Kickstart and I am trying to configure the checkout process.
But control is not going in payment module. Instead it's going in last step directly.
Can anybody help me find out what is wrong?
Answer: I think you are looking for Commerce Checkout Pane Payment or Commerce Checkout Pages.
Commerce Checkout Pane Payment Module Feature:

This module creates a Checkout Pane that shows the selected payment method on the review page of the checkout. This is a contrib module for Drupal Commerce.
Drupal Commerce Contrib. This module creates a Checkout Pane that shows the selected payment method on the review page of the checkout.
Commerce Checkout Pages Module Feature:

Commerce Checkout Paages gives site administrators the ability to create additional pages for the checkout process through the admin user interface.
Comment: i appreciate ur answer, but while in checkout process m not able to view payment pane its jumping direcrtly to last step
Comment: yepp, i installed this module,and its giving me permission to customize panes but,checkout->shipping->review order->payments->order confirmation in these step controll is going upto shipping and directly jumping to last step
Comment: i suggest you to check after adding new page weather it go through the new step or skip
Comment: m using kickstart,
Comment: as usual it checkout process is already there,onlt thing is controll is not going in payment pane
Comment: this part needs to debug i think !!!!!!!!!
Comment: yup, i have installed new kickstart but problem persists in new and old one as well thanx..!
Comment: I have the same problem in commerce kickstart demo version...Is it Fix???


How to open sites from same network?

Question: I have setup few websites on IIS 7.5.
All are working fine.
I have set binding for all sites like
1. http www.example.com 80 unassigned (http://www.example.com)
2. http example.com 80 unassigned (http://example.com)
3. http 80 unassigned (http://localhost/)
Now if I try 1 and 2 I get router page, because I am on same network as my server.  (that's ok) From outside network its working fine.
To view website I use http://server-name/ and it works because of binding no. 3.
Now 3rd binding i.e. localhost can only be set on one website on IIS.
I need that I will be able to access all my sites from local. Maybe Like:
http://server-name/site1
http:// server-name/site2
Please let me know how can I do this in one or the other way?
Answer: I know of three ways to do this:

Modify your local hosts file. Modify your hosts file (in c:\windows\system32\drivers\etc\hosts) to put 'example.com' on the internal IP address.
Use split DNS. Change the internal DNS server to serve up example.com on an internal address instead of the external address.
Use a separate domain. Set up new sites on new names (example-internal.com or internal.example.com for instance) that you then enter into your internal DNS using the internal IP address.

All of these will allow you to use name-based virtual hosts from inside your network.
Comment: I don't understand, how to do any of these? Can you get me help link to do this?
Comment: @CharandeepSingh Then #1 is probably your best bet. The file has some example entries in it to get you started.
Comment: What I have done for now, I open a set of ports like 1000-1100 in firewall, and set one port per site. Like `example.com 1000 unassigned` so it works like http://server:1000/ etc.
Comment: Hello again, #1 works great. I just added domain names in my `hosts` file, its started working. Thanks a lot!

How to open sites from same network?


Force reloading template from a Flask app?

Question: I have a Flask app where I'd like for users to see the effect of selecting a different set of parameters in real time.  So I have a slider displayed on the web page, and after the user selects a different parameter, I'd like to force a re-calculation of my model and re-display of the web page.
Here's what I tried:
In my html:

         <input type="range" min="1" max="100" value={{ slider_value }} class="slider" id="myRange">

Value:

https://v2.vuejs.org/v2/guide/computed.html#Watchers
an example of the sort of thing I was hinting at in my comment.


touch events not firing in safari desktop

Question: I'm developing an app that would support touch events on desktop and mobile devices.
when using something like (per https://developer.apple.com/library/safari/#documentation/appleapplications/reference/SafariWebContent/HandlingEvents/HandlingEvents.html )
<code>element.addEventListener("touchstart", touchStart, false);
element.addEventListener("touchmove", touchMove, false);
element.addEventListener("touchend", touchEnd, false);
element.addEventListener("touchcancel", touchCancel, false);
</code>
these only fire when testing on ipad and iphone, not on desktop. Since I'm developing on desktop, how could I make so these events are recognized?
Answer: You could view your website in iOS simulator, that is included in XCode on MacOs.
Hope it helps.
Comment: any chance you can help http://stackoverflow.com/questions/11888133/touchmove-event-on-mobile-safari-causes-the-whole-page-to-be-dragged
Answer: On the test machines we use phantom limb to simulate touches. It's easy to setup and also won't do anything if the device supports touch natively.
Otherwise follow Alexey's advice and use the Simulator and a real device as often as possible.


Deploy Angular 8 Heroku

Question: Estou a realizar o Deploy de uma aplicação em Angular8, porem parece que o Angular não esta sendo construindo nesse processo. É possível inspecionar o código no navegador, porem nada é renderizado. Segue abaixo as configurações e os logs da Heroku:
       Detected both "build" and "heroku-postbuild" scripts
       Running heroku-postbuild

       > firstname.lastname@example.com heroku-postbuild /tmp/build_4d098a2e09d8365e718fcb24180e2544
       > npm run build:prod

       > firstname.lastname@example.com build:prod /tmp/build_4d098a2e09d8365e718fcb24180e2544
       > ng build --prod
    -----> Build succeeded!
-----> Discovering process types
       Procfile declares types     -> (none)
       Default types for buildpack -> web
-----> Compressing...
       Done: 41.3M
-----> Launching...
       Released v13
       https://capitu.herokuapp.com/ deployed to Heroku

O meu package.json possui a seguinte configuração:
{
  "name": "chat-bot",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "node server.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "./node_modules/.bin/ng build --prod",
    "build:prod": "ng build --prod",
    "heroku-postbuild": "npm run build:prod"
  },
  "engines": {
    "node": "v10.16.3",
    "npm": "5.8.0"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~8.2.7",
    "@angular/common": "~8.2.7",
    "@angular/compiler": "~8.2.7",
    "@angular/core": "~8.2.7",
    "@angular/forms": "~8.2.7",
    "@angular/platform-browser": "~8.2.7",
    "@angular/platform-browser-dynamic": "~8.2.7",
    "@angular/router": "~8.2.7",
    "express": "^4.17.1",
    "path": "^0.12.7",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.5",
    "@angular/cli": "~8.3.5",
    "@angular/compiler-cli": "~8.2.7",
    "@angular/language-service": "~8.2.7",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "api-ai-javascript": "^2.0.0-beta.21",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  }
}

E por fim o server.js esta configurado no formato abaixo para rodar a aplicação angular:
//Install express server
const express = require('express');
const path = require('path');

const app = express();

// Serve only the static files form the angularapp directory
app.use(express.static(__dirname + '/src'));

app.get('/', (req,res) => {

res.render(__dirname + '/index.html')
});

// Start the app by listening on the default Heroku port
app.listen(process.env.PORT || 8080);

Segue abaixo o link da aplicação na Heroku:
https://capitu.herokuapp.com/
Comment: Se vc rodar o ng build --prod ele gera o dist normalmemente?
Comment: Sim eu entrei no CLI da Heroku e a dist esta gerada normalmente....
Answer: Eu comparei com o meu sistema e tem uma coisas diferentes.
"scripts": {
"ng": "ng",
"start": "node server.js",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"heroku-postbuild": "ng build --prod"},

E as dependências do "devDependencies", tem que ficar dentro da chave "dependencies",
Feito essas configurações meu deploy subiu corretamente.
Comment: Seria possivel postar o seu .json completo se fosse possível para que eu possa analisar
Answer: Caso alguem passe pelo mesmo erro as configurações da package.json estão corretas.
Deve-se apenas apontar os arquivos estáticos do node.js para a dist compilada do Angular
ficando com a seguinte configuração o server.js
const express = require('express');
const path = require('path');

const app = express();

// Serve only the static files form the angularapp directory
app.use(express.static(__dirname + '/dist/chatBot'));

app.get('/', function(req,res) {

res.sendFile(path.join(__dirname+'/dist/chatBot/index.html'));
});

app.listen(process.env.PORT || 8080);

Caso tenha duvidas da configuração da dist no terminal dentro da pasta do projeto basta apenas rodar o comando:
heroku run bash

E ver as configurações

Deploy Angular 8 Heroku


Javascript/HTML form redirects to a url path based on 2 dropdown answers (Shopify)

Question: I'm creating a product finder on my Shopify site that redirects customers to a specific path upon form submission based on their answers to 2 dropdowns, but the form submission is appending responses as search (?genre=fiction) instead of a path (/fiction/) for both answers.
Target scenario:
Dropdown 1 answer: fiction
Dropdown 2 answer: bestsellers
--> Clicking submit would take you to /fiction/bestsellers
Note that since the options are displayed in a text form "I'm looking for fiction books that are bestsellers" there's a pre-filled default scenario for "I'm looking for any books that have any theme, so the script can't just run on selection change.
Comment: It would be a good idea to provide an example of your code - like the form and you attempt to solve the problem. See [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)
Answer: First, you will need to get the value of both select boxes. Then using document.location.href you can redirect to any page. You can add more value in the finalURL using "+" same as this example.

      <title>jQuery Redirect OnClick</title>

<select id="first">
    <option value="fiction">fiction</option>
    <option value="fiction1">fiction1</option>
</select>

<select id="second">
    <option value="bestsellers">bestsellers</option>
    <option value="bestsellers1">bestsellers1</option>
</select>
<button  id="open_same_window">Submit</button>


Substitute 'Group By' & 'Having' query with 'ALL'

Question: The schema:
Movie(mID int, title text, year int, director text);
Reviewer(rID int, name text);
Rating(rID int, mID int, stars int, ratingDate date);

I made this simple query which returns the max movie rating, per film.
select title,stars from movie join rating Using(mID)
group by title
HAVING MAX(stars)

I've been trying to make this query without using Group By, Having and MAX, but I can't seem to get my query working.
This is what I have so far:
select title,stars from movie join rating r1 Using(mID)
where stars >=
    ALL(select stars from rating r2 where r1.rID=r2.rID AND r1.mID=r2.mID)

And this just seems to throw me this error: near "all": syntax error: and I'm using DB browser for SQL Lite.
Answer: This query:
select title, stars
from movie M1 join
     rating
     Using mID
group by title
having MAX(stars)

Doesn't do anything sensible -- with respect to the having clause.  All it does is filter out rows where max(stars) is not zero or NULL.  Probably not what you intend.
My guess is that you want the movie with the highest star rating.  If one such movies is fine:
select title, max(stars) as stars
from movie M1 join
     rating
     Using mID
group by title
order by stars desc
limit 1;


Pfsense 2.02 unstable ipsec vpn.Tunnels will come up upon restarting raccon

Question: Pfsense 2.02 Ispec VPN tunnels drops randomly,but when the raccon service is restarted all tunnels are back up.Here is my ipsec vpn configuration.Any fix on this issue?
I have tried enabling and disabling "Prefer older IPsec SAs" and also tried disbaling and enbaling DPD but still no luck.I have to restart raccon daily to keep the tunnels alive.Is this a BUG?
Phase 1

Authentication method : Mutual PSK
Negotiation mode : Aggressive
Policy Generation :Default
Proposal Checking : Obey
Encryption algorithm : 3DES
Hash algorithm : SHA1
DH key group : 5
Life time :28800
NAT T    : Disabled
DPD  : enabled(60 secs and 5 retries)

Phase 2

Protocol :ESP
Encryption algorithms: 3DES
Hash algorithms: SHA1
PFS key group : 2
Life time : 1800

racoon: [---------]: INFO: initiate new phase 1 negotiation: x.x.x.x[500]<=>x.x.x.x1500]
racoon: [---------]: INFO: IPsec-SA request for x.x.x.x1 queued due to no phase1 found.
racoon: ERROR: failed to begin ipsec sa negotication.
racoon: ERROR: phase1 negotiation failed due to send error.b52634c42b55942e:0000000000000000
racoon: INFO: begin Aggressive mode.
Answer: That's likely the same cause as I described here:
Pfsense 2.02 ipsec vpn tunnel goes down randomly
misconfigured "Server IP" on PPTP server.


Configuring Shibboleth SAML 2.0 with ADFS 3.0 with Fedration Errors

Question: I'm trying to configure ADFS 3.0 and SAML 2.0. Currently, I get this error whenever I restart shibd and httpd.
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 2702, message: grammar not found for namespace 'http://docs.oasis-open.org/wsfed/federation/200706'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 2702, message: attribute 'ServiceDisplayName' is not declared for element 'RoleDescriptor'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 3893, message: no declaration found for element 'fed:ClaimTypesRequested'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 24931, message: no declaration found for element 'fed:TargetScopes'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 26031, message: no declaration found for element 'fed:ApplicationServiceEndpoint'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 26285, message: no declaration found for element 'fed:PassiveRequestorEndpoint'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 26473, message: element 'fed:ClaimTypesRequested' is not allowed for content model '(Signature?,Extensions?,KeyDescriptor*,Organization?,ContactPerson*)'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 26848, message: grammar not found for namespace 'http://docs.oasis-open.org/wsfed/federation/200706'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 26848, message: attribute 'ServiceDisplayName' is not declared for element 'RoleDescriptor'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 28026, message: no declaration found for element 'fed:TokenTypesOffered'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 28193, message: no declaration found for element 'fed:ClaimTypesOffered'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 49245, message: no declaration found for element 'fed:SecurityTokenServiceEndpoint'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 49941, message: no declaration found for element 'fed:PassiveRequestorEndpoint'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 50129, message: element 'fed:TokenTypesOffered' is not allowed for content model '(Signature?,Extensions?,KeyDescriptor*,Organization?,ContactPerson*)'
2016-11-07 12:49:08 ERROR OpenSAML.MetadataProvider.XML : error while loading resource (https://c-adfs01.contoso.com/FederationMetadata/2007-06/FederationMetadata.xml): XML error(s) during parsing, check log for specifics
2016-11-07 12:49:08 WARN OpenSAML.MetadataProvider.XML : adjusted reload interval to 1800 seconds
2016-11-07 12:49:08 CRIT OpenSAML.MetadataProvider.XML : maintaining existing configuration, error reloading resource (https://c-adfs01.contoso.com/FederationMetadata/2007-06/FederationMetadata.xml): XML error(s) during parsing, check log for specifics

My current configuration in shibbolet2.xml

<OutOfProcess>
    <Extensions>
        <Library path="/usr/lib64/shibboleth/adfs.so" fatal="true"/>
    </Extensions>
</OutOfProcess>
<InProcess logger="native.log" checkSpoofing="true">
    <Extensions>
        <Library path="/usr/lib64/shibboleth/adfs-lite.so" fatal="true"/>
    </Extensions>
</InProcess>
<RequestMapper type="Native">
    <RequestMap applicationId="default">
        <Host name="c-app01">
            <Path name="secure" authType="shibboleth" requireSession="true"/>
        </Host>
    </RequestMap>
</RequestMapper>
<ApplicationDefaults entityID="https://c-app01.contoso.com/Shibboleth.sso/Metadata.xml"
                     REMOTE_USER="eppn persistent-id targeted-id">
    <Sessions lifetime="28800" timeout="3600" relayState="ss:mem"
             checkAddress="false" handlerSSL="true" cookieProps="https">

        <SSO>
            SAML2 SAML1 ADFS
        </SSO>

        <Logout>SAML2 Local</Logout>

        <Handler type="MetadataGenerator" Location="/Metadata.xml" signing="false"/>

        <Handler type="Status" Location="/Status" acl="127.0.0.1 ::1"/>

        <Handler type="Session" Location="/Session" showAttributeValues="false"/>

        <Handler type="DiscoveryFeed" Location="/DiscoFeed"/>
    </Sessions>
    <Errors supportContact="root@localhost"
        helpLocation="/about.html"
        styleSheet="/shibboleth-sp/main.css"/>
    <MetadataProvider type="XML" validate="true"
        uri="https://c-adfs01.contoso.com/FederationMetadata/2007-06/FederationMetadata.xml"
        reloadInterval="7200">
      <DiscoveryFilter type="Blacklist" matcher="EntityAttributes" trimTags="true"
        attributeName="http://macedir.org/entity-category"
        attributeNameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
        attributeValue="http://refeds.org/category/hide-from-discovery" />
    </MetadataProvider>

    <AttributeExtractor type="XML" validate="true" reloadChanges="false" path="attribute-map.xml"/>

    <AttributeResolver type="Query" subjectMatch="true"/>

    <AttributeFilter type="XML" validate="true" path="attribute-policy.xml"/>

    <CredentialResolver type="File" key="c-app01.contoso.com.key" certificate="c-app01.contoso.com.pem"/>
</ApplicationDefaults>

<SecurityPolicyProvider type="XML" validate="true" path="security-policy.xml"/>

<ProtocolProvider type="XML" validate="true" reloadChanges="false" path="protocols.xml"/>

Apache Configuration /etc/httpd/conf.d/shib.conf
LoadModule mod_shib /usr/lib64/shibboleth/mod_shib_24.so

ShibCompatValidUser Off

<Location /Shibboleth.sso>
  SetHandler shib
  AuthType None
  Require all granted
</Location>

How do I remove those fed errors?
Answer: I don't know if you had find the solution, but I've just encountered the same situation, and I have a workaround : In your shibboleth2.xml file, change the "validate" parameter to "false", like this :
<MetadataProvider type="XML" validate="false" file="/etc/shibboleth/FederationMetadata.xml"/>

In my case, I'm able to be redirected on the login page of the Idp, and send back to my application.
Answer: In ADFS, these errors are coming from the ADFS Endpoints.
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 3893, message: no declaration found for element 'fed:ClaimTypesRequested'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 24931, message: no declaration found for element 'fed:TargetScopes'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 26031, message: no declaration found for element 'fed:ApplicationServiceEndpoint'
2016-11-07 12:49:08 ERROR XMLTooling.ParserPool : error on line 1, column 26285, message: no declaration found for element 'fed:PassiveRequestorEndpoint'

So, I just had to disable the unused Endpoints in ADFS Management > Service > Endpoints. Then, it removed the errors afterwards.


Cache API troubleshooting

Question: I'm trying to cache an object returned after a 3rd party API call via HTTP. The API charges based on calls, so I'm trying to cache the information returned for some period of time.
However I don't seem to be able to get cache_set() to ever store anything. I've enabled "Cache pages for anonymous users" and "Cache blocks" in the performance configuration, as I read somewhere that the cache API may depend on those being set.
I'm using code inside a function called in hook_block_view():

$cache_key = 'custom_module'.$index;
$conditions = cache_get($cache_key);
if (!$conditions) {
     $conditions = API_CALL($index);
     cache_set($cache_key, $conditions, 'cache',  REQUEST_TIME  + (60 * 10)); //stores in cache table and expires after 10 minutes
  }

However this still results in an API call per page load with testing from a logged out browser.
I added some minimal test code:

cache_set('testing','foo','cache',CACHE_PERMANENT);
  var_dump(cache_get('testing'));

And the output is "bool(false)".
Looking in the database shows the 'cache' table is empty.
I'm about to start digging through the function calls being cache_set() to see what is happening, and intend to report back what I find. However if this is a common problem perhaps someone already has an answer?
Comment: Just copy/pasted your code into /devel/php and `cache_get('testing')->data == 'foo'` as expected. Your cache table shouldn't be empty (unless you're not using db cache) so it might suggest you have a custom/contrib module invalidating the cache on every page load
Comment: Yep - just had a forehead slap moment. Earlier in the piece I had problems with excess caching, and had configured up "DrupalFakeCache".
Had to debug down into the cache_set function to realise it wasn't calling the default cache implementation before I remembered!
Answer: I'm an idiot, and I had configured up the DrupalFakeCache earlier in development to prevent caching. Clearly this results in no caching.

Cache API troubleshooting


How can I validate a path used to create a page?

Question: I'm in the process of creating my first D7 module, partly based on the tutorial found here. It's a pretty simple module that creates both a block and a page to show some content.
To go a little further, I want to allow the user to change the path of this page, via a configuration page.
This raises two questions regarding the validation of this data:

how to avoid collision with already existing paths. I already use two function calls (see code below) to check if the alias is already used, but I'm wondering if I'm doing it right because it feels a little bit like a hack, and I'm not sure I'm covering every possible cases.
more importantly, how should I validate the data entered by the user? I suppose some (a lot of) characters are not allowed in a URL (or a least strongly advised against). Is there a Drupal function for that, or should I do it from scratch?

Here is the code I have (simplified, and only the parts relevant to the question) :
<?php

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  // config page
  $items['admin/config/services/mymodule'] = array(
    'title' => 'mymodule',
    'description' => 'Configuration for the mymodule module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  // public page
  $m_title = variable_get('mymodule_title', 'My module');
  $m_title = $m_title ? $m_title : 'mymodule';

  $m_path = variable_get('mymodule_path', 'mymodule');
  $m_path = $m_path ? $m_path : 'mymodule';

  $items[$m_path] = array(
      'title' => $m_title,
      'page callback' => '_mymodule_page',
      'access arguments' => array('access mymodule content'),
      'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Page callback: mymodule settings
 *
 * @see mymodule_menu()
 */
function mymodule_form($form, &$form_state) {
  $form['mymodule_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title displayed on the mymodule page'),
    '#default_value' => variable_get('mymodule_title', 'My module'),
    '#required' => TRUE,
  );
  $form['mymodule_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Path for the mymodule page'),
    '#default_value' => variable_get('mymodule_path', 'mymodule'),
    '#description' => t('
Relative path to your Drupal installation. Default value: mymodule
Do not include a trailing slash. In case of multilingual sites, do not enter the language prefix either.
'),
    '#required' => TRUE,
  );

  return system_settings_form($form);
}

/**
 * Implements validation from the Form API.
 *
 * @param $form
 *   A structured array containing the elements and properties of the form.
 * @param $form_state
 *   An array that stores information about the form's current state
 *   during processing.
 */
function mymodule_form_validate($form, &$form_state) {
  // page path validation
  $m_path = $form_state['values']['mymodule_path'];
  $m_path_db = variable_get('mymodule_path', '');
  if ($m_path_db != $m_path) {

    if (drupal_lookup_path('source', $m_path) || menu_get_item($m_path)) {
      form_set_error('mymodule_path', t('This path is already used.'));
    } else {

      // check if value contains non-standard characters
      // while still allowing for path fragments separators ("/")
      $m_path_parts = explode('/', $m_path);
      $has_invalid_chars = false;
      foreach ($m_path_parts as $key => $part) {
        if (urlencode($part) != $part) {
          $has_invalid_chars = true;
        }
      }
      if ($has_invalid_chars) {
        form_set_error('mymodule_path', t('This path contains invalid characters.'));
      } else {
        variable_set('menu_rebuild_needed', TRUE);
      }
    }
  }

  $m_title_db = variable_get('mymodule_title', 'My module');
  $m_title = $form_state['values']['mymodule_title'];
  if ($m_title_db != $m_title) {
    variable_set('menu_rebuild_needed', TRUE);
  }
}

?>

Edit: In the meantime, I tried to implement some kind of "manual" validation based on the urlencode function. If a part of the path contains characters that are modified by urlencode, then it is considered not valid. I've updated my code. Of course I'm still curious to know if there's a better way of handling that.
Comment: Conflicts are easy, relatively.  Just need to obtain menu and see if anything is there. User input validation is more fun :) +1 from me, later I'll try to answer.
Comment: @Mołot "Just need to obtain menu" -> so using `menu_get_item()` is correct then? But what if a path is present, but not included in a menu? (That's why I combined it with `drupal_lookup_path()`)
Comment: all paths are defined in hook menu, so I would expect everything to be in some menu. Sadly, Drupal mixes menu with routing. I'll try to post answer if I'll have time, but please don't poke me, if I'm not answering, it means I can't, simple as that.
Answer: You could use drupal_valid_path() to determine if the URL exists in Drupal. I would recommend running this as user 1 to avoid any weird permissions issues with the URL.
Link: https://api.drupal.org/api/drupal/includes%21path.inc/function/drupal_valid_path/7
Comment: Thanks for your answer. I can't check it right now, so I'm not entirely sure, but I think I did test that and I got inconsistent results. I'll test it again next week.


Domain access domain menu show default values

Question: The problem:
We have a main site with 70 subsites. On these subsites are users who have access to the menu settings. When they add a menu item they need to check the box near their own subsite.
If they forget this the menu item will be shown on all the other domains. Sometimes resulting in multiple menu items with the same title.
The proposed solution:
Alter the menu_edit_item form so that the $form['domain_menu_access']['manage']['domain_menu_access_show']['#default_value'] is set to the domains the current user has access to.
My question:
How do I set the default value for these checkboxes?
Here is my code:
<code>// Alter the edit menu item form

if($form_id == 'menu_edit_item'){
    $domains = array();
    if($user->uid > 1){
      $form['domain_menu_access']['manage']['#collapsed'] = false;
      foreach($user->domain_user as $domain){

    $form['domain_menu_access']['manage']['domain_menu_access_show']['#default_value'] = array((string)'d'.$domain);
  }
}
</code>
I have tried several variations with the $domain. (array($domain), array($domain => $domain), etc)
Answer: I found a workaround. I just rebuild the options array with the domains the user has admin access to.
Here is my code:
<code>// Alter the edit menu item form

if($form_id == 'menu_edit_item'){
    $form['domain_menu_access']['manage']['#collapsed'] = false;
    $domains = array();
    if($user->uid > 1){

  // We don't need to hide any menu items on other domains so we don't show this option.
  $form['domain_menu_access']['manage']['domain_menu_access_hide']['#access'] = false;

  // Loop the user object for all the domains current user is connected to
  foreach($user->domain_user as $domain){
    // Get the domain data
    $domains[] = domain_lookup($domain);

    // First unset all the options of the form element so we can rebuild it with our own values
    unset($form['domain_menu_access']['manage']['domain_menu_access_show']['#options']);
    //Rebuild the #options array
    $form['domain_menu_access']['manage']['domain_menu_access_show']['#options']['d'.$domain] = $domains[0]['sitename'];

    // Set the default value(s)
    $form['domain_menu_access']['manage']['domain_menu_access_show']['#default_value'] = array('d'.$domain);
  }
}
</code>
}


Conditional expectation for $2X+3 \mid Y$

Question:
Given the pdf: $$f_{X,Y}(x,y)= \begin{cases} x+y,& 0 \le x \le 1, 0 \le y \le 1
\\0, & \text{otherwise}\end{cases}$$
  Find $E(2X + 3\mid Y )$.

Using the formula for conditional expectation:
$\int{xf(x|y)dx}$, where $x=2X+3$, so we have:
$$\int\limits_0^1{(2x+3)\frac{f(x,y)}{f_y(y)}dx}$$
Is this correct or do we have to do something different regarding the $2X+3$? Thanks.
Comment: @A.S. Are you sure $X,Y$ are independent, with $f_{X,Y}(x,y)=x+y$?
Comment: @Mick Of course not - I misread the problem before proper formatting was introduced.
Comment: @A.S. Ok, no problem. Thought I might have been going crazy for a second. :)
Comment: Yes, this is correct, go on.
Answer: Your approach is correct.
You can verify your result with Mathematica:
In[16]:= Expectation[
  2 X + 3 \[Conditioned] Y == y, {X, Y} \[Distributed]
   ProbabilityDistribution[x + y, {x, 0, 1}, {y, 0, 1}]] // Normal

Out[16]= (13 + 24 y)/(3 (1 + 2 y))

And the confirmation that the result is correct, using the law of total expectation:
In[21]:= Expectation[(13 + 24 y)/(3 (1 + 2 y)),
  y \[Distributed]
   MarginalDistribution[
    ProbabilityDistribution[x + y, {x, 0, 1}, {y, 0, 1}], 2]] ==
 Expectation[
  2 x + 3, {x, y} \[Distributed]
   ProbabilityDistribution[x + y, {x, 0, 1}, {y, 0, 1}]]

Out[21]= True


What is "Adjusted CV" or "Bias-corrected CV"?

Question: In the documentation for the R package pls, the following statement appears in the help file for the MSEP function:

"CV" is the cross-validation estimate, and "adjCV" (for RMSEP and MSEP) is
  the bias-corrected cross-validation estimate.

What does this mean? In other words, what does it mean to correct a CV estimate for bias?
Answer: In this context, bias correction refers to the fact that, when we do perform resampling (bootstrap or cross-validation) we almost certainly do not use our whole sample of size $N$; this potential leads to the biased estimates of the MSEP (Mean Squared Error of Prediction).
There are various methodologies that can control for this kind of resampling bias. For example, one of the mostly commonly referenced techniques is the bootstrap 0.632 (Efron, 1983, JASA, Sect. 6). What all methodologies have in common is that they derive a relation approximating the expected difference in performance between a learner trained with the "resampled sample" and another ideal learner trained with the full sample. They then recombine/weight the estimates in such way that the apparent discrepancy is minimised. For example, the adjCV estimator, as implemented in pls::MSEP, adjusts by a factor proportional to the difference of the whole sample MSEP and mean out-of-fold MSEP (see Mevik & Cederkvist, 2005, Chemometrics, Sect. 2.4 ). Similarly, the bootstrap 0.632 estimator recombines the out-of-bootstrap-sample error estimate with the in-bootstrap-sample error estimate.
A nice succinct introduction to the topic touching among the issue of bias (and variance) can be found in Sections 7.10 (Cross-validation) and 7.11 (Bootstrap Methods) from Hastie et al.'s classic textbook Elements of
Statistical Learning, they touch upon bias mostly in the context of bootstrap 0.632 but the rationale for biased adjusted CV is the same. Finally, the CV community has already two very enlightening posts regarding: What is the .632+ rule in bootstrapping? and Bias and variance in leave-one-out vs K-fold cross validation; they definitely worth one's time! (Personal-note: People tend to make a big issue about bias but I have found that the variance is the one that often kills an analysis.)
Comment: Makes perfect sense. Great answer!
Comment: Cool, I am happy I could help.


Atalho para "console.log()" no VSCode

Question: Existe, no Visual Studio Code, uma forma de inserir console.log() assim que começo a escrever? Ou então um atalho do teclado?
Answer: Revirando o VS code, vi que ao digitar 'log', aparece a previsão de console.log(). deve servir pra outros que precisam de algo parecido.
Answer:
Digite 'log'  e aperte a tecla 'tab' (log + tab).
Caso não funcione, quando digitar 'log' escolha a opção que aparecerá 'log log to the console' e tente de novo.

Atalho para "console.log()" no VSCode


KeyError while key is present in CSV file

Question: I have problem that I get KeyError: 'District'  but I have column District in my file here is it
Code:
# Create the CSV file: csvfile
csvfile = open('crime_sampler.csv', 'r')

# Create a dictionary that defaults to a list: crimes_by_district
crimes_by_district = defaultdict(list)

# Loop over a DictReader of the CSV file
for row in csv.DictReader('crime_sampler.csv'):
    # Pop the district from each row: district
    district = row.pop('District')
    # Append the rest of the data to the list for proper district in crimes_by_district
    crimes_by_district[district].append(row)

Error:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/tmp/ipykernel_608/747227460.py in <cell line: 8>()
      8 for row in csv.DictReader('crime_sampler.csv'):
      9     # Pop the district from each row: district
---> 10     district = row.pop('District')
     11     # Append the rest of the data to the list for proper district in crimes_by_district
     12     crimes_by_district[district].append(row)
KeyError: 'District'

Comment: Welcome to Stack Overflow.  Please include the full traceback error and include sample data as text and not as an image.
Comment: Use `for row in csv.DictReader(csvfile):` instead of what you have.
Comment: I can't include sample data it's in file and i can't format it to display normally here
Comment: Change "district = row.pop('District')" to "district = row['District']"
Comment: For future reference, CSV files are text files, so you can open them in any text editor and copy lines from them and then paste those into your question. To get the to look right, format them as though they were code. (i.e. bracket the line pasted with triple backtick characters like this: \`\`\` ).
Answer: From https://docs.python.org/3/library/csv.html, I believe you should
change your parameter to csv.DictReader():
    # Create the CSV file: csvfile
    csvfile = open('crime_sampler.csv', 'r')

    # Create a dictionary that defaults to a list: crimes_by_district
    crimes_by_district = defaultdict(list)

    # Loop over a DictReader of the CSV file
    for row in csv.DictReader(csvfile):
        # Pop the district from each row: district
        district = row.pop('District')
        # Append the rest of the data to the list for proper district in crimes_by_district
        crimes_by_district[district].append(row)


Windows Server 2012 R2 - Out of range signal

Question: I have recently bought Windows Server 2012 Essentials R2, I booted from DVD, it has loaded the files and I get the Windows logo and the loading circle. Then my monitor states the message:

Out of range signal. Cannot display this video mode, change computer display input to 1680x1050 @60Hz

I was trying to setup WS. Can anyone can recommend anything?
Comment: Try a different monitor? Or use your remote console?
Answer: During windows startup, try installing server core, rather than the "full" version.  As this won't install a GUI, if it installs without issue, the problem is likely to be in the default video drivers for whatever graphics card you have.  You may need to slipstream new drivers into the install media.
If you can't install the core version either, then the problem may lie with either the media you're using, or a problem with the hardware.  I've seen everything from bad video cards to bad power supplies cause issues with installing windows.  Try to test the media on another machine.


IN statement multiple columns

Question: I want to implement the below query
Select * from table1
where a in(select a,b,c,d,e from table2 order by date desc limit 5)

But IN statement is allowing only 1 column.
Answer: The fact that you need to do this suggests your design could use a rethink.  But assuming the goal is to compare "a" from table1 separately to each column's value for table2, you can do it like this:
 ... in (select unnest(array[a,b,c,d,e]) from (select * from table2 order by date limit 5) foo )

Comment: The following error is occurring; ERROR:  `subquery in FROM must have an alias
LINE 1: ..." where a in(select unnest(array[a,b,c,d,e]) from (select * ...
                                                             ^
HINT:  For example, FROM (SELECT ...) [AS] foo.
SQL state: 42601
Character: 79`
Comment: Fixed.  The dummy alias isn't needed in the current dev version ( the future v16) which I tested with.
Answer: You can use the where clause in following
Select * from table1
where (a,a,a,a,a) in(select a,b,c,d,e from table2 order by date desc limit 5)

Comment: Based on the above query, the outcome is 0. As @jjanes mentioned, basically I want to compare "a" from table1 separately to each column's value for table2

IN statement multiple columns


Excel VBA Bloomberg Refreshallstaticdata Issue

Question: I am trying to use excel vba to refresh a workbook that contains Bloomberg excel formulas. I am able to have the formulas update by using the below formulas
<code>Application.run "RefreshAllWorkbooks"
Application.run "RefreshallStaticData"
</code>
however, they only update once the sub has completed. I have tried putting in formulas to wait, but from what I have found the Bloomberg formulas will not update until the sub completes, once it completes I can see the formulas updating on the tab. I need to have the formulas update so then I can use the data later in the sub. Is there a way I can have the formulas update without having the sub complete?
Answer: you have to use two different Macros. The Frist on consisting of the refresh arguments and the second macro with the calculations, updates etc.
An alternative to this could be: To download the Bloomberg Data directly via VBA.


how to use transform class with active pseudoclass in tailwindcss

Question: I want to give click effect to a button like this:
.btn-translate-effect {
    transition: transform .1s ease-in-out;
}

.btn-translate-effect:active {
   transform: translateY(3px);
}

with tailwind utility classes.
But I'm not able to it figure it out. I tried this:
<button class="transform active:translate-y-4"></button>

It doesn't work. I also modified variant config tailwind.config.js like this:
variants: {
  extend: {
    transform: ['active']
  },
}

But to no avail.
Answer: You need to replace transform with translate on tailwind config.
  variants: {
    translate: ['active'],
  },

Working Example


Why is $\mathbf{realmax}$ equal to $\mathbf{(2-eps)*2^{1023}}$?

Question: In Numerical Computing With Matlab it is stated that(Under the IEEE standard):
 "the smallest positive normalized floating-point number has f = 0 and e = −1022. The largest floating-point number has f a little less than 1 and e = 1023."
We have
realmin = $2^{-1022}$ and
realmax = $(2-eps)*2^{1023}$
where eps = $2^{-52}$
My question is why does the computation for realmax involve an extra $(2-eps)$ term and not realmin? Realmax ends up being approximately equal to $2^{1024}$ but this value is larger than $2^{1023}$ thus violating the maximum allotted number of bits for the exponent. (11 bits for exponent in IEEE)
You can see realmin is $2^{-1022}$ and not any value lower is allowed. Why is this not the case for realmax?
Comment: This doesn't seem to be a question about maths.
Comment: They cannot represent 2^1024 with 1023 bits, so they are trying to get a slightly smaller number. More often than not MATLAB is used for large calculations, so the extra room by doing this is probably helpful
Comment: Presumably Matlab uses something like [floating point arithmetic](https://en.wikipedia.org/wiki/Floating-point_arithmetic).  I would guess that the lowest possible (non-zero) value for the significand is zero, and the highest possible value is `2 - eps`.
Comment: @almagest: It's definitely a question relevant for numerical analysis. Whether you count that as math or computer science is perhaps a matter of taste. At my university the numerical analysts are in the math department, at least.
Answer: The 64 bit double-precision floating point format has 1 sign bit, 11 bits for the exponent, and 52 bits for the fractional part of the significand.
The exponent 11111111111 (eleven ones, in binary) is used for special purposes (inf & nan), so the largest exponent available for numbers is 11111111110, which is 2046 in decimal, but there's an offset of 1023 that one must subtract, so it really represents $2046-1023=1023$.
And the largest fraction is 1111111111111111111111111111111111111111111111111111 (fifty-two ones), which has an implicit "1." in front, so that it means the binary number 1.1111111111111111111111111111111111111111111111111111, or $2-2^{-52}=2-\varepsilon$ in other words (not quite "two", just as close as you can get).
So
$$
\mathrm{realmax} = (2-\varepsilon) \times 2^{1023}
.
$$
Similarly, the exponent 00000000000 is used for special purposes (zero & subnormal numbers), so the smallest exponent available for normalized numbers is 00000000001, which after subtracting the offset becomes $1-1023=-1022$.
And the smallest fraction is 0000000000000000000000000000000000000000000000000000, which corresponds to the number 1.0000000000000000000000000000000000000000000000000000 (so just "one", no $\varepsilon$ here).
Therefore
$$
\mathrm{realmin} = 1 \times 2^{-1022}
.
$$
Comment: +1 Ok, you persuaded me!
Comment: @Hans Lundmark  Thank you this is clears up a lot of the confusion. In some references to floating point arithmetic, they consider the fractional part of the significand to be between [0.5, 1). How does that apply in the context of realmin and realmax?
Comment: From the answer of this post: https://math.stackexchange.com/questions/184630/what-does-mantissa-mean-here    I would have assumed the mantissa would need to be between [0,1] not [0.5,1).
Comment: It's just because they use an implied "0.1" in front of the fraction instead of "1.", so that the whole mantissa is just half as large, and then they shift the offset by 1 (subtract 1022 instead of 1023) so that $2^{\text{exponent}}$ becomes twice as big instead, to compensate.
Comment: @Hand Lundmark But then how do you represent a number like 1,232 considering the mantissa can't be below 0.5?
Comment: As I said, make the mantissa half as large (instead of $m \in [1,2)$, use $m'=m/2 \in [\tfrac12,1)$), and increase the exponent by one (use $e'=e+1$ instead of $e$); then $x = m \times 2^e = m' \times 2^{e'}$. So $x=1.232 = 1.232 \times 2^0$  becomes $x=0.616 \times 2^1$ instead.
Comment: Genius.. thank you


Automatically BCC in Outlook Office 365 or Outlook Desktop on Mac or PC

Question: I am trying to automatically populate the bcc field with an email address in order to get emails to flow through to Pipedrive CRM. I am wondering how I can run a script to make this populate since there currently is not any functionality in Outlook to do this.
I tried using an Applescript but it is not working. I need it to populate the bcc field when I reply to a message AND when I create a New message. Thanks!
Answer: You need to download and install this plugin:
Auto BCC/CC plug-in
Note:
Payware, but has "Unconditional 60-days money-back guarantee"
Comment: Hey Behzad, so my company actually restricts downloading plug-ins. So it has to be a way where I don't have to rely on those.
Comment: Hey, there is a built-in option for this. check out this link: https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-add-auto-bcc-to-all-user-accounts/89dda0d8-de33-412d-9e3d-e4fd76f97c2a
Comment: Certainly you can set a BCC address via rules. One disadvantage: while creating a new message/replying you don't see the BCC field populated.
Comment: @VictorIvanidze - could you clarify the bcc address via rules? So when a draft of an email is created there is a rule where it automatically bcc's the email address in the rule? I searched high and low for something like that an couldn't find it. The address I want to BCC is different than the sender address too
Comment: @CaitlinFerson - follow the behzad's link: https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-add-auto-bcc-to-all-user-accounts/89dda0d8-de33-412d-9e3d-e4fd76f97c2a?auth=1
Comment: Note, the link that can _"set a BCC address via rules"_ is done via EAC, i.e., the "Exchange Admin Center" in the backend.


What test to use to show that methods are different / not equal

Question: so I have this graph

What test can I use to show that the three methods are different / not equal? The data is not normally distributed, nor has it a common variance. I also failed to transform it to a normal distribution.
I'm working in R if that helps.
The sample size is 1000, maybe that solves all problems of non-normality and I can simply use an ANOVA?
Comment: Huh??? Looking at that graph how could you possibly believe the methods were _not_ different. Looks like a case for the "Inter Ocular Trauma Test" https://www.johndcook.com/blog/2009/08/31/the-iot-test/
Comment: You could fit two GAMs, one stratified by method, one not, and compare them.
Answer: One idea, you could ignore the models and timesteps and just compare the values, with anova or kruskal-wallis. This isn't very elegant, but with data that clearly separated, it gives you the magic p-value.
Another idea, if you can put 95% confidence intervals around the models on the plot, the fact that the intervals don't overlap would suggest that the methods are different.  Again, nothing fancy, but it does the job.
Comment: thanks. i'll plot them with confidence intervals then. looks nice too :)
its really obvious that they are not the same anyways.


A question on trigonometry and solution of triangles

Question:
Sides $a, b, c$ of the triangle ABC are in H.P, then prove that $\csc A (\csc A +\cot A); \csc  B (\csc  + \cot B) $& $\csc  C (\csc  C + \cot C)$ are in AP.

I recently came across the above question which I'm not able to solve. I'm not getting any ideas regarding this question. I'm also not able to understand how to algebraically manipulate the expression and use the condition appropriately. Would someone please help me to solve this problem?
Thanks for help.
Comment: Isn't is $\csc$?
Answer: Hint:
$$\csc A(\csc A+\cot A)=\dfrac{1+\cos A}{\sin^2A}=\dfrac1{1-\cos A}$$
$$=\dfrac{2bc}{4(s-b)(s-c)}$$
$$=\dfrac{abc}{2(s-a)(s-b)(s-c)}\cdot\left(\dfrac sa-1\right)$$
Comment: Thank you very much


Cross-validation transformer fit to test set?

Question: When applying transformers in a cross-validation routine, it is often advised to fit the transformer to the data in your train set, and transform both the train and test set using the obtained transformer parameters. As an example, suppose we are using a standard scaler as a transformer, the cross-validation routine might look like this:
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold

scaler = StandardScaler()
cv = KFold(n_splits=5)
folds = cv.split(X=X)

for train_idx, test_idx in folds:
    X_train = X[train_idx,:]
    X_test = X[test_idx,:]
    y_train = y[train_idx]
    y_test = y[test_idx]

    scaler.fit(X_train)
    X_train = scaler.transform(X_train)
    X_test = scaler.transform(X_test)

    # Train & score model

This is also the behavior that Scikitlearn's pipelines implement.
What I'm interested in is the following: Why do we transform the test set based on the parameters of the train set, instead of fitting a separate transformer for the test set? If we would fit a separate standard scaler based on the test set and use the obtained parameters to transform the test set, then, as far as I see, the train and test set remain independent. As an example, we could do the following in every fold:
X_train = StandardScaler().fit_transform(X_train)
X_test = StandardScaler().fit_transform(X_test)

In case of a standard scaler, it would probably hardly matter for the performance of the resulting model. But I can imagine there to be transformers in which it matters. Is there any objection to using the second method described here?
Comment: My two cents to @Hooman's comment. The transformer (as you call like) becomes part of the model. So applying it to the test set is part of the processing before the rest of the model can be used.
Comment: The second method means that you have all the test set (X_test) available during evaluation of your model. Think about it like this: for validation and testing of the model you should mimic the actual operation of the model. In this condition every time you have one sample from X_test. You don't have all the samples at the same time.
Comment: I'm not sure if I understand what you mean. If you do K-fold cross-validation (or split-half or something like that), you can have a reasonably large test set, right? Something large enough to fit a scaler/transformer on, at least. Only if you use leave-one-out CV you have a single observation - in which case, it indeed doesn't make sense to try to fit a scaler.
Answer: This answer is the same as what @Hooman said, but explained a little differently. For this example I'm going to pretend you have users visiting your site, and you want to predict if they will click on an ad or not.
The idea of a train-test split is that you want to mimic real life. In real life you will have some historical data about users who came to your site, and you will know if they clicked on an ad or not, this is your training set. You now have to build a model to predict if future users will click on an ad, but you don't have this data yet, this is your test set. You can't use the mean and standard deviation from the test set yet because you wont get that data until tomorrow, and you need to build a model tonight!
Comment: I am sorry. I don't understand what point you are making or how it relates to the question.
Comment: The question was "why transform the test set with the parameters of the training set instead of the the parameters of the test set"? There answer is that the test set is supposed to mimic data you don't have yet that you will collect in the future. You can use the test parameters to transform the test set, but your results will probably be better than what you would get in a real world problem, you would just be tricking yourself.
Answer: Let's take a very basic example:
X_train = [-4, -3, -2, -1, 0, 1, 2, 3, 4]

Y_train = [-8, -6, -4, -2, 0, 2, 4, 6, 8]

X_test = [3.5, 4.5]

Y_test = [7, 9]

As you can see, the model $y=2x$ works perfectly for this data. To simplify, let's say we want to center the data, but we don't want to normalize the standard deviation to 1.
We can use a standard scaler on X_train. Actually, it is already centered, so it will not change anything.
If we use another scaler for the test set, we are going to obtain:
Xtest_modified = [-0.5, 0.5].
And after training we are going to predict: Y_test = [-1 ,1] which is obviously wrong.
If you had used the same scaler (which does not do anything in this case), you would have obtained Xtest_modified=[3.5, 4.5], which gives correct estimates.
Although in this case, the error is huge, it may be that with large dataset the error is almost invisible. Indeed, if you have a large i.i.d. dataset, the mean and variance of your training and test sets will be very similar.
Answer:
as far as I see, the train and test set remain independent

You're right that information from the test set wouldn't be leaking into the training set, but it could be leaking into the model at test time.

In case of a standard scaler, it would probably hardly matter for the
  performance of the resulting model.

Transformers that are fit to a dataset contain information about that dataset. So if you fit a transformer (such as StandardScaler) to the test set, then information from the test data (mean and standard deviation in this case) has leaked into that transformer. This information leakage may cause your model to overfit the test set.


NGINX - Two different rails apps under same domain

Question: I have two different Rails (passenger) apps that I wan to host on one server:
somehost.com/      <-- App #1
somehost.com/admin <--- App #2

Tried playing with the 'location' directive, but failed to have both operate.
Can someone suggest the correct approach ?
(I would prefer both to share same environment, only launch from different directories)
EDIT: Sample (desired) config
Trying to do something like:
server {
   listen 80;
   server_name myhost.com;
   rails_env production;
   passenger_enabled on;

  location / {
    root /opt/main_site/public/;
  }

  location /dev {
    root /opt/admin_site/public/;
  }
}

Answer: What did you actually try to do with the location directives?  Can you post that?
Something like:
  location /admin {
    proxy_pass http://app2;
  }

  location / {
    proxy_pass http://app1;
  }

should work.
Comment: I added a sample config