Can DRS be used to challenge which batsman was run out?

Question: This could be a "hilarious" use of the Decision Review System, but nonetheless I want to know if it is possible.
Suppose both the batsmen run to the same end (mix-up, as commentators like to call it), and the fielding side puts down the wicket at one end. The on-field umpire declares one of the batsmen out. Can this batsman invoke DRS to challenge the umpire's decision, in effect, claiming that his partner should be out instead?
A non-hilarious scenario would be if a top-order batsman and a tailender gets involved in the mix-up, and the tailender is given out. The fielding captain might want to invoke the DRS to try to get the more skilled batsman out instead.
Comment: I've seen them go upstairs for this, you think that if it's close they'd do this
Comment: You are right, but that's different from using DRS. On-field umpires can seek help from the TV umpire when they please (subject to some restrictions), but I am not sure if players too can use DRS for that purpose.
Comment: A little off topic, but I remember a match where they spent a good 5 minutes working out which person was out after a major mix up. I think they were both at the same end.
Answer: From Wikipedia:

A fielding team may use the system to dispute a "not out" call ...

and

At their discretion, field umpires may request the Third Umpire ... to determine run outs ...

These in combination would seem to suggest that the fielders can appeal the 'not-out' decision of the second batsman. The field umpires would then defer to the video umpire for a decision.
Note that because UDRS requires clear contradiction to the original call, the video would have to definitively show the 'not-out' batsman being nearest to the crease. Any hint of the distances being indeterminate would result in upholding the decision and a loss of review for the fielding team.
Answer: On close runout calls On-filed umpires takes help from TV umpire, then there is no point of asking  DRS (because the same answer will come even if he asks for DRS). Even in the confusing situation (both batsman are at the same end) can be handled by taking help of TV umpire.
Comment: You are right, however, a lot of players have been very lousy with the use of DRS, often challenging blatantly obvious decisions only to look foolish on the big screen. Even if the on-field umpire doesn't refer to the TV umpire (because he thinks the decision is obvious enough), do the laws permit the players to challenge it?


how to get the page source and search with Watin

Question: i'm using Watin and i want to search in the page source (HTML), like the ctrl+F search, what is the best way to do it?
thanx for any help,
Shiran
Comment: Did my answer assist you ?Things move fast at stackoverflow best you check every hour...
Answer: This should help you, that is a example of how to impliment it
<code>        // Find text like ctr+F (NOT IN SOURCE BUT IN "WHAT YOU SEE"
        if (ie.Text.Contains("SOME TEXT TO FIND").Equals(true))
        {
            //Do stuff you would like when found here
            MessageBox.Show("Text Found! ");

        }
        else
        {
            // cant find
        }

        //OR

        // Find text in SOURCE
        if (ie.Html.Contains("SOME TEXT TO FIND").Equals(true))
        {
            //Do stuff you would like when found here
            MessageBox.Show("Text Found! ");

        }
        else
        {
            // cant find
        }
</code>
Answer: You can use the IE.Text property to get the text of the whole page equivalent to innerText of the body element. Otherwise if you want the raw HTML you can use IE.Html.


Angular datatables nested rows rendering

Question: Is there a better way to display nested tables in angular-datatables?
I solved my problem by using rowCallback and setting up click event:
$scope.dtOptions = DTOptionsBuilder.fromSource('data.json')
    .withOption('rowCallback', rowCallback)

and in a click handler I get dt-instance and build html using row data from data table instance.
function rowCallback(tabRow, data, dataIndex) {
    $(tabRow).unbind('click');
    $(tabRow).on('click', function () {
        console.log('click');
        $(this).find('.a1-icon').toggleClass('fa-rotate-180');
        var tr = $(tabRow);
        var table = $scope.dtInstance.DataTable;
        var row = table.row(tr);

        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Open this row
            row.child( format(row.data()) ).show();
            tr.addClass('shown');
        }
    });
}

But it feels a litte bit weird especially for angular. Here is Plunker with full simplified code http://plnkr.co/edit/gVf926obJKTXvXU7fLdA?p=preview
Answer:

 $(tabRow).on('click', function () {})

