Compile Jasper Report remoteley without Java-Bridge

Question: Is there any way I can put jrxml files onto the Jasper server, link it to a datasource and let it compile without iReports, Java-Bridge, local Jaspersoft UI, ... I want to use as little Java as possible and I don't know about Apache ANT.
Can I do it through the (PHP) REST/SOAP API?
Or can I setup a little shell script on the Jasperserver that I can use like this way:
<code>./compileMyReport.sh --report=/home/bla/test.jrxml --datasource=MongoDB_test_1
</code>
Answer: What do you mean by "Jasper server"? Do you mean the "JasperReports Server - Web Application" (http://community.jaspersoft.com/project/jasperreports-server)? If so, it does offer a REST interface. Have a look at the "JasperReports Server Web Service Guide" (http://community.jaspersoft.com/documentation?version=7114).
If you, however, only want to have reports somewhere and execute them programmatically that can also be arranged (and would be much easier than to go via the JasperServer Rest Interface). For this you would only need to set up a minimal java class. You could then simply call this "script" via a e.g. a system call and let it generate the report to disk. I've recently blogged about a security issue with jasperreports and there I'll also give the necessary code to execute jaspers: http://blog.datenwerke.net/2013/05/jasperreports-in-box-part-i.html
Hope that helps.
Comment: I find the documentation very oldschool and hard to read through but I managed to use the REST v2 API now to create and compile reports.
Thanks for your helpful advice anyways.


Compiling C code that uses R libraries in Netbeans

Question: I've been having trouble debugging some C code that I'm writing as part of an R package.  The code compiles and executes when I use R CMD SHLIB from the Windows console (i.e. cmd.exe):
>R CMD SHLIB MaximumAgreementForest.c
gcc -m64 -I"C:/PROGRA~1/R/R-32~1.4RE/include" -DNDEBUG     -I"d:/RCompile/r-compiling/local/local323/include"     -O2 -Wall  -std=gnu99 -mtune=core2 -c MaximumAgreementForest.c -o MaximumAgreementForest.o
gcc -m64 -shared -s -static-libgcc -o MaximumAgreementForest.dll tmp.def MaximumAgreementForest.o -Ld:/RCompile/r-compiling/local/local323/lib/x64 -Ld:/RCompile/r-compiling/local/local323/lib -LC:/PROGRA~1/R/R-32~1.4RE/bin/x64 -lR

The script also built correctly in Netbeans until I started using the functions R_alloc and C_alloc from the R libraries.  Now it doesn't seem to be able to find the definitions of a number of R-specific functions.  When I attempt to build the project in Netbeans the console lists the following:
cd 'C:\Work\Fun\implied_weight\MAF'
C:\MinGW\msys\1.0\bin\make.exe -f Makefile CONF=Debug
"/C/MinGW/msys/1.0/bin/make.exe" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make.exe[1]: Entering directory `/c/Work/Fun/implied_weight/MAF'
"/C/MinGW/msys/1.0/bin/make.exe"  -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/libMAF.dll
make.exe[2]: Entering directory `/c/Work/Fun/implied_weight/MAF'
mkdir -p build/Debug/MinGW-Windows/_ext/5c0
rm -f "build/Debug/MinGW-Windows/_ext/5c0/MaximumAgreementForest.o.d"
gcc -DDEBUG -O2 -Wall -mtune=core2   -c -g -Wall -I/C/Program\ Files/R/R-3.2.4revised/include  -MMD -MP -MF "build/Debug/MinGW-Windows/_ext/5c0/MaximumAgreementForest.o.d" -o build/Debug/MinGW-Windows/_ext/5c0/MaximumAgreementForest.o ../MaximumAgreementForest.c
mkdir -p dist/Debug/MinGW-Windows
gcc -DDEBUG -O2 -Wall -mtune=core2    -o dist/Debug/MinGW-Windows/libMAF.dll build/Debug/MinGW-Windows/_ext/5c0/MaximumAgreementForest.o -L/C/Program\ Files/R -L/C/Program\ Files/R/R-3.2.4revised/library -shared
build/Debug/MinGW-Windows/_ext/5c0/MaximumAgreementForest.o: In function `forest_new':
C:\Work\Fun\implied_weight\MAF/../MaximumAgreementForest.c:37: undefined reference to `R_alloc'
build/Debug/MinGW-Windows/_ext/5c0/MaximumAgreementForest.o: In function `forest_plant':
C:\Work\Fun\implied_weight\MAF/../MaximumAgreementForest.c:55: undefined reference to `S_alloc'
[...]
C:\Work\Fun\implied_weight\MAF/../MaximumAgreementForest.c:515: undefined reference to `R_chk_free'
collect2.exe: error: ld returned 1 exit status

My script, a single .c file, contains the lines
#define USE_RINTERNALS
#include <R.h> // which itself #includes R_ext/Memory, R_ext Printf
#include <R_ext/Print.h>
#include <R_ext/Memory.h>
#include <Rinternals.h>

Figuring that Netbeans is failing to point to the relevant libraries, I have tried adding and removing C:/Program Files/R/R-3.2.4revised/include and C:/Program Files/R/R-3.2.4revised/bin/x64 at File→Project Properties→General→Source folders, to no effect.
Under File→Project Properties→Build→C compiler, I have included C:/Program Files/R/R-3.2.4revised/include.
When I add C:/Program Files/R/R-3.2.4revised/bin/x64/R.dll to Build→Linker→Libraries→Libraries, via the Add Library... option, I receive the error c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: cannot find -lR, and the linker exits without (before?) complaining about the undefined references.
When I subsequently add "C:/Program Files/R/R-3.2.4revised/bin/x64/", which is already in by System PATH, to Build→Linker→Additional Library Directories, the compiler fails with the message C:/Program Files/R/R-3.2.4revised/bin/x64/R.dll: file not recognized: File format not recognized
What am I missing... how can I point Netbeans to the relevant R libraries?
Comment: Didn't work with _R_, but there may be a problem with the command: _gcc -DDEBUG -O2 -Wall -mtune=core2 -o dist/Debug/MinGW-Windows/libMAF.dll build/Debug/MinGW-Windows/_ext/5c0/MaximumAgreementForest.o -L/C/Program\ Files/R -L/C/Program\ Files/R/R-3.2.4revised/library -shared_; you pass a bunch of arguments (that _gcc_ passes to the _linker_), including lib paths ([`-L`](https://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_2.html#SEC14)), but you didn't include the library itself ([`-l`](https://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_2.html#SEC13)): if `R_alloc` is in _(lib)R.dll(.a)_ then add _-lR_.
Comment: Thanks for the suggestion. When I add R.dll as a library, Netbeans automatically adds the -lR to the gcc line, which reads
`gcc -o dist/Debug/MinGW-Windows/libMAF.dll build/Debug/MinGW-Windows/_ext/5c0/MaximumAgreementForest.o -L/C/Program\ Files/R/R-3.2.4revised/bin/x64 -lR -shared`
Answer: The File format not recognized error is encountered when a 32-bit compiler tries to load to a 64-bit .dll (or vice-versa).  Changing the path
C:/Program Files/R/R-3.2.4revised/bin/x64/R.dll
to
C:/Program Files/R/R-3.2.4revised/bin/i386/R.dll
resolved the problem.


How many times will be this statement will be executed?

Question: How many times will be this statement will be executed?
#include <stdio.h>

int main() {
    p = 0;
    for(i = 1; i < n; i = i * 2)
    {
       p++;
    }
    return 0;
}

The answer should be log(n), but I am getting log(n) + 1.
Comment: In terms of big oh *O(log(n))* is the same as *O(log(n)+1)*, and even *O(a log(n))*.
Comment: Suppose we have to find the exact value of p than how we will do it?
Comment: @WillemVanOnsem what will be the time complexity log(n) or ceiling of log(n)?
Comment: It does not matter, since the two are the same.
Comment: But isn't the graph of log and ceiling log different?
Comment: it does not matter: `ceil(x)` is always between `x` and `x+1`. *O(...)* does not sees this `+1` as a "difference", it would only be a problem if it was *(ceil(log(n))*n)* for example. When *n* goes to infinity, then the relative difference between *log n* and *ceil(log n)* is infinitismal small.
Comment: Do you want to say the infinitismal difference when multipiled by large value of n result in large difference in value so when frequency count is (ceil(log(n)) *n, it is better to write time complexity as (ceil(log(n)) *n rather than (log(n)) *n
Answer: In case of time complexity, to be exact:

1 from p=0;
 from the for loop
 from the inside of the loop

in total it would be:

In case of the value of p:

to prove this we can say p is initially 0 and it is increased as long as i is less than n.
If we assume  , we have k1 and k2 before the loop ends:

so p is increased by 1 for k1 times. Therefore: p=k1 at the end. We know:

Therefore:
Comment: Thanks, btw can you also provide proof?
Comment: @HritikKumar If it is a homework question, please think about the answer carefully to see if there are mistakes in it. If you find it helpful, please accept it. Thanks!
Comment: Shouldn't i will be 2^k-1 ?


C3X Polling Strategy - Fewest Answered

Question: I've been playing around with a 3CX PBX system and have been trying to alter a call queue so that members of staff that have had the fewest calls will get called first.
So I have set the call queues polling strategy to "Fewest Answered" however our newest member of staff is complainning that she is now receiving all calls rather then been spread out over the team equally.
My question is what time period is the "Fewest Answered" covering. Is it looking for the fewest answered extension from the whole time the PBX has been running or for that day etc?
Answer: Resetting the call statistics for the queue will do it, can also configure it to be done on a schedule.

C3X Polling Strategy - Fewest Answered


Programmatically render HTML in taxonomy term description

Question: I'm facing an issue where I'm attempting to programmatically set the description property for a taxonomy term that includes HTML, but the HTML is being rendered as text, rather than being rendered into HTML elements, unless I manually access the term in a browser and save it.
Example
taxonomy_term_save((object)array(
  'name' => $name,
  'description' => $t('
My description.

More info.
'),
  'vid' => $vocab->vid,
));

When I attempt to render the description, it appears as:

My description.

More info.

However, if I then go to Structure > Taxonomy > My_Vocabulary > My_Term and simply save the term (without any edits), it will then render properly as:

My description.More info.

I've also made a number of attempts to achieve this through an Entity Metadata Wrapper, but no luck (though I am admittedly not well versed on EMWs).
How can I programmatically force the description to correctly render the HTML without having to manually re-save it?
Any help is appreciated!
Comment: Just on mobile so can't check - isn't there a `format` property can you set to `full_html`, or the name of another more permissive filter?
Comment: From what I can tell, there is no format property because Description is an entity property, rather than a field (corrections to any misunderstanding are welcome!).
Comment: @Clive, I take that back. I was so focused on the idea that the format property belonged to the Description that I didn't think to look at the term itself. There is indeed a format property that I completely overlooked as part of taxonomy_term_save(). Please post this as an answer so I can give you credit.
Comment: Just got back to the computer and answered as it happens :)
Answer: The taxonomy_term_data table, which is the entity table for taxonomy terms, has a format column which stores the name of a filter to apply to the description when rendered.
It's available as a property on the entity, so you can use:
taxonomy_term_save((object)array(
  'name' => $name,
  'description' => $t('
My description.

More info.
'),
  'vid' => $vocab->vid,
  'format' => 'full_html',
));

Answer: Use the format property:
$term = taxonomy_term_load($tid);
$term->description = t('
Text
');
$term->format = 'full_html';
taxonomy_term_save($term);

Comment: this is also great information and I'm grateful for it! It just happens to be that Clive beat you to it. :-)
Comment: It's not about beating or losing, we all learn and help each other. Remember that you can always reward a good answer not only by accepting it but by up-voting it in either case ;) I up voted  Clive's answer while you didn't , see what I mean ?
Comment: Actually, I did upvote his answer (and yours), but my reputation is too puny to count. :/


Which attribute to choose first (the root) when making a decision tree?

Question: I am a bit confused, as it seems like my teacher has told me something different than what I see and hear on YouTube videos.
My problem is as follows:
My teacher told us to that the probability when deciding the root of the decision tree needs to be as close to 50% as possible. So, let's say we have this table:

My teacher told me for the ID3 algorithm, we can "clearly see, without having to calculate the information gain, that we need to pick "Growling" as our root as this is 50%, hence the 4 times YES and 4 times NO"
Well, okay, but why? When I check YouTube videos, they say that we need to take the most pure ones, so the ones where we have the most difference (like: 7 times YES and 0 times NO), which is certainly not "growling", as it's impure...
As you can see I am confused. Is this 50% strictly for the ID3 algorithm or is there something I am missing here? Could someone help me out, please?
Answer: ID3 algorithm would first takes growling because creates two nodes that are overall purer than the root:
root has 3 yes and 5 no, if you use growling to split your data you'll have 2 yes and 2 no in one node (that can be splitted using smelly) and 1 no and 3 yes in the other node. the first node gives you an information loss, the second one an information gain, the algorithm calculates the mean of the two measures, and finding it positive, performs the split. information gain (loss is his negative) is based on entropy, which measures the heterogeneity of the response variable in the nodes.
Comment: But does this mean that you first need to check what comes AFTER you would hypothetically choose some root? I mean, do you choose the root here because it's 2 YES and 2 NO or because of the possibilities after you would choose this?
Comment: you choose the variable for performing the split for the information gain that you will get choosing it, and that's calculeted on nodes created by the split, so, yes.
Comment: Okay, but does this mean that the information gain of an element with 2 yes and 2 no is higher than 3 yes 5 no?
Comment: no, entropy of a node wtih 2 yes and 2 no is higher than one with 3 yes and 5 no, so there's an information loss. however, this is averaged with the information gain from the other node, which has a lower entropy, and the overall information gain is positive
Comment: You say no, but you also state that a node with 2 yes and 2 no is higher... higher what? Higher information gain? If so, why do you say no? Can you be more concise / precise please?
Comment: higher entropy. I see you don't understand how does it all work, so I suggest you to read some more complete explanations, like: http://stackoverflow.com/questions/1859554/what-is-entropy-and-information-gain, or http://www.math.unipd.it/~aiolli/corsi/0708/IR/Lez12.pdf (first pages only)


Alert box is unable to show a variable Order ID of the order placed

Question: I am using a checkout page to allow users to place an order on my shopping website using Django. But once the checkout form is filled out and the submit button is clicked, an alert box pops up:
<code>$('#done').click(function(){
  console.log({{ord_id}})
  alert('Thanks for ordering with us. Your order Id is {{ord_id}} . Use it to track your order.');
  localStorage.clear();
})
</code>
Look at the variable inside the alert box string. I am unable to get its value:

The function in views.py which points to the HTML page containing the JavaScript part looks like this:
<code>def checkout(request):
    if request.method=="POST":
        itemsJson=request.POST.get("itemsJson","")
        name=request.POST.get("name","")
        email=request.POST.get("email","")
        phone=request.POST.get("phone","")
        address=request.POST.get("address1","")+" "+request.POST.get("address2","")
        city=request.POST.get("city","")
        state=request.POST.get("state","")
        zip=request.POST.get("zip","")
        place_order=Order(itemsJson=itemsJson,name=name,email=email,phone=phone,
                address=address,city=city,state=state,zip=zip)
        place_order.save()
        orderid=place_order.check_id
        update=UpdateOrder(order_id=orderid,update_email=email,
                update_desc="Your Order has been Placed")
        update.save()
        params={'ord_id':orderid}
        return render(request,'shop/checkout.html',params)
    return render(request,'shop/checkout.html')
</code>
What should I do?
Answer: You must do it with template literals. So:
<code>$('#done').click(function(){
  console.log({{ord_id}})
  alert(`Thanks for ordering with us. Your order Id is ${ord_id} . Use it to track your order.`);
  localStorage.clear();
})
</code>
Comment: Still not working @Danial using template literals its now not even showing the alert box
Comment: @PalashVishnani try ${{{ord_id}}}
Comment: nope ${{{ord_id}}} is also not working out for me
Comment: What does it show `console.log({{ord_id}})` ?
Comment: It shows nothing @Danial. I think views.py is unable to give me the dictionary object but everything inside the function definition is correct.
Comment: Maybe you doesn't pass `ord_id` parameter. Look : you do `return render(request,'shop/checkout.html',params)
    return render(request,'shop/checkout.html')` .  The `params` may doesn't pass.
Comment: Soo What should I do then? How can I pass params? @Danial
Comment: @PalashVishnani Based on your python code, params return just when method is `POST`, check this.
Comment: I am only using post method in my checkout page, `if request.method=="POST":` condition is working properly thats why all the data is getting stored in UpdateOrder and Order tables but only when it comes to this line: `return render(request,'shop/checkout.html',params)` then params is not returned to the HTML page. And also, once the return statement is called why is the compiler reading the line written after that, which contains one more return statement??????
Comment: @PalashVishnani try `return render(request,'shop/checkout.html',{'ord_id':orderid})` or something else to test returned params
Comment: Still not working maybe its a bug or something.
Comment: Try something else for `ord_id` value. Ex. `return render(request,'shop/checkout.html',{'ord_id':123})`
Comment: It is working for the return statement present outside the if condition. If I provide something like `{'ord_id':123}` in the return statement outside the if condition its working. But if I provide this same thing to the return statement present inside the if  condition, its not working
Comment: So maybe problem is in `place_order.save()
        orderid=place_order.check_id`
Comment: Watch these new changes in my code and the output for testing purpose also have a look at the terminal:  [link](https://imgur.com/a/4F6RiS9)
Comment: I saw. try this `return render(None, "shop/checkout.html", {"ord_id":orderid})`
Comment: @PalashVishnani have you problem yet?
Comment: Are you sure about view? I mean you do coding on right html view file.


Capturando o valor boolean de uma checkbox em PHP

Question: Estou fazendo um formulário de produto, onde o usuário precisa informar se o produto é ou não usado, porém estou tendo dificuldades em capturar o valor dessa checkbox, se é 1 ou 0, no mysql a coluna já está setada como boolean com default 0
logica-adiciona-produto.php
 <?php
    include("conecta.php");

    #Variáveis para cadastrar
    $nome = $_POST["nome-produto"];
    $preco = $_POST["preco-produto"];

    $descricao = $_POST["descricao-produto"];

    #Caso de verificação da variável booleana
    $usado = $_POST["usado-produto"];
    if(array_key_exists($usado, $_POST)) {
        $usado = "true";
    }else{
        $usado = "false";
    }

    #Query de inserção
    $query = "insert into produtos(nome, preco, descricao, usado) values('{$nome}', '{$preco}', '{$descricao}', {$usado})";

    #Variável para executar a inserção
    $retornoInsercao = mysqli_query($conexao, $query);

    #Teste para verificar inserção
    if($retornoInsercao){
        header("Location:index.php");
        die();
    }else{

    };

?>

adiciona-produtos.php
<?php
    include("header.php");
    include("conecta.php");
?>

 <form action="logica-adiciona-produto.php" method="post">
    <fieldset>
        Nome:
        <input type="text" name="nome-produto">
        Preço:
        <input type="number" name="preco-produto">
    </fieldset>
    <fieldset>
        Usado ?
        <input type="checkbox" name="usado-produto" value="true">
        Categoria:
        <select name="">

        </select>
        Descricao:
        <textarea name="descricao-produto"></textarea>
    </fieldset>
    <fieldset>
        <input type="submit">
    </fieldset>
 </form>

Comment: 1 e 0 mesmo !!! 1 para `true` e 0 para `false`
Comment: continua recebendo como 0 no banco
Comment: Se está dizendo do código! neh?
Comment: mesmo quando marco a checkbox, ele registra como false no servidor (0)
Answer: O seu código está errado, está enviando uma variavel que não condiz com o nome da chave, observe:
Troque:
#Caso de verificação da variável booleana
$usado = $_POST["usado-produto"];
if(array_key_exists($usado, $_POST)) {
    $usado = "true";
}else{
    $usado = "false";
}

por isso:
$usado = array_key_exists('usado-produto', $_POST) ? 1 : 0;

Explicação:
A estrutura da função array_key_exists
bool array_key_exists ( mixed $key , array $array )

onde o primeiro paramentro é o nome da chave a buscar dentro do array e o segundo o array propriamente, que retorna verdadeiro (true) ou falso (false) no resultado, se encontrou ou não ...
ou também
$usado = isset($_POST['usado-produto']) ? 1 : 0;

Referencia: array_key_exists
Comment: queria algo aproximado com o que eu fiz, pois o professor no curso usou o mesmo método que eu estou utilizando
Comment: @MuriloGambôa é o primeiro código `array_key_exists`, não é isso ? só lembrando que você colocou os paramentos errados, ou seja, estava fazendo errado...
Comment: o professor no curso usou basicamente isso >

`

 Usado
`
...
`$usado = $_POST['usado'];

if(array_key_exists('usado', $_POST)) {
    $usado = true;
} else {
    $usado = false;
}`
Comment: `'usado'` é diferente de `$usado` e outra coisa se o seu professor ensinou `$_POST['usado'];` sem conferir se existe também é uma prática errada, cuidado.
Comment: Você esta passando a variável como parâmetro do "array_key_exists" o que você deveria passar é o nome da "key" que você está querendo verificar se existe.
Comment: @JhonnyRogerVirgiliodaSilva foi o que eu relatei, na resposta.


How to select an element in a browser using its title in selenium?

Question: I need to click on the button in a webpage using its title, in Java using selenium webdriver. How can I do it?
The html is like this:

   <input type="text" value=""
      id="14611txnId" name="txnId"
      style="width: 250px;" placeholder="Enter TransactionId"
      readonly="true">
   <button type="button" title="Enter TxnID"
      id="14611addTxnid"
      onclick="javascript:enableInputForEdit('14611')"
      class="btn btn-info btn-xs">Edit</button>
   <button type="button" title="Save TxnID"
      id="14611SaveTxnid"
      style="display: none"
      onclick="javascript:saveTxnId('14611','MD-PE_02')"
      class="btn btn-info btn-xs">Save</button>

I need to click on the first button. How can I do it using title?
Comment: Show how you tried
Comment: do you mean you need your title to clickable like a button ?
Comment: Do you mean title property or text of the button?
Comment: @hatched not like that i need to click on the button using the property title.
Answer: You can use css-selectors:
WebElement button = webDriver.findElement(By.cssSelector("[title=\"yourtitle\"]"));

Where yourtitle is the title of the element you want to select.
Answer: You can try to click on it by using cssSelector to locate a button with a specific text, like this:
webDriver.findElement(By.cssSelector("button[title*='ButtonText']")).click();

The * sign indicates that webDriver will find a button with attribute title that contains the text "ButtonText".
Hope it helps.
Comment: This doesn't looks like locating element *by title*
Comment: Yes, I know :). But as he stated that he wants to click on 1st button, so this can be an option, to rid of static Text
Comment: actually, i need to use title property. since there are lots of buttons. like this.
Comment: @rakesh OK, I see. I updated my answer. Hope it helps :)
Answer: You can use :
driver.findElement(By.xpath("//button[@title='Enter TxnID']"));

OR
driver.findElement(By.id("14611addTxnid"));

Comment: since there are lots of buttons and every button id are different(like 14611addTxnid,14612addTxnid etc.. ) so cannot specify the exact id. so i need a method which will select it using the title.
Comment: @rakesh, Refer my updated answer for title attribute
Comment: @Ishitha ,Thanks can you please tell me that i am storing the web element till div in a variable row and then using row.findElement(By.xpath("//button[@title='Enter TxnID']")).click();  will it work?? or i need to use row.findElement(By.xpath("/button[@title='Enter TxnID']")).click();   ?
Comment: @Ishitha what is the difference between single / and double // ?
Comment: Its xpath syntax to define node with //(Double)
Comment: Thanks for the valuable suggestions


Como pegar campo específico de um array de objetos utilizando o componente autocomplete do material ui

Question: Tenho um componente autocomplete do Material UI, criado utilizando o pacote formik-material-ui. O componente renderiza um array de objetos do modelo abaixo:
const teams = [
  {id: 1, name: 'Barcelona'},
  {id: 2, name: 'Real Madrid'},
];

Quando alterar a seleção (onInputChange) do Autocomplete, preciso pegar somente o ID da seleção, o que acontece é que estou pegando o nome.
Segue o código completo: .
Qual seria o procedimento correto para pegar o ID?

import * as React from 'react';
import {render} from 'react-dom';
import {Formik, Form, Field} from 'formik';
import {Button, LinearProgress} from '@material-ui/core';
import MuiTextField from '@material-ui/core/TextField';
import {
  Autocomplete,
  AutocompleteRenderInputParams,
} from 'formik-material-ui-lab';
import Box from '@material-ui/core/Box';

const teams = [
  {id: 1, name: 'Barcelona'},
  {id: 2, name: 'Real Madrid'},
];

const App = () => {
  const [selected, setSelected] = React.useState('');

  const handleShowId = React.useCallback((event, value) => {
    alert(value.id);
    setSelected(event.target);
  }, []);

  console.log(selected);

  return (
    <Formik
      initialValues={{
        autocomplete: [],
      }}
      onSubmit={(values, {setSubmitting}) => {
        setTimeout(() => {
          setSubmitting(false);
          alert(JSON.stringify(values, null, 2));
        }, 500);
      }}
    >
      {({submitForm, isSubmitting, touched, errors}) => (
        <Form>
          {isSubmitting && <LinearProgress />}
          <Box margin={1}>
            <Field
              name="autocomplete"
              component={Autocomplete}
              options={teams}
              value={selected}
              getOptionLabel={(option: any) => option.name}
              style={{width: 300}}
              onChange={handleShowId}
              renderInput={(params: AutocompleteRenderInputParams) => (
                <MuiTextField
                  {...params}
                  error={touched['autocomplete'] && !!errors['autocomplete']}
                  helperText={touched['autocomplete'] && errors['autocomplete']}
                  label="Autocomplete"
                  variant="outlined"
                />
              )}
            />
          </Box>
          <Box margin={1}>
            <Button
              variant="contained"
              color="primary"
              disabled={isSubmitting}
              onClick={submitForm}
            >
              Submit
            </Button>
          </Box>
        </Form>
      )}
    </Formik>
  );
};

render(<App />, document.getElementById('root'));

Comment: https://material-ui.com/pt/components/autocomplete/#controllable-states
Comment: `onChange` em vez de `onInputChange` devolve o objeto selecionado
Comment: Certo, eu havia pensado nessa abordagem, o problema é que o campo está limpando após o onChange. Atualizei o SANDBOX.
Answer: Acredito que o seguinte código consegue resolver seu problema
import * as React from 'react';
import {render} from 'react-dom';
import {Formik, Form, Field} from 'formik';
import {Button, LinearProgress} from '@material-ui/core';
import MuiTextField from '@material-ui/core/TextField';
import {
  Autocomplete,
  AutocompleteRenderInputParams,
} from 'formik-material-ui-lab';
import Box from '@material-ui/core/Box';

const teams = [
  {id: 1, name: 'Barcelona'},
  {id: 2, name: 'Real Madrid'},
];

const App = () => {
  const handleShowId = React.useCallback((event, value) => {
    alert(JSON.stringify(value.id));
  }, []);

  return (
    <Formik
      initialValues={{
        autocomplete: [],
      }}
      onSubmit={(values, {setSubmitting}) => {
        setTimeout(() => {
          setSubmitting(false);
          alert(JSON.stringify(values, null, 2));
        }, 500);
      }}
    >
      {({submitForm, isSubmitting, touched, errors}) => (
        <Form>
          {isSubmitting && <LinearProgress />}
          <Box margin={1}>
            <Field
              name="autocomplete"
              component={Autocomplete}
              options={teams}
              getOptionLabel={(option: any) => option.name}
              style={{width: 300}}
              onChange={handleShowId}
              renderInput={(params: AutocompleteRenderInputParams) => (
                <MuiTextField
                  {...params}
                  error={touched['autocomplete'] && !!errors['autocomplete']}
                  helperText={touched['autocomplete'] && errors['autocomplete']}
                  label="Autocomplete"
                  variant="outlined"
                />
              )}
            />
          </Box>
          <Box margin={1}>
            <Button
              variant="contained"
              color="primary"
              disabled={isSubmitting}
              onClick={submitForm}
            >
              Submit
            </Button>
          </Box>
        </Form>
      )}
    </Formik>
  );
};

render(<App />, document.getElementById('root'));

Como o comentario acima diz o a propriedade onInputChange representa o valor que esta dentro da caixa de texto, enquanto o onChange representa o objeto em si. Espero ter ajudado
Comment: Funcionou com o event.preventDefault() ? Testei aqui e não deu certo. Estou achando que é um bug do Autocomplete do pacote formik-material-ui-lab.
Comment: Eu que agradeço. Bom saber disso caso eu for usar isso em algum projeto sera bem util
Comment: Certo, eu havia pensado nessa abordagem, o problema é que o campo está limpando após o onChange. Atualizei o SANDBOX.
Comment: @Fred Agora não consigo testar pois estou ocupado mas acredito que se você passar ```event.preventDefault()``` para o callback deve funcionar
Comment: Como pode ver testando esse código o navegador recarrega a pagina pois esse é o comportamento padrão e com o ```event.preventDefault()``` impedimos isso de acontecer
Comment: Fiz o seguinte, criei um estado inicializando-o como vazio, no onChange, seto o estado com o valor de value.name. E passo esse valor para a propriedade value do Autocomplete. Dessa forma funcionou. Valeu pela ajuda!
Answer: Conforme o link enviado pelo Rafael Tavares no seu comentário, a documentação especifica que para você conseguir capturar o objeto selecionado você precisa utilizar o método onChange ao invés do onInputChange.

Se você trocar o onInputChange por onChange a sua variavel value vai retornar o objeto inteiro ao invés de somente o nome.

https://material-ui.com/pt/components/autocomplete/#controllable-states


How can enable multiple contact form in drupal 8?

Question: I want multiple contact forms(different fields) in my drupal 8 site Like Webform module drupal 7.
I have tried to add multiple contact forms and i am able to number of contact forms with different different fields but at time only one form i can able to enable. Can i enable different contact form with different menu link?
Is there any alternatives to achieve this or i need to go for custom form?
Thank you
Answer: Each has their own URL. Check contact.routing.yml but pretty sure they are of the form contact/{contact_form} where contact form is the machine name. You can create menu links and aliases to these like any other path.


Add data validation in excel file (*.xlsx)

Question: I would like to add one condition to check the data on the first column as follow:
0 < data <= 1

So, how can I do it by Apache Poi library?
Thank you so much
Answer: Hint : Use Below Classes ;
import org.apache.poi.hssf.usermodel.DVConstraint;

import org.apache.poi.hssf.usermodel.HSSFDataValidation;

import org.apache.poi.ss.usermodel.DataValidation;

import org.apache.poi.ss.util.CellRangeAddressList;

Comment: Can you show the code more detail, pramod? I know them but I cannot how to explain the logic: 0 < data <= 1


capture value from login fields

Question: I'm facing a problem getting values from the login field, I solved it, I'm using an elegant model, and I'm trying to modify it, seeing some examples I can't adapt to my problem.
main.dart file
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Login',
      theme: ThemeData(
        primaryColor: kPrimaryColor,
        scaffoldBackgroundColor: Colors.white,
      ),
      home: LoginScreen(),
    );
  }
}

my login.dart file
class LoginScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Body(),
    );
  }
}

they are in a separate file, I think it's better that way, but all the examples that I see people use practically inside a single file, the buttons are one for each file for that module
my file body.dart
class Body extends StatelessWidget {

  final TextEditingController usuarioController = TextEditingController();
  final TextEditingController _senhaController = TextEditingController();
/*  const Body({
    Key? key,
  }) : super(key: key);*/

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Background(
      child: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "LOGIN",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            SizedBox(height: size.height * 0.03),
            SvgPicture.asset(
              "assets/icons/login.svg",
              height: size.height * 0.35,
            ),
            SizedBox(height: size.height * 0.03),
            RoundedInputField(
              hintText: "Seu Email",
              onChanged: (value) {},
            ),
            RoundedPasswordField(
              onChanged: (value) {},
            ),
            RoundedButton(
              text: "LOGIN",
              callbackClickLogin: () {},
            ),
            SizedBox(height: size.height * 0.03),
          ],
        ),enter code here
      ),
    );
  }
}

I saw in an example that I need to define
final TextEditingController userController = TextEditingController();

to get data from the user field,
and final TextEditingController _passwordController = TextEditingController();

to get the password values.
and this is the click-to-login button
my file button_login.dart
class RoundedButton extends StatelessWidget {
  final text of the String;
  final Function() callbackClickLogin;
  final color Color, textColor;
  constRounded Button({
    Key? key,
    necessary this.text,
    required this.callbackClickLogin,
    this.color = kPrimaryColor,
    this.textColor = Colors.white,
  }) : super(key: key);

  @overlay
  Widget Build (BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      width: size.width * 0.8,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(29),
        child: newElevatedButton(),
      ),
    );
  }

  //Used:ElevatedButton as FlatButton is deprecated.
  //Here we have to apply customizations to the Button inheriting the styleFrom

  newElevatedButton() widget {
    return HighButton(
      child: Text(
        text,
        style: TextStyle (color: textColor),
      ),
      onPressed: callbackClickLogin,
      style: ElevatedButton.styleFrom(
          primary color,
          padding: EdgeInsets.symmetric(horizontal: 40, vertical: 20),
          Text Style: Text Style(
              color: textColor, fontSize: 14, fontWeight: FontWeight.w500)
      ),
    );
  }
}

I don't know how to retrieve the values when I click the login button, as I want to get the values and pass them to another class in another file that will make a query via api.
I'm new to flutter.
thank you all.
Comment: where is your form of TextFeild !
Answer: Can you show the code of RoundedInputField() ?
If I am not wrong , you probably have widget named RoundedInputField with TextField() inside it.
you must define your controller in that widget and pass the controller to TextField as:
  final TextEditingController userController = TextEditingController();

  TextField(
      //.........
      controller : userController,
   )

and you can retrieve the value as :
  final value = userController.text ;

Comment: thank you very much, i recovered by doing the same

capture value from login fields


How many students chose lessons $A$ and $B$?

Question: In a class in which the students must choose at least two lessons, $15$ students chose lesson $A$, $12$ students chose lesson $B$, and $17$ students chose lesson $C$. According to this, how many students are there who chose lessons $A$ and $B$?
I've tried solving it by Venn diagram. However, I couldn't work it out.
Kindest Regards
Comment: Can anyone take a look?
Comment: There is not enough information in this problem to be able to solve it. Are you sure you have not missed out any information?
Comment: @JohnDoe That was from our worksheet which is for training exams. Indeed, you are too right because they hadn't given enough information. this is not first time.
Answer: Well I don't get the exact result.
Say there is $x$ students taking all three.
$a+x$ students taking A and C, $b+x$ students taking A and B and $c+x$ students taking B and C. Then we have $$a+b+x = 15$$ $$b+c+x = 12$$ and $$a+c+x=17$$
Thus $$15+12-17 =(a+b+x)+(b+c+x)-(c+a+x) = 2b+x$$
but you are interested in $b+x$
Comment: We can't solve this question, right?
Comment: Right............
Comment: Ok, I wanna accept your answer =))


Which enharmonic to use when writing down a sequence of chords

Question: I've got a sequence of chords, denoted using solmization here:
S:  re  di  do  ti
A:  ti  TA  la  sol
B:  fa  mi  ri  re
I'd like to write down these chords in B flat major. I'm concerned with the second tone of the alto (the all-caps "TA"). In B flat major, it's either A flat or G sharp.
My question is: which one of the two enharmonic equivalents (A flat or G sharp) is more "correct", more idiomatic to write in this specific case? I. e., should I write
S:  C      | B               | B flat  | A
A:  A      | >>> A flat  <<< | G       | F
B:  E flat | D               | C sharp | C

or
S:  C      | B               | B flat  | A
A:  A      | >>> G sharp <<< | G       | F
B:  E flat | D               | C sharp | C

?
I know that the choice of enharmonic depends on the context of the notes; here's what I was able to come up with so far:

This sequence of chords is descending, so maybe the A flat would be more appropriate;
However, 'di' (B) naturally resolves to 're' (C), and as such, it might be regarded as the leading-tone of C. Hence, the note in question is enclosed between the major sixth formed by D and B, and since the chord is the fourth-sixth translation of the tritone G sharp–B-D, we could write G sharp as well.

So, I can't quite decide between the two. What gives?
Answer: Use flats. In fact, write the bass of the 3rd chord as D♭. You're not only running parallel second inversion diminished chords downwards, you're doing so in a key that already uses flats in the key signature. I'd even be tempted to write the soprano and bass of the second chord as C♭ and E♭♭ respectively, but leaving them be might be a little easier to read.
Comment: You're most welcome.
Comment: I agree that leaving the D as-is (rather than an E♭♭) is easier to read, but I'd still be tempted to consider using a C♭ in sheet music, if only to preserve the visual of descending thirds. Especially if it and the A♭ are on the same staff.
Comment: Well, @Caleb, I did say I was tempted. This is one of those cases where other considerations would tip the choice one way or the other. If the sequence we've been given was a right-hand piano part over a true bass that start with a G suspended through to the 2nd chord and resolved at the end of the beat through F or A♭ (or both) to land on E♭ on the third chord (which could be held under the F chord as well - yes, I do like sevenths in the bass :D), then I'd want to leave it _exactly_ as I suggested because the progression makes sense with B and D.
Comment: @Patrx2 Actually, I ended up following your more rigorous advice, and I've written C♭ and E♭♭.
Comment: That's fine, @H2CO3. The three-voice case you mentioned makes sense like that. Almost invariably I would use at least the A♭ and D♭. (I'd need to supply roots of E and F♯ to even start considering sharps in those chords, and wouldn't _that_ make for an interesting progression! Chances are good I would treat them as F♭ and G♭ anyway...) My point was that different contexts might lead to different choices. I might leave in the B and D natural as well if I were writing a piece for student performers in the range of difficulty of the 1st three Mikrokosmos books.
Comment: @Patrx2 "My point was that different contexts might lead to different choices" – exactly. That's the main reason I've asked this question :)
Comment: @Patrx2 (By the way, the sheet I'm writing is probably going to be used by a semi-professional choir, so there's no need to superficially ease readability by not using double flats.)
Comment: Yup. Then the criteria are: 1) key; 2) underlying harmonic function; 3) direction of movement; and 4) (skill-appropriate) ease of reading, in roughly that order. It's always a bit of a balancing act - criteria (2) and (3) can change places, and, of course, you can end up mixing and matching when you've got both upper and lower leading tones (e.g., the various augmented sixth chords when used in chromatic progressions like this one).
Answer: To add to Patrx2's answer, you will call the note Ab (for the key Bb).  The reason why is because you're referring to the seventh scale degree when you label the pitch "ta" (we called it "te" but that's not the subject of the question :) ).  Ti, Te, or Ta all refer to a pitch of the seventh scale degree.  And so it must be a note that starts with the letter A (be it A, A#, Ab, etc.), which is also the seventh scale degree, for the key of Bb.
On the other hand, if the syllable was labeled "li" (i.e., raised "la"), or "la" or "le", you would refer to it as some form of the sixth scale degree (G), and in this case it would be G#.  However, as Patrx2 mentioned, flats lead downward (and sharps lead upward), so "li" would have been awkward and functionally unconventional in terms of voice leading.
So go with Ab!


Conditional e-mails based on radio buttons Drupal Webform

Question: I've built a form at http://dev.vies.dk/tilmelding. In the backend, it is easy to send e-mails to people filling out the form.
However, I need to send additional e-mails to other people based on some of the answers in the webform, namely the subjects they choose and the sex they have.
Subject         Female       Male
Soccer          email@example.com firstname.lastname@example.com
Handball        firstname.lastname@example.com   firstname.lastname@example.com
Kayak           firstname.lastname@example.com email@example.com
Dance           email@example.com   firstname.lastname@example.com
Biking          email@example.com   email@example.com

Is there a hook, where this can be programmed, so I can achieve what I want?
Answer: Yes, you want to use hook_mail_alter() in a custom module. This will intercept the outgoing email from Drupal and allow you to add programming logic to the process. For example you could:

Load the webform in question and view its results.
alter the to value of the $message to meet your needs.

'to': The address or addresses the message will be sent to. The
  formatting of this string will be validated with the PHP e-mail
  validation filter.
Comment: How would you load the webform, because when I grasp that, I think I might be good to go?
Comment: You probably dont want the webform itself, you want the submission by a given user. You want to look at the webform API, and at least the function [webform_get_submissions](http://drupalcontrib.org/api/drupal/contributions%21webform%21includes%21webform.submissions.inc/function/webform_get_submissions/7). Also if you simply do a `node_load()` on a `NID` with a webform -- you get the webform itself back as apart of the Node.


Como utilizar um nome customizável para o campo de senha no Laravel 8?

Question: Já tentei de tudo, mas nada funciona. Eu tenho quase certeza que o motivo é que o nome padrão do attempt "password" não condiz com a o nome da coluna passwordhash,
<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class LoginController extends Controller
{
    public function login(Request $request){
        $data =  $request->all();

        if(Auth::guard('admin')->attempt(['login'=>$data['loginadmin'],'password'=>$data['passadmin'],'isadmin'=>1]))
        {
            return 'logou';
        }else{
            return 'naao logou';
        }

    }

}

Meu Model User:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends \Illuminate\Foundation\Auth\User
{
    protected $table = "tb_user";
    protected $fillable = [
        'login',
        'passwordhash',
        'fullname',
        'cpf'
    ];
    public $timestamps = false;

}

Eu creio que vou precisar mudar esse padrão do Attempt "password" pra passwordhash, mas não faço a mínima ideia de como fazer. Ou pode até ser outra solução e eu não qual.
Desde já agradeço quem me ajudar.
Comment: voce ja tentou alterar a chave de array de `passsword` para `passwordhash` no método `attempt`?
Comment: pior que já tentei, mas quando faço isso da um erro q o atributo password está null, ou seja, é obrigatório usar desse jeito
Answer: Você precisa sobrescrever o método getAuthPassword no seu model de User  para que ele retorne o atributo passwordhash, veja:
class User extends \Illuminate\Foundation\Auth\User
{
    protected $table = "tb_user";
    protected $fillable = [
        'login',
        'passwordhash',
        'fullname',
        'cpf'
    ];
    public $timestamps = false;

    public function getAuthPassword()
    {
        return $this->passwordhash;
    }
}

Comment: Cara ajudou demaiss, só foi implementar que deu certo, obrigado mesmo.
Comment: O campo password está cadastrado "senha" no meu banco de dados. Eu tentei fazer com essa função mas não deu certo. Alguma outra ideia? Obrigado
Answer: Eu tentaria olhar na trait AuthenticateUsers, na função validateLogin, trocar na validação o 'password' pelo 'passwordhash', talvez o erro seja nessa validação que está dando o return false.


Parser XML Webservice em Java

Question: Estou tendo problemas com retorno XML de um webservice ao tentar fazer o parser. A saída do Netbeans reclama desta forma:

[Fatal Error] :1:13: O espaço em branco é obrigatório entre o destino da instrução de processamento e os dados.
  org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 13; O espaço em branco é obrigatório entre o destino da instrução de processamento e os dados.

O webservice é este: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=11748933&retmode=xml
Eu fiz algumas pesquisas aqui para tentar encontrar alguma solução, mas encontrei apenas uma tópico no qual o código está quase idêntico ao meu.
Link do tópico
O erro acontece nesta conversão:
Document doc = dBuilder.parse(source);

Método completo do request:
private void aplicaMetodoXML() throws MalformedURLException, IOException, ParserConfigurationException, SAXException {

    // conexão com o webservice
    StringBuilder xmlContent = new StringBuilder();
    URL url = new URL("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi?db=pubmed&id=11237011");
    HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
    conexao.setRequestMethod("GET");
    conexao.setRequestProperty("Content-Type", "text/xml");
    conexao.setDoInput(true);
    // tempo para requisição
    conexao.setConnectTimeout(5000);
    conexao.connect();

    /* Pega o dado requisitado e joga na string */
    Scanner scan = new Scanner(url.openStream());

    while (scan.hasNext()) {
        xmlContent.append(scan.next());

    }

    //System.out.println(xmlContent);]

    // Trata conteúdo xml
    String res = xmlContent.toString();
    StringReader sr = new StringReader(res);
    InputSource source = new InputSource(sr);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

    // Aqui onde a exceção é chamada
    Document doc = dBuilder.parse(source);

    doc.getDocumentElement().normalize();
    String teste = doc.getElementsByTagName("AbstractText").item(0).getTextContent();
    System.out.println(teste);
}

Já tentei mas não consigo achar onde está o problema. Há alguma outra alternativa para fazer o parser?
Answer: Resposta curta:
Mude o conteúdo da sua condição while para
xmlContent.append(scan.next() + " ");

Resposta longa:
Você comentou o trecho de código que mais te ajudaria a resolver esse problema:
//System.out.println(xmlContent);

Imprimindo o conteúdo do seu xml, sem a alteração de um espaço vazio, o resultado é:
<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEePostResultPUBLIC"-//NLM//DTDepost20090526//EN""https://eutils.ncbi.nlm.nih.gov/eutils/dtd/20090526/epost.dtd"><ePostResult><QueryKey>1</QueryKey><WebEnv>NCID_1_213127966_188.8.131.52_9001_1559196845_1904740853_0MetA0_S_MegaStore</WebEnv></ePostResult>

Isso resulta em um xml mal formado. Adicionando um espaço a cada iteração vai formar um xml possível de ser lido:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ePostResult PUBLIC "-//NLM//DTD epost 20090526//EN" "https://eutils.ncbi.nlm.nih.gov/eutils/dtd/20090526/epost.dtd"><ePostResult> <QueryKey>1</QueryKey> <WebEnv>NCID_1_48388134_22.214.171.124_9001_1559196975_1500027833_0MetA0_S_MegaStore</WebEnv> </ePostResult>

Comment: É isso aí, meu caro. Muito obrigado. Erro simples mas que acaba atrapalhando bastante. Principalmente pelo fato de eu não entender de XML, logo eu demoraria bastante para consertar - se é que eu conseguiria sozinho. Eu já tinha encontrado outras alternativas em Python, mas eu precisava dessa. Valeu, brother!
Comment: Que bom que resolveu! Mais importante que o erro em si, é entender o motivo que ele está acontecendo. Boa sorte ai!

Parser XML Webservice em Java


Image Src for calling a Servlet

Question: I want to call a Servlet from img src. I have defined a Servlet class with name ImageProducerServlet and registered it in web.xml:
<servlet>
   <servlet-name>ImageProducerServlet</servlet-name>
   <servlet-class>com.company.servlet.ImageProducerServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>ImageProducerServlet</servlet-name>
   <url-pattern>/imageproducerservlet</url-pattern>
</servlet-mapping>

In this servlet's doGet I just wrote a System.out. Now From the JSF page I am calling that servlet as:

I was expecting that it would print the System.out! But it doesn't.
The URL for the page where the img is added is:

http://localhost:7101/mycompany/faces/home

If I write in the address bar the follwoing URL:

http://localhost:7101/mycompany/imageproducerservlet

and press enter then the servlet's doGet is executing.
I am unable to find it's solution.
It will be very helpful if I get your suggestions.
Thanks and regards.
Answer: If this is working:
http://localhost:7101/mycompany/imageproducerservlet

then you need your img tag to look like that:

Answer: Just say

or

Answer: You need to prepend the context path. You preferably won't hardcode it as the context path is a server-controlled setting. You can obtain it from the HTTP request as follows:

An alternative is to use the HTML <base> tag and set it to the URL of the context root. This way every URL which doesn't start with / will be relative to it.
See also:

How get the base URL?

Image Src for calling a Servlet


Connecting Couchbase sync adapter to couchdb server

Question: How do I connect the couchbase sync adapter to a couchdb server, the docs only say how to use couchbase server and then to use the "administrator console" which couchdb doesn't have, and when I run
sync_adapter -url 192.168.1.xx/mydb

it returns an error
Before you say "it can't be done", here is a  quote from the couchbase docs

"Couchbase Lite can sync with servers running Apache CouchDB and with
  Couchbase Server via Sync Gateway."
Comment: Just to verify, you are trying to connect the Sync Gateway to a CouchDB server? You can't: it can either be backed by a Walrus file store or Couchbase Server. Why do you want to?
Comment: @Will Then explain this quote from the docs "Couchbase Lite can sync with servers running Apache CouchDB and with Couchbase Server via Sync Gateway."
Answer: Couchbase Lite is compatible with CouchDB replication, and you can use it same way as you would use Sync Gateway on top of Couchbase.
What you mixed here is 3 different tools:

Sync Gateway, which is actually adapter between Couchbase Server and CouchDB API
CouchDB which is another database
Couchbase Lite which is mobile database solution

To be more clear, Couchbase Lite is document storage database for mobile platform and from API it totally looks like CouchDB. Since CouchDB has nice and pretty replication algorithm that works over HTTP API (ye, you only need internet connection to make synchronization), authors of Couchbase Lite found it handy and used it.
Next, since Couchbase database uses binary protocol for (instead of HTTP replication) synchronization, they made Sync Gateway for that "HTTP API" sync.
I am not sure if you can replicate Sync Gateway (backed by Walrus or Couchbase) with CouchDB, but for sure you can replicate your Couchbase Lite with Sync Gateway AND/OR with CouchDB.
So long story short:

CouchDB = database with HTTP API for all operations,
Couchbase = database, binary protocol (=you need drivers for it),
Sync Gateway = HTTP API on top Couchbase
or you can say - Couchbase + Sync Gateway = CouchDB, and
Couchbase Lite = CouchDB for mobile
Answer: I don't think you can - note that Couchbase Server is a significant evolution / fork of CouchDB, and as such the two now differ significantly.
Would it be possible to change CouchDB to be able to connect to Couchbase Sync Gateway? Possibly, but AFAIK no-one has done that yet.
Comment: Then explain this quote from the docs "Couchbase Lite can sync with servers running Apache CouchDB and with Couchbase Server via Sync Gateway."
Comment: Sync Gateway proxies the Couchbase Server and manages revision information. It is a couch instance and you should be able to replicate against it. I'm working on a [Cordova app](https://github.com/wholcomb/habit_tracker) running Couchbase Lite that I got replicating against CouchDB. I'm in the process of converting it to Couchbase.
Answer: Synchronization/Replication is inherent in CouchDB.
It has it's own replication protocol. (http://docs.couchdb.org/en/latest/intro/overview.html?highlight=replication)
Depending on your application/goal you can sync/replicate directly to CouchDB without using the couchbase sync adapter.
Couchbase lite (both IOS and Android versions) can sync/replicate directly to Couchdb.
Two CouchDB instances can sync/replicate directly to each other.
Pouchdb can sync/replicate directly to other Pouchdb instances or to Couchdb.
You only need the couchbase sync adapter to get couchbase to sync/replicate.
Comment: How exactly? From what I've found couchbase lite only syncs through sync gateway
Comment: [Here](https://github.com/wholcomb/habit_tracker/blob/couchdb-rewrite/www/js/app.js#L124) is some example code that replicates a Couchbase Lite instance with a CouchDB.
Answer: sync_gateway -bucket mydb -url http://name:pass@localhost:8092
Comment: Wait, on this page you have both provided an answer to the question and said "it can't be done" which is it?
Comment: That is how you set up a Sync Gateway to run against Couchbase Server. It doesn't work with CouchDB.


How do I show the form for adding a node as block?

Question: I have a content type with the title and name fields. How can I the form for adding a node as block, in the front page?
I am using Drupal 7.
function mail_block_info() {
  $blocks = array();
  $blocks['mail_block'] = array(
    'info' => t('backend info left block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function mail_block_view($block_name = '') {
  if ($block_name == 'mail_block') {
    $match = TRUE;
    $types = array('mailin_list_node_form' => 1);
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(array('nid' => $nid));
      $type = $node->type;
      if (isset($types[$type])) {
        $match = FALSE;
      }
    }

    $contact_node = node_load($node);

    drupal_get_form($node);
    $block = array(
      'subject' => t(''),
      'content' => $content,
    );

    return $block;
  }
}

Comment: Do you mean you want the teaser of the node to be displayed? Or the full node? Or do you mean the node add form?
Comment: i mean node addform
Comment: As side note, it is useless to pass an empty string to `t()`: An empty string is an empty string in any language. There is no need to translate an empty string; just use `''`, instead of `t('')`.
Answer: Try node_add():
$content = node_add($type);

or:
$content = drupal_get_form($type . '_node_form', $node);

Also, please keep in mind that node_load() changed in D7. You should use it like this:
node_load($nid);

Comment: @MohamedIbrahim I'm pretty sure he means `node_load`...your code is: `node_load($node)`, which might have been valid in Drupal 6 but not in Drupal 7
Comment: @Clive In Drupal 6, it would work if `$node` is an array; in Drupal 7, the first argument must be the node ID, as you said.
Comment: you mean node_load_multiple()
Comment: Thanks @kiamlaluno I've forgotten most of D6 to be honest ;)
Answer: There are some errors in your code.
    $types = array('mailin_list_node_form' => 1);
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(array('nid' => $nid));
      $type = $node->type;
      if (isset($types[$type])) {
        $match = FALSE;
      }
    }

In Drupal 7, the first argument of node_load() is the node ID, not an array. The full code snippet is unnecessary complex. All that code can be replaced with a call to menu_get_object(), and to check the content type of a node you just compare $node->type with a string.
    $contact_node = node_load($node);

You are passing to node_load() an object you already obtained from node_load(). First, node_load() doesn't accept an object, in Drupal 7 (nor would it accept a node as first argument, in Drupal 6); secondly, it doesn't make sense to call node_load() when you have already obtained a node object from that function.
You initialize $contact_node, but that variable is not used from the rest of your code.
    drupal_get_form($node);

The parameters passed to drupal_get_form() are wrong; the first argument passed is the form ID, and you didn't pass that argument to the function.
The result returned from the function is not saved; probably you were supposed to save it in the $content variable.
I would use code similar to the following one.
function mail_block_view($delta = '') {
  if ($delta == 'mail_block' && ($node = menu_get_object()) && $node->type == 'YOUR CONTENT TYPE') {
    $block = array(
      'subject' => '',
      'content' => drupal_get_form('YOUR CONTENT TYPE FORM ID', $node),
    );

    return $block;
  }
}

Replace 'YOUR CONTENT TYPE' with the ID of the content type, and 'YOUR CONTENT TYPE FORM ID' with the form ID for the form, which is normally similar to <your_content_type>_node_form, where <your_content_type> is the string you used for 'YOUR CONTENT TYPE FORM ID'.
To notice that it is not necessary to pass an empty string to t() because an empty string is still an empty string in all the languages; there is no need to translate it.
Answer: Try this:
function mail_block_info() {
  $blocks = array();
  $blocks['mail_block'] = array(
    'info' => t('backend info left block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function mail_block_view($block_name = '') {
  global $user;

  if ($block_name == 'mail_block') {
    // This is required if you want to show this block even if user profile page.
    module_load_include('inc', 'node', 'node.pages');

    // Create a node for the content type.
    $node = new stdClass();
    $node->uid = $user->uid;
    $node->name = $user->name;
    $node->type = 'CONTENT_TYPE_NAME';
    $node->language = LANGUAGE_NONE;
    // Create the form.
    $form = drupal_get_form('CONTENT_TYPE_NAME_node_form', $node);

    $block = array(
      'subject' => t(''),
      'content' => drupal_render($form),
    );

    return $block;
  }
}

Answer: There is a module Form Block

Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

As its dev in D7 make sure you read the Issues for Form Block
Answer: function mail_block_view($block_name = '') {
  if ($block_name == 'mail_block') {
    $form = drupal_get_form('mailin_list_node_form');
    $block = array(
        'subject' => t(''),
        'content' => drupal_render($form),
    );
    return $block;
  }
}

Comment: The problem with the code is that the call to `drupal_get_form('mailin_list_node_form')` is missing an argument that is necessary: the node object. Without that, Drupal doesn't know for which node the form is being shown.
Comment: I have used this code but it return me an error: "Undefined variable: node in mail_block_view()."
Comment: i think that the name of content type is wrong
Comment: are you sure your content type's machine name is called "mailin_list"? Not "mailing_list"? (notice the g after mailin). I got it from your original question.
Comment: yes iam sure its called "mailin_list" ,
Comment: now i think all problem in the $block line
Comment: @kiamlaluno you are right. i have tried to do this and it resolved . function mail_block_view($block_name = '') {
     module_load_include('inc', 'node', 'node.pages');
  if ($block_name == 'mail_block') {
    $type = 'mailin_list';

//    $form = drupal_get_form($type);
    $form = node_add('mailin_list');
    $block = array(
        'subject' => t(''),
        'content' => drupal_render($form),
    );
    return $block;
  }

}
Comment: Sorry for misleading you. Yes, drupal_get_form should get the node object as a second parameter. Glad you got it working though, sorry again for wasting your time.


Concatenar string

Question: Quero concatenar o dia atual com o caractere "0", só que não estou conseguindo.
string diaAtual = DateTime.Now.ToString("d");
string diaFormatado = diaAtual+"0";

Preciso fazer isso para inserir em um select que estou usando. Pois no banco de dados a data esta em um formato diferente. O dia 01 é 10, o dia 02 é 20 e assim por diante. Então estou usando o select a seguir para pegar as datas menores que hoje
SELECT COUNT(DISTINCT SALES_ORDER) AS SALES_ORDER, COUNT(DISTINCT DELIVERY)
AS DELIVERY, COUNT(MATERIAL) AS MATERIAL
FROM V_CABOS WHERE DT_INI IS NOT NULL AND DT_FIM IS NULL AND PRIORIDADE < 30

Só que no lugar do dia que quer dizer 3 (dia atual), quero colocar a concatenação que no caso seria diaFormatado.
Comment: O que aconteceu ao executar esse código?
Comment: O dia primeiro tem que ser 10, o dia 2 tem que ser 20 e assim por diante. Preciso fazer isso para colocar em um select e pegar tudo que for menor que a data atual, só que a data no banco esta da forma que expliquei a cima
Comment: Vale a pena ler [**esse post**](https://pt.stackoverflow.com/questions/124/qual-o-meio-mais-apropriado-para-se-concatenar-strings)
Comment: Ok, mas deu algum erro no código? Explique melhor a parte de "não estou conseguindo", por favor
Comment: Esse é o select que estou usando: SELECT COUNT(DISTINCT SALES_ORDER) AS SALES_ORDER, COUNT(DISTINCT DELIVERY) AS DELIVERY, COUNT(MATERIAL) AS MATERIAL
FROM V_CABOS WHERE DT_INI IS NOT NULL AND DT_FIM IS NULL AND PRIORIDADE < 30. O 30 quer dizer que é dia 3. Se eu executar o código com o valor 30, ele funciona normalmente. Só que ao tentar concatenar o dia atual com o 0 para que fique 30, o select só retorna 0.
Comment: Você tem certeza de que que você quer concatenar à direita? se está trabalhando com data, poderia adicionar 10 dias... se você quer preencher o espaço vazio em uma string, poderia utilizar os `PadRight()` mas ainda assim não faz sentido. O que exatamente você está fazendo e o que deseja com isso?
Comment: Como assim 30 quer dizer 3? 300 seria 30?
Comment: No banco de dados o dia 01 esta como 10, o dia 02 como 20, e assim por diante. Quero pegar tudo que for menor que o dia atual, que no caso é 30. Então para que eu não fique mudando o código todo dia, quero pegar apenas o dia atual sem o zero e adicionar o zero a direita. Sim 300 seria 30
Comment: Não está claro porque você precisa fazer isso, parecendo inclusive ser um [Problema XY](https://pt.meta.stackoverflow.com/q/499/5878). Quanto ao problema na pergunta, não entendo muito de C#, mas testei o seu código e concatenou os valores, o que deixa sua pergunta ainda mais confusa.
Comment: Mas o dia 1 é guardado como 10 ? E o 10 seria 100 ? Parece muito estranho o que está a tentar fazer. Qual o objetivo dessa transformação ? Porque motivo ficou armazenado dessa maneira no banco ?
Comment: Isso vem de um sistema usado onde trabalho. Ele formata a data desta forma no banco. Sim o dia 1 é 10 e o dia 10 é 100.
Answer: para obter o dia atual já com duas casas você deve usar o comando:
string diaAtual = DateTime.Now.ToString("dd");

Comment: Não posso pegar a data dessa forma. Tenho que pegar a data do formato de 1 a 31 e não de 01 a 31.

Concatenar string


PhpmyadminController could not be found. CakePHP 2.3.5

Question: I have same problem as the following Question but the solution there didn't helped me.
I'm using Vagrant box precise64 (Ubuntu server 12.04) and set there all the required dependencies for CakePHP to work.
The project folder synced with no problem on the server.
Problem is, after installing PHPMyAdmin on the server, and trying to access it from my localhost:8080/phpmyadmin I get the following error:
Missing Controller
Error: PhpmyadminController could not be found.

Error: Create the class PhpmyadminController below in file: app/Controller/PhpmyadminController.php

I've check my .htaccess files, tried to fix with number of solutions (see above as one example) and none seem to work.
I made sure my virtual host allow overwrite to all so if I mess up the .htaccess I get error 500 (like it should be).
Here is my .htaccess content:
<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L]
</IfModule>

and even the VirtualHost (under sites-enabled on the server):
<VirtualHost *:80>
    ServerName savion.localhost
    ServerAdmin root@savion
    DocumentRoot "/myfinalproject/"

    <Directory "/myfinalproject/">
            Options -Indexes FollowSymLinks
            AllowOverride All
            Order allow,deny
            Allow from all
    </Directory>
</VirtualHost>

I can't find a resolution to this issue and will appreciate any help given.
Comment: You should set the `DocumentRoot` of your Directory to your `app/webroot` folder. Which will eliminate the problem of dealing with your `htaccess`.
Comment: Directory also? Or just DocumentRoot change is enough?
Comment: Did that and got 404, in the apache error.log it says: File does not exist: /myfinalproject\xd7
Comment: Then you probably want to make a rule in your htaccess to pass /phpmyadmin through the rewrite.
Comment: after the change I've just did? because previously it didn't work.
Comment: I wonder why he got a downvote on the question. Seems like a clear question to me.
Answer: Eventually the problem was in a corrupted installation of PHPMyAdmin, re installing it solved the problem.


Preencher matriz com ZERO nos espaços nulos, (python/django)

Question: O problema esta nas partes marcadas em vermelho, não estou conseguindo atribuir zeros a ela.
De acordo com modelo:

 O trecho do código que estou gerando esta tabela:

*Obs: A seleção deste período pode variar de acordo com a seleção: (ex. 2016 até 2017/ 2015 até 2017...)
Comment: É mais difícil verificar seu problema quando se coloca código como imagem. Poderia editar sua pergunta colando o código JS? (Isso pode ser feito clicando na imagem do papel com <> ao lado de inserir imagem)
Answer: Se as variáveis somatorio.3 e somatorio.2 estiverem apresentando o valor None, você pode usar o filtro default_if_none para traduzí-los para zero.
No seu caso ficaria assim:
{{ somatorio.3|default_if_none:"0" }}({{ somatorio.2|default_if_none:"0" }})

Comment: Cara tentei aqui e não rolo com default_if_none:"0". Ele segue igual.
Comment: Certamente o motivo é que `somatorio.3` e `somatorio.2` não possuem o valor `None`, ou seja, não são  valores nulos como vc colocou na sua pergunta.


Annonymous pre and post survey results with different N values

Question: I have some survey data which was collected pre and post intervention. There is a drop off in the N value of respondents and the surveys were anonymous. Can I compare the pre and post at an aggregate level for changes even though the total N the percentages are based on is lower?
Answer: In general, no. It will depend on the type of missingness that you have - that is, is there a pattern by which people failed to follow up? For example, if your survey dealt with income and people who had higher incomes were less likely to respond, merely comparing pre- and post- results might lead to biased estimation.
What I might recommend is looking up different types of missingness, executing a few tests to try to assess how the missingness affects your data, and then attempt to appropriately overcome it.
However, if your N is reasonably large and the difference between your pre- N and post- N is 5% or less, I might recommend ignoring those data and executing the analysis on those who only did the pre- and post-surveys as any missing data techniques will only minority affect the outcome.
Comment: The question seems to suggest that information about connections or links between pre and post respondents was not collected.


Create a list representing the inventory of products in python

Question: I have a programming assignment but I cannot figure out how to fix this output problem.
This is my output:
[['Choc 5\t'], ['Vani 10'], ['Stra 7'], ['Choc 3 '], ['Stra 4']]

But it should be like this:
['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]]

Code:
def process_input(lst):
    result = list(map(lambda x: [x[0:7]], lst))
    return result

string = input()
lines = []
while string != "END":
    lines.append(string)
    string = input()
print(process_input(lines))

Comment: Please give an example of an string used for `string = input()`
Answer: output = [['Choc 5\t'], ['Vani 10'], ['Stra 7'], ['Choc 3 '], ['Stra 4']]
print(output)
output = [[s[0].strip().split(' ')[0], int(s[0].strip().split(' ')[1])] for s in a]
print(output)

output
[['Choc 5\t'], ['Vani 10'], ['Stra 7'], ['Choc 3 '], ['Stra 4']]
[['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]]

Answer: You can try this approach :
data=[['Choc 5\t'], ['Vani 10'], ['Stra 7'], ['Choc 3 '], ['Stra 4']]

print(list(map(lambda x:[x[0].split()[0] , int(x[0].split()[1])],data)))

output:
[['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]]


Multiple barber paradox

Question: I'm having a little trouble formalizing the proof for this statement
Suppose B is the set of barbers in a town who shave ALL those and ONLY those who DO NOT shave themselves
I have to prove that the set B is either the empty set , or the barbers do not shave.
This result is intuitive given this particular formulation of the paradox, however I haven't been able to formally prove this result
I've tried to write down my process using latex but I end up with unformatted code \forall \exists \land
Comment: It seems to me that barbers who do not shave surely do not shave themselves. So I'm having trouble understanding how it could be that $B$ is not the empty set. (I mean that even if "the barbers do not shave" is true, the set $B$ should still be empty.)
Comment: This question was taken from an Italian maths textbook, I understood it to mean that any given Barber cannot have his beard shaved under any circumstances.

If a barber shaves another barber, then the barber being shaved would be compelled to shave himself , because he did not shave himself.

If the barber shaves himself, he is compelled not to shave himself.

The only solution is not to shave at all, which I understood to be different from not shaving oneself

I'm trying to formalize the above with set notation, or even propositional logic
Comment: Perhaps it is a case of original meaning lost in translation?  In English, I would regard "he does not shave" to imply "he does not shave himself and does not have anyone else shave him," which in turn implies "he does not shave himself." On the other hand, "he is shaved by someone else" would imply "he does not shave himself," but is a stronger statement (because it also implies "he shaves").
Comment: I think [this](http://en.wikipedia.org/wiki/Barber_paradox#Multiple_barbers) explains it quite well.
Comment: I had already read the section on multiple barbers on Wikipedia, and I agree with their conclusion, I'm just running into problems when trying to formalize it using set notation or predicate logic
Answer: You might try the following formalization:
$\forall a\in M :[[\exists b\in B: bSa] \iff \neg aSa]$
where
$M$ is the set of men in town
$B$ is the set of barbers, $B\subset M$
$bSa$ mean b shaves a
In words: Together, the barbers shave those and only those men in the village who do not shave themselves.

I have to prove that the set B is either the empty set , or the barbers do not shave.

It is not possible that there is only one barber.
It is possible that there are exactly two barbers x and y such that x shaves every man in town but himself, and y shaves x.
EDIT $1$
In addition, you can construct the shaves relation as a subset $S$ of $M\times M$ as follows:
$\forall a,b :[(a,b)\in S \iff (a,b)\in M\times M \land [[a=x \land b\ne x]\lor[a=y \land b=x]]]$
Then you can prove:
$\forall a\in M:[a\ne x \implies (x,a)\in S]$
$(x,x)\notin S$
$(y,x)\in S$
$\forall a\in M:[[ \exists b\in B:(b,a)\in S] \iff (a,a)\notin S]$
Other possibilities exist for $S$ including no barbers ($B=\emptyset$) and every man shaving himself (thanks WmE).
EDIT $2$
We make the following assumptions about the sets M, S and B:
1) All barbers are men who live in town
$B\subset M$
2) Shavers are unique.
$(a,b)\in S \land (c,b)\in S\implies a=c$
3) If a man doesn't shave himself, then a barber must shave him.
$(a,a)\notin S\implies \exists b\in B: (b,a)\in S$
Then it can be shown that
$\forall a\in M:[[ \exists b\in B:(b,a)\in S] \iff (a,a)\notin S]$
$\iff \forall a\in B: (a,a)\notin S$
i.e. the barbers cannot shave themselves.
See my formal proof (in DC Proof format) at Multiple Barber Paradox.
Comment: Thanks for your reply ! Yes I have already written a similar formalization, however it is not complete. Consider two of the barbers (elements of B) call them b1 and b2.

If B1 shaves B2, then B2 is one of those who don't shave themselves, thus B2 must then shave himself. Contradiction

If B2 shaves himself, he breaks the rules once again.

That is the condition I can't formalize. I even tried considering the cartesian product subset of M^2 .

Note: why does latex not work with me ? i followed the syntax ! \land
Comment: In the scenario of two barbers x and y, I think you will find that no such contradictions can be obtained since no man in town, including the two barbers shave themselves. If, on the other hand, you have only one barber, you can always obtain a contradiction. BTW, to use Latex here, you have to enclose your string in $-signs.
Comment: Very nice--well done
Answer: You can say that with two or more barbers it is not a problem. For example with two barbers a and b, they  together shave everyone who doesn't shave themselves and a shaves b and b shaves a, with three barbers, a b and c, a shaves b, b shaves c, and c shaves a. This thing keeps going further for four five or even 100 barbers.
Answer: With zero barbers it is also not a problem, as everyone has to shave themselves.
With one barber only there is a problem. There can never be a negative number of barbers.

Multiple barber paradox


Runtime Error handling

Question: class A {
    B b = new B();
    b.myMethod();
}

class B {
    public void myMethod() {
        C c = new C();
        c.errMethod();
    }
}

class C {
    public int errMethod() {
        // Some runtime Error
    }
}

Some runtime error in errMethod(). My application should not shutdown. What should I do here?
This is one of the Java interview question, we should not be using any exception handling technique. Is there any other way to handle this?
Comment: Google for `Exception Handling` in Java. Start from -> [Here](http://docs.oracle.com/javase/tutorial/essential/exceptions/)
Comment: Thanks for your response.
This is one of the java interview question, we should not be using any exception handling technique. Is there any other way to handle this.?
Comment: You want to handle an exception without exception handling techniques? That doesn't make sense at all.
Answer: Write the code in errMethod in a try/catch block.
public int errMethod(){

   try{
    //code goes here
   }
   catch(Exception e){
    // handle exception
   }
}

Runtime Error handling


How to display custom data array via Twig

Question: I've created service which gets the raw data from custom content type. It looks like this :

  Array
(
    [front_page_slider] => Array
        (
            [1] => Array
                (
                    [title] => Lorem ipsum dolor sit amet
                    [body] =>Some example slider text up here
                    [field_image] => http://localhost/drupal8/sites/default/files/2016-05/slider1.png
                    [field_link_uri] => http://example.com
                    [field_link_title] => see more
                )

        )

)

After that i use array_push function to add this array $variables global variable.
I've tried to display any of this fields like this:
<code>{{ dump(front_page_slider[1].title) }}
</code>
or this:
  {{ dump(front_page_slider) }}
But both return NULL. What I do wrong ?
Answer: Have you added 'front_page_slider to the variables array in your twig template definition?
File...module_name.module
<code>function hook_theme(array $existing, $type, $theme, $path) {
  return [
    'template_name' => [
          'variables' => [
           'front_page_slider' => [],
      ],
    ],
  ];
}
</code>
Comment: Where should I create this .module file ? In the theme directory ?
Comment: Yes. Your main directory should contain a module_name.info.yml, module_name.module, and your template directory.
Answer: Install Devel Module (also enable devel kint sub module)and use kint
What is Kint?

Kint for PHP is a tool designed to present your debugging data in the absolutely best way possible.
In other words, it's var_dump() and debug_backtrace() on steroids. Easy to use, but powerful and customizable. An essential addition to
  your development toolbox.
This module allows to use kint($data) like as dpm()/dsm()/krumo() in
  Devel module.

something like
           {{ kint(page) }}
Read more  and some usage about kint.


Analytically derive standard deviation of parent normal distribution (with known mean) from moments of the truncated normal distribution

Question: Given $\sigma_t$ and $\mu_t$ of a truncated normal distribution, as well as $\mu_p$ of the parent normal distribution, I would like to analytically compute the standard deviation $\sigma_p$ of the parent normal distribution.
A similar question has been asked before, without a solution. I want to give it another try though, also by specifying some constraints that apply in my case:

I'm specifically interested in the normal distribution and not a generic approach to truncated distributions
I assume knowing $\mu_p$
For the truncation of the lower tail I'm only interested in the case $a=0$
I also would be fine with a solution for the case of a truncation of the lower tail only (i.e. $a=0$); the two-sided truncation case with an arbitrary $b>0$ would also be of interest to me though.
An approximate analytical solution is fine

From Wikipedia I got for the one-sided truncation of the lower tail:
$\sigma_t^2=\sigma_p^2\left[1 + \alpha\frac{\phi(\alpha)}{Z} - \left(\frac{\phi(\alpha)}{Z}\right)^2\right]$
with $\;Z=1-\Phi(\alpha)$ and $\alpha=(a-\mu_p)/\sigma_p\;$ (i.e. $\alpha=-\mu_p/\sigma_p$ in my case).
(The two-sided case has a similar structure)
So essentially, I'm looking for an (approximate) analytical inverse of the form $\sigma_p=f(\mu_p,\sigma_t)$.
There is a paper which may be relevant in this context, but it exceeds my mathematical understanding, so I am not sure whether it helps.
Answer: For now, I ended up doing function fitting on simulated data. In particular, I was interested in the case of truncating at $a=0$ and $b=1$. The typical relationship between $\sigma_p$ and $\sigma_t$ depends on $\mu_p$ and looks as follows:

I compared a couple of sigmoid-type functions and ended up with a function of the type $\frac{x}{\sqrt{1+x^2}}$.
Two more facts one can use:

The asymptotic $\sigma_t$ is the standard deviation of a uniform distribution over the interval $[a=0; b=1]$, which is $\frac{1}{2\sqrt{3}}(b-a)=\frac{1}{2\sqrt{3}}$.
The problem is symmetric around 0.5. I decided to fit on the interval [0.5; 1] as it avoids the special case $\mu_p=0$.

The final fitting function for $\sigma_t$ was:
$f(\sigma_p, \mu_p; \alpha, \beta)=\frac{1}{2\sqrt{3}}\frac{\beta\mu_p^\alpha\sigma_p}{\sqrt{1 + (\beta\mu_p^\alpha \sigma_p)^2}}$
or by means of inversion: $\sigma_p=\frac{1}{\beta\mu_p^\alpha\sqrt{\frac{1}{12\sigma_t^2}-1}}$
..for which I obtained the parameters $\alpha=-0.712$ and $\beta=3.137$ by least square minimization. The fits look as follows:

There's obviously still room for improvement.
Update:
$
f(\sigma_p, \mu_p; \alpha_1, \beta_1, \alpha_2, \beta_2, \theta)=
\begin{cases}
\frac{1}{2\sqrt{3}}\frac{\beta_1\mu_p^{\alpha_1}\sigma_p}{\sqrt{1 + (\beta_1\mu_p^{\alpha_1} \sigma_p)^2}} & \text{if $\mu_p<\theta$}\\
\frac{1}{2\sqrt{3}}\tanh(\beta_2\mu_p^{\alpha_2}\sigma_p) & \text{else}
\end{cases}
$
or by means of inversion:
$
\sigma_p=\begin{cases}
\frac{1}{\beta_1\mu_p^{\alpha_1}\sqrt{\frac{1}{12\sigma_t^2}-1}} & \text{if $\mu_p<\theta$}\\
\frac{1}{\beta_2\mu_p^{\alpha_2}}\text{arctanh}(2\sqrt{3}\sigma_t) & \text{else}
\end{cases}
$
.. with $\alpha_1=-0.151$, $\beta_1=4.154$, $\alpha_2=-1.017$, $\beta_2=2.478$, $\theta=0.738$ works better:


iOS always add white background to images

Question: I am writing an app process image. But when I change alpha of an image to 0, it mean that this image will be transparent. And then I save this image to photo library.
<code> UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
</code>
But when I open this image again, i see that it has white background.
Does anybody know why?
Answer: Did you saved as jpeg?
try this:
<code>NSData* pngdata = UIImagePNGRepresentation (image);
UIImage* img = [UIImage imageWithData:pngdata];
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
</code>


easygui.msgbox ('You entered ' + flavour) TypeError: must be str, not NoneType

Question: import easygui

flavour = easygui.enterbox('What is your favourite ice cream flavour?')

easygui.msgbox ('You entered ' + flavour)

What do I do here so that when I hit the 'cancel' button on the 'enter' box it doesn't return an error? At the moment I get the following error:
"easygui.msgbox ('You entered ' + flavour)
TypeError: must be str, not NoneType"
Answer: this will do it
import easygui
while True:
flavour = easygui.enterbox('What is your favourite ice cream flavour?(type quit to quit)')
a = bool(flavour)
if a == False:
    easygui.msgbox('you did not enter something')
elif a == True:
    if flavour == 'quit':
        break
    else:
        easygui.msgbox ('You entered ' + flavour)

(i can make the program better but bigger and larger)
Answer: What is happening is that msgbox wants the message to be string. However, if you hit cancel, flavour is a NoneType object. You can add an if statement to make sure your code does not error out if you hit cancel. Do something like:
flavour = easygui.enterbox('What is your favourite ice cream flavour?')

if flavour is not None:
    easygui.msgbox ('You entered ' + str(flavour))
else:
    pass


Why are "large prime numbers" used in RSA/encryption?

Question: I've learned the theory of public key encryption but I'm missing the connection to the physical world. e.g.
I've been told that good RSA encryption should rely on prime numbers with 300 decimal digits but why? who came up with this number? How long it will take to break such encryption (statistics about different machines).
I've tried Google, but couldn't find what I wanted. anyone?
thanks
Comment: Please focus questions. Hopefully the title change will prevent this from being mercilessly downvoted and closed ..
Answer: The key of asymmetric cryptography is to have an asymmetric function which allow decrypting message encrypted by the asymmetric key, without allowing to find the other key. In RSA, the function used is based on factorization of prime numbers however it is not the only option (Elliptic curve is another one for example).
So, basically you need two prime numbers for generating a RSA key pair. If you are able to factorize the public key and find these prime numbers, you will then be able to find the private key. The whole security of RSA is based on the fact that it is not easy to factorize large composite numbers, that's why the length of the key highly change the robustness of the RSA algorithm.
There are competitions to factorize large prime numbers with calculators each years with nice price. The last step of factorizing RSA key was done in 2009 by factorizing 768 bits keys. That's why at least 2048 bit keys should be used now.
As usual, Wikipedia is a good reference on RSA.
Comment: The security of RSA is based on the difficulty of factoring large *composite* numbers that are the product of two primes of roughly the same size.
Comment: not really ... the security of RSA is based on the fact that you can't efficiently calculate a modular inverse ... in this case you need PHI(n) for that calculation while you only have n with n=p*q with p and q unknown ... if you find another way to calculate PHI(n) ... other than (p-1)*(q-1) ... you would have broken RSA without factorizing n ... but that task is considered at least as difficult as factorizing n
Comment: I am a bit late to the party, but this answer really coalesced my understanding of RSA.
Answer: All public key algorithms are based on trapdoor functions, that is, mathematical constructs that are "easy" to compute in one way, but "hard" to reverse unless you have also some additional information (used as private key) at which point also the reverse becomes "easy".
"Easy" and "hard" are just qualitative adjectives that are always more formally defined in terms of computational complexity. "Hard" very often refers to computations that cannot be solved in polynomial time O(nx) for some fixed x and where n is the input data.
In the case of RSA, the "easy" function is the modular exponentiation C = Me mod N where the factors of N are kept secret. The "hard" problem is to find the e-th root of C (that is, M). Of course, "hard" does not mean that it is always hard, but (intuitively) that increasing the size of N by a certain factor increases the complexity by a much larger factor.
The sizes of the modulus which are recommended (2048 bits, or 617 decimal digits) relate to the availability of computation power at present time, so that if you stick to them you are assured that it will be extremely expensive for the attacker to break it. For more details, I should refer you to a brilliant answer on cryptography.SE (go and upvote :-)).
Finally, in order to have a trapdoor, N is built so as to be a composite number. It theory, for improved performance, N may have more than 2 factors, but the general security rule is that all factors must be balanced and have roughly the same size. That means that if you have K factors, and N is B bits long, each factor is roughly B/K bits longs.
This problem to solve is not the same as the integer factorization problem though. The two are related in that if you manage to factor N you can compute the private key by re-doing what the party that generated the key did. Typically, the exponent e being used is very small (3); it cannot be excluded that someday somebody devises an algorithm to compute the e-th without factoring N.
EDIT: Corrected the number of decimal digits for the modulus of a 2048 bits RSA key.
Answer: RSA uses the idea of one-way math functions, so that it's easy to encrypt and decrypt if you have the key, but hard (as in it takes lots and lots of CPU cycles) to decrypt if you don't have the key. Even before they thought of using prime numbers, mathematicians identified the need for a one-way function.
The first method they hit upon was the idea that if your "key" is a prime number, and your message is another number, then you can encrypt by multiplying the two together. Someone with the key can easily divide out the prime number and get the message, but for someone without the prime number, figuring out the prime number key is hard.
Comment: Sorry for the harshness, removed my comments. I've not removed my downvote, I don't think this makes it any clearer.


Setar valores dentro ou fora do método?

Question: Estou estudando sobre a passagem de parâmetros no PHP. Eu quero, por exemplo, usar um determinado método que precisa receber dois valores, tenho os seguintes códigos:
Exemplo 1
Na class:
class Exemplo {
        protected $var1, $var2;

        public function setVar1($value){
           $this->var1 = $value;
           return $this;
        }
        public function setVar2($value){
           $this->var2 = $value;
           return $this;
        }

        public function exemplo(){
           $dado1 = $this->var1;
           $dado2 = $this->var2;
        }
}

E a chamada
 $exe = new Exemplo();
 $exe->setVar1('dado1')
     ->setVar2('dado2')
     ->exemplo();

Ou
Exemplo 2
Na class:
class Exemplo {
   public function exemplo($var1, $var2)
   {
      $dado1 = $var1;
      $dado2 = $var2;
   }
}

E a chamada
 $exe = new Exemplo();
 $exe->exemplo('dado1', 'dado2');

Aparentemente os dois códigos fazem o mesmo, e o Exemplo 2 claramente é bem mais simples de se fazer, gostaria de saber qual a diferença entre eles além da escrita, e/ou qual seria a forma mais correta (se existir) ou melhor. E em termos de segurança e velocidade eles possuem diferença?
Answer: Bom, nessa pergunta os dois exemplos não são equivalentes. Em ambos o método exemplo() não faz nada útil de fato. Atribuir valores para variáveis locais e não fazer nada com eles não faz sentido. Então faça o mais simples, o que tem menos passos. Eu diria que é o exemplo 2, mas até ele é desnecessário.
Se o método fosse:
public function exemplo($var1, $var2) {
    $dado1 = $this->var1 = $var1;
    $dado2 = $this->var1 = $var2;
}

Coloquei no GitHub para referência futura.
Aí a diferença é que o segundo você garante que as duas propriedades são atribuídas juntas. É uma operação atômica. No primeiro exemplo é possível fazer de forma separada.
Não há diferença relevante de velocidade. Segurança propriamente não muda nada. É uma questão de intenção. Se as duas propriedades precisam ser mudadas juntas, o primeiro exemplo é errado. Se eles precisam, mesmo que eventualmente serem mudadas independentemente, o segundo é errado.
Então não tem melhor, tem o certo e o errado. E depende da situação.
Nesse exemplo eu diria que tanto faz. Em um exemplo mais concreto, depende. Tem muita regrinha que as pessoas escrevem e vários programadores seguem que não fazem sentido. Se você seguir cegamente, acaba fazendo errado.
De uma maneira geral sé deve criar métodos setters se tiver um bom motivo para isso. Se não encontrar uma boa justificativa para criá-los, não crie.
Answer: Isso é uma questão de escopo e ecapsulamento.
A pergunta é você vai usar esses valores fora do escopo do método?
Se sim, talvez seja interessante usar os "set".
Você vai precisar tratar/validar esses dados na entrada?
Se sim definitivamente é melhor usar o "set"
Partindo dos conceitos de SOLID responsabilidade única,é melhor realizar o tratamento da informação em um método certo pra isso no caso seria o Set.
Edit: Ah esqueci, tem a questão do controle de acesso na informação. Caso essa informação vá ser usada somente dentro da classe e não é para ficar aberta talvez seja interessante definir as variaveis como private e usar o set mesmo.

Setar valores dentro ou fora do método?


Onde os bancos ficam salvos no SQL*Plus?

Question: Eu baixei o SQL*Plus no site da Oracle, instalei (meu notebook é Windows 10) criei usuário e já criei alguns bancos, mas não sei onde ele salva os bancos que criei. Onde fica?
Answer: Em nenhum lugar. O SQL*Plus é um utilitário para uso de comandos, principalmente em scripts para manipular bancos de dados. Ele não é um banco de dados, então não tem porque estar em algum lugar.
Deve ter criado bases de dados no Oracle Database através do SQL * Plus. Os arquivos dele podem estar em qualquer lugar. É possível configurar isso. O mais adequado é consultar onde eles foram instalados. Pode consultar pelo SQL*Plus:
select name from v$datafile;

Também consultar por:
select value from v$parameter where name = 'db_create_file_dest'

Outra possibilidade:
select * from dba_data_files;

Coloquei no GitHub para referência futura.
Há uma documentação sobre o assunto.
Comment: Olá, instalei no windows 10, eu baixei o oracleXE11.
Eu ainda não consegui encontrar onde os bancos ficam salvos.


Confidence interval probability

Question: I am struggling to even understand how to approach this problem
Finding the probability of
$$P(Z<z_a+z_{1-a})$$
Where Z is a standard normal variable and
$$P(Z\leq z_a)=1-a$$
Is there manipulation rules for adding arguments in a normal distribution? How do I even start with this?
Comment: I think I figured it out. I (think that) was able to prove that $z_{1-a}$=$-z_a$ therefor the probability is always 0.5
Answer: There's an implicit symmetry here:
 note that $z_a = -z_{1-a}$ because $\Pr(z>z_a)=a$ also $\Pr(z<z_{1-a}) = a$. This is telling you that the area to the left of $z_{1-a}$ is equal to that on the right of $z_a$. With that being said,
$$\Pr(Z < z_a + z_{1-a}) = \Pr( Z <0) = 0.5$$

Confidence interval probability


Copy stored procedure from one database to another using T-sql

Question: I'm using sql server
I want to copy a stored procedure from one database to another using T-sql,
but my stored procedure contains dynamic sql.
I get the definition from sys.sql_modules and execute it using this code
exec sp_executesql @sp_definition

but it gives me error:

Msg 102, Level 15, State 1, Line 23 Incorrect syntax near ' + @tblName + '

Example of my stored procedure
CREATE Procedure insertRow
(
    @tblName nvarchar(250),
    @value  nvarchar(250)
)
AS
    DECLARE @script nvarchar(1000)
    SET @script='INSERT INTO '+@tblName +' VALUES('+@value+')'
    exec @script

How can i escape the quotes to execute it succesfully
Comment: *but it gives me errors* is not very clear. Try to print out the content of `@sp_definition` and try to execute this directly. Do you get the same errors? Might be connected to *internal quotes* due to your dynamic SQL...
Comment: The error is because your didn't spell VALUES correctly. Thankfully this failed or you might have actually used this in your system. This stored procedure is wide open to sql injection attack. This is example of trying to create the "one procedure to rule them all". Don't do this to yourself. Create an insert procedure for all your tables and avoid dynamic sql where you directly execute input values like this. My friend bobby tables loves this kind of thing. http://bobby-tables.com/
Comment: could u Give us an example ??
Comment: Since it gives you errors, you should give us errors--kind of helps
Comment: Msg 102, Level 15, State 1, Line 23
Incorrect syntax near ' + @tblName + '
Comment: this is example but not my real code , here i want to show example of stored procedure that uses dynamic sql
Comment: Try adding a print command tight after the SET command something like     PRINT @Script. then it ill show you what the query looks like. You are gonna have to just play around with quote marks until you get it right, At least this way it shows you what it sees,
Comment: the syntax of this procedure is correct , the error occurs when i try to copy this stored procedure to another database using t-sql : my process is :1- select sp(named inserRow) definition from database1 and execute it using exec in database2
Answer: The solution is to escape quotes properly and using ''' instead of only one quote