//instead of this "on" event Use "load"

 $(tabRow).load('click', function () {})


Conditional probability that one of three random variables is the largest

Question: Suppose I have three random variables $X_1$, $X_2$, and $X_3$ that are i.i.d $N(0,1)$ distributed. The chance that $X_3$ is larger than $X_2$, given that $X_3$ is also larger than $X_1$ should equal $\frac{2}{3}$ in theory. However, when trying to calculate this conditional probability, I always end up with an probability equal to 1, which obviously is not correct. Perhaps you could point out where my mistake is?
$\Pr[X_3 > X_2 \mid X_3 > X_1] = \Pr[X_2 < X_1]\Pr[X_3 > X_2 \mid X_3 > X_1, X_2 < X_1]+\Pr[X_2 \geq X_1]\Pr[X_3 > X_2 \mid X_3 > X_1, X_2 \geq X_1]$.
I then rewrite the last term as
$\Pr[X_2 \geq X_1]\Pr[X_3 > X_2 \mid X_3 > X_1, X_2 \geq X_1] = \Pr[X_2 \geq X_1]\frac{\Pr[X_3 > X_2]}{\Pr[X_3 > X_1]}$.
This gives me
$\Pr[X_3 > X_2 \mid X_3 > X_1] = 0.5 * 1 + 0.5\frac{0.5}{0.5} = 1 \neq \frac{2}{3}$.
Answer: The easiest thing is to look at it combinatorically. If you rank the numbers $X_i$ by 1,2 and 3 according to their magnitude (3 is the largest), then you have 6 ranked combinations of ($X_1,X_2,X_3$) in total: (1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2) and (3,2,1).
The ones with $X_3>X_1$: (1,2,3),(1,3,2) and (2,1,3).
Out of these two combinations also have $X_3>X_2$: (1,2,3) and (2,1,3).
Hence your probability $P(X_3>X_2\mid X_3>X_1)$: 2/3


Spring Security without Spring Tag Library (JSTL)

Question: We are having a typical web application which uses Spring Security and JSPs. We use standard Spring Security tag library to show/hide, allow/restrict parts of the web pages based of user roles.
Now we are going to change the JSP part and write a complete Javascript based client.

Is there a way to get a similar functionality provided by the tag library with Javascript.
If not, what are the things we should be worry about in implementing our own mechanism in Javascript.

Thanks,
Ish
Answer: If your question is "does Spring Security have a Javascript equivalent to the JSP tags" then the answer is definitely "no". The obvious difference is that Javascript runs on the client whereas JSP is executed on the server, so you can't just rely on hiding sensitive information using a Javascript library as this would be insecure.
A Javascript client is fundamentally different and the security will most likely be implemented in the API you expose to it to allow it to retrieve data from the server. It will consist of security contstraints applied to URLs and server-side methods, rather than having anything to do with a display technology, so in some ways it is simpler to test and reason about than JSP security, since it is decoupled from the actual display code.
Comment: Thanks for your response. So if I have a menu called 'administration' item in my application is it accessible only for Server Admins, I should show it to every users and display a message saying "You are not Allowed" after the request hits the server side, if he/she is not an admin.
Comment: No, I'd say you'd only show the item to people who have the admin role. If you're using a REST-like API, then the menu would probably be the result of a request to the server, and the links you return would be dependent on the user's role.


Enviar e-mail no final de cada mês

Question: Tenho um sistema de assinatura de usuários, eu preciso enviar uma notificação todo final de mês avisando que a assinatura esta vencendo, o problema é que eu não sei como fazer esse script ser executado automaticamente sem que eu precise ficar acessando uma determinada página para que ele seja executado, vou tentar dar um exemplo de forma simplista:
Vamos supor que eu queira enviar esse e-mail no dia 02 de outubro, então eu faria assim:
$data_programada = '02/10/2018';
if(date('d/m/Y') == $data_programada) {

    mail('email@example.com','vencimento','mensagem de vencimento');

}

o problema é que esse e-mail só vai ser enviado se eu acessar a página que contem esse script, eu preciso que faça isso automaticamente
Comment: Possível duplicata de [Alerta por email tal dia](https://pt.stackoverflow.com/questions/30100/alerta-por-email-tal-dia)
Comment: Possível duplicata de [Como criar um Cron job?](https://pt.stackoverflow.com/questions/248534/como-criar-um-cron-job)
Answer: O que você quer é um CronJob:
O que são CRON JOBS e como usa-los com PHP
Este exemplo utiliza o mecanismo de cron do unix/linux, que é o mais comum de ser utilizado, porém existem mecanismos que se integram diretamente a linguagem, como é o caso do Quartz para Java, porém não conheço nenhum desse para PHP.
Minha dica: Use o cron do linux :)
Complementando a resposta:
É preciso adicionar uma entrada na cron do seu usuário do sistema (linux):
Passo 1: Crie o arquivo que será executado:
Arquivo helloworld.php
<?php

echo 'Hello world';

?>

Passo 2: Inicie a alteração no arquivo de cron do sistema usando o comando 'crontab -e'.
Esse comando irá abrir o arquivo de cron usando o editor default, provavelmente o vim
Passo 3: Adicione a entrada de cron desejada com o arquivo que foi criado. Neste exemplo vou colocar pra executar todo primeiro dia de mês as 9 da manhã:
0 9 1 * * php -f /home/murilo/meu_php/helloworld.php > /dev/null 2>&1

Descrição:
0 9 1 * * -> Expressão cron para executar em todo primeiro dia do mes as 9 da manhã (para mais exemplos acesse https://crontab-generator.org/)

php -f /home/murilo/meu_php/helloworld.php -> Comando a ser executado

> /dev/null 2>&1 -> Direcionando sysouts para /dev/null

Passo 4: Salve o arquivo e pronto, está configurado !
Para executar exatamente no final do mês é um pouco mais complicado, pois como os meses possuem diferentes dias de término (pode acabar no dia 28, 29, 30 ou 31) a expressão cron fica uma pouco mais complicada.
O jeito mais fácil que achei foi criando mais  de uma entrada na cron para cobrir os diferentes casos.
Veja:
https://stackoverflow.com/questions/6139189/cron-job-to-run-on-the-last-day-of-the-month
https://blog.nexcess.net/2013/05/09/cron-job-for-the-last-day-of-the-month/
Comment: preciso ter uma vps para fazer isso? uma hospedagem compartilhada tem como?
Comment: Até onde sei é possível sim fazer isso em uma hospedagem compartilhada. Aconselho entrar em contato com sua hospedagem para saber como fazer, pois eles podem  usar configurações diferentes, como local de instalação do php e etc.

Enviar e-mail no final de cada mês


Escaping ' from mySQL array

Question: There is some text stored in mysql table as long text. It contains ' characters.
Trying to escape these so I can fetch the results. Anything having ' gives error.
review_text with ' fails to bring back anything. The answer is supposed to be with mysql_real_escape_string but that's not working.
while ($row = mysql_fetch_array($result)) {
    $review = array();
    $review["name"] = $row["reviewer_name"];
    $review["title"] = $row["review_title"];
    $review["content"] = $row["review_text"];
    $review["rating"] = $row["review_rating"];
    $review["time"] = $row["date_time"];
    // push single product into final response array
    array_push($response["reviews"], $review);
}

Comment: you don't need to escape it if it's for viewing. If there's no user input, then I don't see why you'd want to "escape" anything. If you really want to, then use `stripslashes` http://php.net/manual/en/function.stripslashes.php even then, that may not be what you want. Like I said, there's no need to escape it if it's just for displaying purposes.
Comment: good point @Fred-ii-   I find it is easier to use prepared statements, no need to escape, `stripslashes` etc.  with all the added benefits
Comment: *"Anything having `'` gives error."* - Show us that error.
Comment: @nomistic hard to say till we know what the *real* purpose is.
Comment: @Fred-ii- I'm guessing that it ends or starts a string breaking anything after it. ;)
Comment: I can't think of an instance where a `'` being present in your provided code would cause an issue. Perhaps you went too minimal?
Comment: @Fred -ii- In my database, there is a field called review_text.
So the ' is present in the review text part.The review_text field is of  Long Text type. I want to print that data using PHP, but its not printing anything.  Please let me know if there is a way to print the data with ' or %.
Answer: There are several ways of handling this, however first of you need to stop using deprecated mysql_ extensions.   "Deprecated" means that they are no longer included within php, and soon will stop working, as it states on the official php site here:  http://php.net/manual/en/function.mysql-fetch-array.php

Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in
  the future. Instead, the MySQLi or PDO_MySQL extension should be used.
  See also MySQL: choosing an API guide and related FAQ for more
  information. Alternatives to this function include:
mysqli_fetch_array()
PDOStatement::fetch()

You can use mysqli_real_escape_string to "escape" your variables, however it's much better to use prepared statements.   Either mysqli_ or PDO will work.
In this case where you are getting the variables using a select, you can do as follows (it's not clear where you are getting your variables but let's use this as an assumption), you would connect to your database like so:
$conn = new mysqli($host, $username, $password, $dbname);

if  ($conn->connect_error) {
    die("Connection failed: " . $dbc->connect_error);

$stmt = $conn->prepare(select name, title, content, rating, time from tablename where variable = ?);
// this is assuming that this is a string, so "s" is used, otherwise use "i" for string
$stmt->bind_param("s",$variable);
$stmt->execute();
//then you can bind your results into tidy variables all of which have been "escaped"
$stmt->bind_result($name, $title, $content, $rating, $time);
$stmt->close();

To get your variables, insteady of using mysql_fetch_array() you just use $stmt->fetch();
or like this:
while (stmt->fetch()) {
    [stuff here]
}

voila, your variables are pretty clean.   Note: while these will handle quotations, apostrophes, etc, they will also be much more secure for protection against SQL injecction.  You can also use PDO.
Comment: I'm glad I could help. :) To help future users it's good to check  the correct answer

Escaping ' from mySQL array


Migrar função PHP de mcrypt para Openssl

Question: Tenho uma função em PHP que utiliza o mcrypt.
O problema é que o PHP 7.2 não aceita mais o mcrypt...
Alguém sabe como refazê-la de modo a obter o mesmo resultado utilizando o Openssl?
function Encript($Val, $chave){

    $cifrado = MCRYPT_RIJNDAEL_256;
    $modo = MCRYPT_MODE_ECB;
    $Cript = mcrypt_encrypt($cifrado, $chave, $Val, $modo, mcrypt_create_iv(mcrypt_get_iv_size($cifrado, $modo), MCRYPT_DEV_RANDOM));
    return base64_encode($Cript);

}

function Decript($Val, $chave){

    $Base = base64_decode($Val);

    $cifrado = MCRYPT_RIJNDAEL_256;
    $modo = MCRYPT_MODE_ECB;
    return mcrypt_decrypt($cifrado, $chave, $Base, $modo, mcrypt_create_iv(mcrypt_get_iv_size($cifrado, $modo), MCRYPT_DEV_RANDOM));

}

Answer: Infelizmente, você precisará criptografar novamente todos os seus dados e na verdade desde de PHP 7.1.0, o mcrypt_decrypt e o mcrypt_encrypt estão depreciados, sendo assim para resolver o teu problema você precisa usar o  openssl_encrypt e o openssl_decrypt, algo como isto.
$string="string";
$chave="chave";
$encrypted_string=openssl_encrypt($string,"AES-128-ECB",$chave);
$decrypted_string=openssl_decrypt($encrypted_string,"AES-128-ECB",$chave);

Só lembrando ECB não é totalmente seguro, mas é simples. Documentação :
Comment: Veja se a alteração atende ao que você queria.
Comment: Poderia ter apenas corridigo, mas tudo bem, acabou passando despercebido.
Answer: Não há como portar para o OpenSSL. Isso ocorre porque o MCRYPT_RIJNDAEL_256 não é igual ao AES-256, ele usa uma versão não-padrão. O AES opera sempre com blocos tamanho de 128 bytes, mesmo no AES-256, isso não ocorre no MCrypt, que usa blocos maiores. O AES-256 é mais vulnerável do que o AES-128 em alguns tipos de ataques, mas a construção do MCrypt é ainda menos estudada, o que o torna menos seguro.
Uma outra observação é o uso do ECB, nunca use ECB, você consegue ver o penguim crifrado. Além disso, o modo usado não garante integridade da informação, é ainda possível mudar o texto cifrado.

Você tem duas opções:
1.Use OpenSSL com AES-256-GCM:
$nonce = random_bytes(openssl_cipher_iv_length("aes-256-gcm")); // Há riscos de colisão devido ao pequeno tamanho!
$cifrado = openssl_encrypt($Val, "aes-256-gcm", $chave, '', $nonce, $tag);

$original = openssl_decrypt($cifrado, "aes-256-gcm", $chave, '', $nonce, $tag);

2.Use LibSodium com XChaCha20Poly1305 (recomendado):
$nonce = random_bytes(SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES);
$cifrado = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt($Val, '', $nonce, $chave);

$original = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt($cifrado, '', $nonce, $chave);

Em qualquer um dos dois é preciso que decifre e cifre novamente, preferencialmente com novas chaves.


Flutter - Unexpected character when decoding json

Question: Unexpected characters  showing up when I decoding json
E/flutter (27537): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter (27537): {"data":[{"kode_wilayah":"056001  ","nama":"Kec. Karang Pilang","mst_kod...
E/flutter (27537): ^
E/flutter (27537):
E/flutter (27537): #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1392:5)

Here is the code
Future<List<Kecamatan>> getData() async {
    List<Kecamatan> list;
    String link =
            "http://jendela.data.kemdikbud.go.id/api/index.php/CWilayah/wilayahGET/?mst_kode_wilayah=056000";
    var res = await http
        .get(Uri.encodeFull(link), headers: {"Accept": "application/json;charset=UTF-8", "Charset": "utf-8"});
    print(res.body);
        if (res.statusCode == 200) {
        var data = json.decode(res.body);
        var rest = data["data"] as List;
        print(rest);
        list = rest.map<Kecamatan>((json) => Kecamatan.fromJson(json)).toList();
        }
    print("List Size: ${list.length}");
    return list;
}

//inside build function
final kec = FutureBuilder<List<Kecamatan>>(
    future: getData(),
    builder: (BuildContext context,
        AsyncSnapshot<List<Kecamatan>> snapshot) {
    if (!snapshot.hasData) return CircularProgressIndicator();
    return DropdownButton<Kecamatan>(
        items: snapshot.data
            .map((camat) => DropdownMenuItem<Kecamatan>(
                child: Text(camat.nama),
                value: camat,
                ))
            .toList(),
        onChanged: (Kecamatan value) {
        setState(() {
            _selectedKec = value;
        });
        },
        isExpanded: false,
        //value: _currentCamat,
        hint: Text('Pilih Kecamatan'),
    );
});

Anybody know how to remove those characters? or maybe you can show me another method to create dropdown menu based on json?
Answer: You can do this in such a way:
  if (res.statusCode == 200) {
    // <============
    final prefix = '';
    var body = res.body;
    if (body.startsWith(prefix)) {
      body = body.substring(prefix.length);
    }
    // ============>

    var data = json.decode(body);
    var rest = data["data"] as List;
  }


show the rule between $w$, $w^2$, ...$w^{n-1}$ with $w^n$ given w an nth root of unity

Question: Let $w≠1$ be an $n$-th root of unity, i.e., $w^n-1=0$. Show that
$1+2w+3w^2+\dots+nw^{n-1}=-\frac n{1-w}$.
My question is how to relate $w, w^2, \dots,w^{n-1}$ with $w^n$?
Answer: Hint: Let $x=1+2w+3w^2+\cdots +nw^{n-1}$.
Then
$$wx=w+2w^2+3w^3+\cdots +(n-1)w^{n-1}+nw^n.$$
Consider $x-wx$.
Comment: Then it remains to show, and how to show 1+w+w^2+...+w^(n-1)=0?
Comment: $(1+w+\cdots+w^{n-1})(1-w)=1-w^n$.
Answer: $$1+2x+3x^2+\cdots+nx^{n-1}=\frac{x+x^2+x^3+\cdots+x^n}{dx}$$
$$=\frac{d\frac{x(x^n-1)}{x-1}}{dx}$$
$$=x(x^n-1)\left(\frac{-1}{(x-1)^2}\right)+\frac1{x-1}\{(n+1)x^n-1)\}$$
If $x\ne1, x^n=1$  $$1+2x+3x^2+\cdots+nx^{n-1}=\frac n{x-1}$$


Finding the value of $c$ that makes this system of equations have a solution

Question:
Find the value of $c$ that makes the system of equations below have a solution.
  $$\begin{align*}
u + v + 2w &= 2 \\
2u + 3v - w &= 5  \\
3u + 4v + w &= c
\end{align*}$$

I have taken a suggestion from a similar question asked 2 months ago.  After row reduction, I have:
$$\begin{bmatrix}
1 & 1 &  \hphantom{-}2 & 2  \\
0 & 1 & -3 & 1  \\
0 & 0 &  \hphantom{-}1 & (3-c)/2
\end{bmatrix}$$
From here I am confused on how to actually solve for $c$.
Any help would be greatly appreciated!
Comment: Please check your row reduction. I think that the 2nd row should be $0, 1, -5, 1$ (2nd row - twice of 1st row)
Comment: [Please see here](http://meta.math.stackexchange.com/q/5020/264) for how to typeset common math expressions with LaTeX, and [see here](http://meta.stackoverflow.com/editing-help) for how to use Markdown formatting. You can also [take a look here](http://math.stackexchange.com/revisions/3a9cd16b-5e64-473d-9092-a342903c1d7a/view-source) at how I edited your question.
Comment: Yes, Thank you Calvin.
Comment: Once you correct your row reduction (and also remember to check the third row), you will get the answer. You should get $c=6$ as the answer.
Comment: Calvin~ i got c=7.  from the corrections and in the last row reduction that i did:  -1-(6-c)
Comment: @Lanae: $7$ looks great as Steve answered below and he visually saw it - check out his nice answer.
Comment: @Lance Yes, should be 7 (I made a calculation mistake too!). I'm glad that you were able to get it from row reduction.
Answer: Adding the left hand sides of the first two equations gives the left hand side of the third equation, so $c=7$ is the only possibility.
Comment: If i substitute c=7 in the system and solve the system, shouldn't i get right side = left side in the end?
Comment: @Lanea notice the first two equations sum to give you $3u+4v+w=7$ while our third equation is $3u+4v+w=c$. If we want there to be any solution at all it is required that every equation is satisfied and so it follows readily that $c=7$.
Comment: @oldrinb~  I hadn't noticed that!  Thank you!  I'm wondering if the prof wants us to solve for u, v, and w after plugging in c=7.  I tried and it didn't work out.  Most likely because of what you just pointed out.
Comment: @Lanae this system has more than one solution!


How to read data from bluetooth barcode scanner Symbol CS3070 to Android Device

Question: In my project i have to read barcodes using barcode scanner Symbol CS3070 through bluetooth. i.e; i have to establish a connection between android device and barcode scanner through bluetooth. Can any one tell me how to read values from barcode reader and how to setup for communication? I've already read the Bluetooth Developer Guide, and I don't want to use Barcode Reader in Bluetooth Keyboard Emulation (HID) mode (I've some textview that can be filled using soft keyboard and Barcode Reader and I can't control the focus)
I'd use a thread like this to communicate with a reader
<code>    private class BarcodeReaderThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;

    public BarcodeReaderThread(UUID UUID_BLUETOOTH) {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("BarcodeScannerForSGST", UUID_BLUETOOTH);
            /*
             * The UUID is also included in the SDP entry and will be the basis for the connection
             * agreement with the client device. That is, when the client attempts to connect with this device,
             * it will carry a UUID that uniquely identifies the service with which it wants to connect.
             * These UUIDs must match in order for the connection to be accepted (in the next step)
             */
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mmServerSocket.accept();
                try {
                    // If a connection was accepted
                    if (socket != null) {
                        // Do work to manage the connection (in a separate thread)
                        InputStream mmInStream = null;

                        // Get the input and output streams, using temp objects because
                        // member streams are final
                        mmInStream = socket.getInputStream();

                        byte[] buffer = new byte[1024];  // buffer store for the stream
                        int bytes; // bytes returned from read()

                        // Keep listening to the InputStream until an exception occurs
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);
                        if (bytes > 0) {
                            // Send the obtained bytes to the UI activity
                            String readMessage = new String(buffer, 0, bytes);
                            //doMainUIOp(BARCODE_READ, readMessage);
                            if (readMessage.length() > 0 && !etMlfb.isEnabled()) //Se sono nella parte di picking
                                new ServerWorker().execute(new Object[] {LEGGI_SPED, readMessage});
                        }
                        socket.close();
                    }
                }
                catch (Exception ex) { }
            } catch (IOException e) {
                break;
            }
        }
    }

    /**
     * Will cancel the listening socket, and cause the thread to finish
     */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }
}
</code>
Thanks
Comment: I need same functionality in my application, kindly tell me if you find anything helpful related to this task.
Comment: Im also trying to accomplish this, Please let me know if you find a solution. Thank you.
Comment: Hello there! I would like to know if you got to get Bluetooth device reading! I'm on the same problem you mention! @Android84
Comment: Hello @sioesi, yes the solution below solve the problem but it's better to use the barcode scanner in Bluetooth Keyboard Emulation mode
Comment: @Android84 As well? you think we can contact?
Answer: I just received my device and when I paired and connected the device it automatically sends the data to the currently focused EditText. What version of Android are you using because I tried it on ICS and JB and it worked this way.
I have not tested it in any earlier versions.
Edit:
I downgraded my phone to Gingerbread and found out it does not work the same way but I have a solution:
This is important! >> First you must scan the barcode in the manual that says "Serial Port Profile (SPP)".
<code>btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter.isEnabled())
{
    new BluetoothConnect().execute("");
}

public class BluetoothConnect extends AsyncTask<String, String, Void>
{
    public static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";

    @Override
    protected Void doInBackground(String... params)
    {
        String address = DB.GetOption("bluetoothAddress");
        BluetoothDevice device = btAdapter.getRemoteDevice(address);
        try
        {
            socket = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
            btAdapter.cancelDiscovery();
            socket.connect();
            InputStream stream = socket.getInputStream();
            int read = 0;
            byte[] buffer = new byte[128];
            do
            {
                try
                {
                    read = stream.read(buffer);
                    String data = new String(buffer, 0, read);
                    publishProgress(data);
                }
                catch(Exception ex)
                {
                    read = -1;
                }
            }
            while (read > 0);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(String... values)
    {
        if (values[0].equals("\r"))
        {
            addToList(input.getText().toString());
            pickupInput.setText("");
        }
        else input.setText(values[0]);
        super.onProgressUpdate(values);
    }
}
</code>
This is an incomplete version of my working code but you should get the gist.
I hope this solution works for you as well!
Comment: +1 Would you be able to append the complete code? I'm trying to use the same barcode reader in SPP mode.
Comment: The code I provided should suffice, you just need to know the address of the device. You can get it by calling getBondedDevices() after its been paired. Look here for more info: http://developer.android.com/guide/topics/connectivity/bluetooth.html
Comment: When you call the socket = device.createRfcommSocketToServiceRecord(); then socket.connect(); it will attempt to connect to the scanner. Once its connected you create an InputStream with socket.getInputStream();. When you call Stream.read(); it will read wait until the scanner sends data. Once you scan something, it will read the bytes from the stream. Convert the byte array to a string and there's your data! I have noticed sometimes the scanner sends the \r separately so just keep that in mind. Hope that covers the confusion.
Comment: I would definitely not want to connect everytime I want to get data from the scanner. I would just stay connected and either have a "Done" button or like you said close the connection when onPause is called.
Comment: You would just use the TextView.setText() method and just pass it the data that you read from the socket
Comment: Ok, maybe I'm just not getting it, but how do I invoke the reading from the socket? Thanks so far!
Comment: Ok, one more question. Would you connect to the socket once at the start of the activity and only close the connection when onPause is called or would you connect each time I want to use the scanner and close the connection right after that?
Comment: Small question about this code. I know the cs3070 keeps a list of barcodes on the device. Is it possible to retrieve al those barcodes at once using this code? I would like to scan a list on the scanner and then send it to the smartphone.
Comment: I believe when you have the batch mode turned on it just stores each scan in a text file on the device itself. I'm not sure if there's a way to retrieve the list over the bluetooth connection, you'd have to check the documentation. Sorry I can't be of more assistance.
Comment: One query is that is Barcode Scanner Api dependent on Manufacturer OR this code will work with all Bluetooth Supported Barcode Scanner? Any suggestion?
Comment: @SureshSharma I have not tried with any other manufacturer or model. But Im assuming different devices will give similar but possibly different outputs.
Comment: Thanks for the reply. Would you be able to list all near by Bluetooth barcode Scanner Device and Connect with one of them by selection and then communicate barcode with selected one?
Comment: Great example, In addition i want to ask would this code be able to read data from all kind of Barcode Scanner (all brands). I am in the initial phase of developing an application.


How to change the name of the input and output file dynamically in workitem method in design automation api for Revit

Question: I am working on a project where I need to generate output Revit file based on the input json file in the Design automation API for Revit.
Since my input json string was large, I create a json file example "InputFile.json" and upload it to the cloud  and pass the signed url to it to the work item and activity as input parameter, the generated output is a zip file example "OutputFile.zip" which is again uploaded to the cloud using the signed url.
My project works properly using this process. But since the name used for the input and output files are fixed, I am facing issue when I send continuous request, I get mismatched output.

<code>Activity request
..
"parameters": {
      "Inputs": {
        "zip": false,
        "ondemand": false,
        "verb": "get",
        "description": "Element parameters",
        "required": true,
        "localName": "InputFile.json"
      },
      "Result": {
        "zip": true,
        "ondemand": false,
        "verb": "put",
        "description": "new created element",
        "required": true,
        "localName": "OutputFile"
      }
    },
...
</code>
and the WorkItem request
<code>...
"arguments":{
        "Inputs":{
            "url":"https://storage.googleapis.com/XXXXXXX/InputFile.json?XXXXXXXXXXXXXXXsigned-url"
            },

        "Result":{
            "verb":"put",
            "url":"https://storage.googleapis.com/XXXXXXX/OutputFile.zip?XXXXXXXXXXXXXXXsigned-url",
...
</code>
How can I pass dynamically generated names like "InputFile_[DATE].json" and "OutputFile_[DATE].zip"?
Thanks in advance
Regards
Comment: The first idea I can think of is to specify the local name of activity with desired name. But it sounds you want to keep the same definition of Activity, i.e. the local name of Output will be always OutputFile?
Secondly, I might be misunderstanding youe question, but from your code, it looks Google Signed URL service can specify the file name. Is this not useful in your scenario? I am not familiar with signed URL of Google, I can be wrong.
Comment: I was confirmed what Jeremy commented is correct. localName is for any url. localname defined as argument/workitem takes precedence over the one defined as parameter/activity
Answer: You should be able to replace the localName value when submitting the workitem by adding the "localName" attribute to your argument.
Example:
<code>"arguments":{
        "Inputs":{
            "url":"https://storage.googleapis.com/XXXXXXX/InputFile.json?XXXXXXXXXXXXXXXsigned-url"
            },

        "Result":{
            "verb":"put",
            "url":"https://storage.googleapis.com/XXXXXXX/OutputFile.zip?XXXXXXXXXXXXXXXsigned-url",
            "localName": "myOutputFileName"
        }
}

</code>


Choosing best model produced from different algorithms. Metric produced by cross-validation on the train set or metric produced on the test set?

Question: I know that choosing between models produced by one algorithm with different hyperparameters the metric for choosing the best one should be the cross-validation on train set.
But what about choosing between models that are produced by different algorithm? By which metric should I compare them, the metric produced by cross-validation on the train set or metric produced on the test set? Also why?
Answer: No, not on the test set. Model selection is a generalised hyperparameter optimisation and should be done over validation set(s). Imagine all different models embedded in a single model object with the algorithm (and associated hyperparameters) as a hyper parameter.