Como usar o Enum.Parse()?

Question: Meu código exibe erro ao usar o Enum.Parse<enum>(Console.ReadLine());
Estou pedindo para o usuário digitar o nível do cargo ocupado, porem para receber os dados digitados pelo usuário o Parse<> exibe erro, não passa para o Level.
 Classe program

    static void Main(string[] args)
    {
        Console.WriteLine("Enter client data: ");
        Console.Write("Name: ");
        string clientName = Console.ReadLine();
        Console.Write("Email: ");
        string email = Console.ReadLine();
        Console.Write("Birth date (DD/MM/YYYY): ");
        DateTime birthDate = DateTime.Parse(Console.ReadLine());
        Console.WriteLine("Enter order data: ");
        Console.Write("Level: (Junior/MidLevel/Senior) ");
        OrderStatus Level = Enum.Parse<OrderStatus>(Console.ReadLine());

    }

classe Enums

enum OrderStatus : int
{
    Junior = 0,
    MidLevel = 1,
    Senior = 2
}

Erro CS0308 O método não genérico "Enum.Parse(Type, string)" não pode ser usado como argumentos de tipo SalesOrde

https://github.com/thuliomariano/Exercicio
Comment: Erro CS0308 O método não genérico "Enum.Parse(Type, string)" não pode ser usado como argumentos de tipo SalesOrder
Comment: O seu código aqui não tem `SalesOrder`. O código no Github não tem enumeração.
Comment: desculpe, corrigido
Comment: o Enum está dentro do Entitie
Answer: Você não deveria usar o Parse(), isto está explicado em Diferenças entre Parse vs TryParse. Usando o TryParse() ficaria assim e funciona:
using System;
using static System.Console;

public class Program {
    static int Main() {
        WriteLine("Enter client data: ");
        Write("Name: ");
        string clientName = ReadLine();
        Write("Email: ");
        string email = ReadLine();
        Write("Birth date (DD/MM/YYYY): ");
        if (!DateTime.TryParse(ReadLine(), out var birthDate)) return 1;
        WriteLine("Enter order data: ");
        Write("Status: ");
        if (!Enum.TryParse<OrderStatus>(ReadLine(), true, out var status)) return 1;
        return 0;
    }
}
enum OrderStatus {
    Junior = 0,
    MidLevel = 1,
    Senior = 2
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Ainda acho preocupante essa coisa de deixar a pessoa digitar o nível, mas como solução simples até passa se usar o TryParse(), sem ele não pode usar em hipótese alguma, não é robusta.
Comment: Estou estudando enumeradores e quando uso o git clone o código do professor executa normalmente e quando faço o mesmo código exibe erro, segue o git do professor: https://github.com/acenelio/composition1-csharp.  obs:  não consegui fazer da maneira que você mencionou, mesmo com o tryParse o erro persiste
Comment: Eu respondi o que está na pergunta e posso colocar *link* mostrando funcionando. Você está fazendo algum erro que não está na pergunta.
Answer: //class program main ----------------------------------------------

using System;

 namespace Worker
 {
      class Program
      {
          static void Main(string[] args)
          {
               Console.WriteLine("Enter client data: ");
               Console.Write("Name: ");
               string clientName = Console.ReadLine();
               Console.Write("Email: ");
               string email = Console.ReadLine();
               Console.Write("Birth date (DD/MM/YYYY): ");
               DateTime birthDate = DateTime.Parse(Console.ReadLine());
               Console.WriteLine("Enter order data: ");
               Console.Write("Level: (Junior/MidLevel/Senior) ");
               Enum.TryParse(Console.ReadLine(), out OrderStatus level);

          }
      }
 }

 // enums ----------------------------------------------

 namespace Worker.Entities.Enums
 {
     enum OrderStatus : int
     {
          Junior,
          MidLevel,
          Senior
     }
 }

Como usar o Enum.Parse()?


Groups of correlated time series prediction

Question: Consider two group of time series $X$ and $Y$. Both $X$ and $Y$ contain time series $\{x_0,..., x_N\}$ and $\{y_0,..., y_N\}$, respectively. Within each group, the time series are correlated and also there is correlation across the groups so that $(x_i, y_j)$ have non-zero correlation. The times series in $Y$ is sparely populated and $X$ has complete information. How might I design a model to fill in the missing data in $Y$?
Answer: You have a VECTOR ARIMA problem (VARIMA) where you have k1 endogenous series ( the Y series ) and k2 exogenous series ( the X series ) . Identify a useful VARIMA model which book can help me for self-learning VARIMA model? and obtain the fitted values to help you fill in your "missing values"  also see a particular favorite of mine which I have some responsibility for ...  https://www.amazon.co.uk/Time-Series-Analysis-Univariate-Multivariate/dp/0201159112
I would strongly consider an iterative approach .... i.e. a number of passes due to the deleterious effect of lots of 0's to begin with in the Y's


Adding monomials of different degree.

Question: Can you prove that x^m + x^n can never equal x^k, where k is some rational number, and m is not equal to n.
I know we've all been doing it since middle school, but is there a mathematical way of proving it?
Comment: @Joel: You're interpreting it as them never being equal for _all_ $x$, we're interpreting it as never being equal for _any_ $x$. Sidd, can you clarify the intention?
Comment: What happens when you plug in 1 into both equations?
Comment: @omnomnomnom This means that you can't write $x^k$ as $x^m+x^n$, since the two expressions dont agree at $x=1$.
Comment: @Joel nothing of note; $1+1\neq 1$
Comment: @Sidd presumably we are to assume $x \neq 0$.  Any further restrictions?
Comment: @Semiclassical: I mean that there cannot be any continuous interval in which the equality holds.
Comment: What I am looking for is an algebraic proof. For example, right now I was working on linear independence, and was able to prove that the equality holds only when k equals m or n.
Comment: Thanks a lot Semiclassical, Omnomnomnom, Matt B. and Joel. I got my answer. :)
Answer: First, note that there will be trivial solutions; indeed, if $m\leq n$ then there will be $m$ of them. We can eliminate these by dividing out $x^m$, so the only case we really need concern ourselves with is $1+x^n = x^k$.
But this certainly has solutions. For example, $x^2=1+x$ includes the golden ratio $\phi=\frac{1}{2}(1+\sqrt{5})$ as an irrational solution. A better question is what kinds of solutions one gets: must they always be irrational?
Answer: $x=0$ is trivial and works. If $x \not = 0$, necessarily $k>max(n,m)$ so let's suppose $m<n<k$. Then you're trying to solve $x^k - x^n - x^m = 0 \Leftrightarrow x^m(x^{k-m}-x^{n-m}-1)=0 \Leftrightarrow (x^{k-m}-x^{n-m}-1)=0$ which is a perfectly valid expression that has roots and everything depending on the parameters.
Answer: So here's how I did it. I wrote down the equality, and calculated the Wronskian for the expression, assuming x^m, x^n and x^k to be all functions. The Wronskian comes out to be non-zero if k is any value other than either m or n. Hence proving that the three terms are linearly independent, and hence, no equality exists for k not equal to m or n.
Glad to see that there are easier ways as well, and also learnt to watch out for trivial solutions after reading the other responses.

Adding monomials of different degree.


Cant build C project in Eclipse

Question: I want to dump a simple Hello World code in a Cortex M4 microcontroller.(Nuvoton M487KM)
All the tool, board support files and IDE are provided on the website which are installed with the Eclipse IDE (NuEclipse GCC Windows).
After creating a basic Hello world project, I try to build the project but keep getting these errors that wont stop bothering me.
Here is the code: (main.c)
#include <stdio.h>
#include "NuMicro.h"

#define PLL_CLOCK           192000000

void SYS_Init(void)
{
    /*---------------------------------------------------------------------------------------------------------*/
    /* Init System Clock                                                                                */
    /*---------------------------------------------------------------------------------------------------------*/
    /* Unlock protected registers */
    SYS_UnlockReg();

    /* Set XT1_OUT(PF.2) and XT1_IN(PF.3) to input mode */
    PF->MODE &= ~(GPIO_MODE_MODE2_Msk | GPIO_MODE_MODE3_Msk);

    /* Enable External XTAL (4~24 MHz) */
    CLK_EnableXtalRC(CLK_PWRCTL_HXTEN_Msk);

    /* Waiting for 12MHz clock ready */
    CLK_WaitClockReady(CLK_STATUS_HXTSTB_Msk);

    /* Set core clock as PLL_CLOCK from PLL */
    CLK_SetCoreClock(PLL_CLOCK);
    /* Set PCLK0/PCLK1 to HCLK/2 */
    CLK->PCLKDIV = (CLK_PCLKDIV_APB0DIV_DIV2 | CLK_PCLKDIV_APB1DIV_DIV2);

    /* Enable UART clock */
    CLK_EnableModuleClock(UART0_MODULE);

    /* Select UART clock source from HXT */
    CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UART0SEL_HXT, CLK_CLKDIV0_UART0(1));

    /* Update System Core Clock */
    /* User can use SystemCoreClockUpdate() to calculate SystemCoreClock. */
    SystemCoreClockUpdate();

    /* Set GPB multi-function pins for UART0 RXD and TXD */
    SYS->GPB_MFPH &= ~(SYS_GPB_MFPH_PB12MFP_Msk | SYS_GPB_MFPH_PB13MFP_Msk);
    SYS->GPB_MFPH |= (SYS_GPB_MFPH_PB12MFP_UART0_RXD | SYS_GPB_MFPH_PB13MFP_UART0_TXD);
    /* Lock protected registers */
    SYS_LockReg();
}

/*
 * This is a template project for M480 series MCU. Users could based on this project to create their
 * own application without worry about the IAR/Keil project settings.
 *
 * This template application uses external crystal as HCLK source and configures UART0 to print out
 * "Hello World", users may need to do extra system configuration based on their system design.
 */

int main()
{

    SYS_Init();
    /* Init UART to 115200-8n1 for print message */
    UART_Open(UART0, 115200);
    /* Connect UART to PC, and open a terminal tool to receive following message */
    printf("Hello World\n");

    /* Got no where to go, just loop forever */
    while(1);

}

And these are the errors I get:
c:/program files (x86)/gnu arm embedded toolchain/10 2021.10/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/nofp\libc_nano.a(lib_a-closer.o): in function `_close_r':    hellowork           C/C++ Problem
c:/program files (x86)/gnu arm embedded toolchain/10 2021.10/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/nofp\libc_nano.a(lib_a-fstatr.o): in function `_fstat_r':    hellowork           C/C++ Problem
c:/program files (x86)/gnu arm embedded toolchain/10 2021.10/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/nofp\libc_nano.a(lib_a-isattyr.o): in function `_isatty_r':  hellowork           C/C++ Problem
c:/program files (x86)/gnu arm embedded toolchain/10 2021.10/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/nofp\libc_nano.a(lib_a-lseekr.o): in function `_lseek_r':    hellowork           C/C++ Problem
c:/program files (x86)/gnu arm embedded toolchain/10 2021.10/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/nofp\libc_nano.a(lib_a-readr.o): in function `_read_r':  hellowork           C/C++ Problem
c:/program files (x86)/gnu arm embedded toolchain/10 2021.10/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/nofp\libc_nano.a(lib_a-sbrkr.o): in function `_sbrk_r':  hellowork           C/C++ Problem
c:/program files (x86)/gnu arm embedded toolchain/10 2021.10/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/lib/thumb/v7e-m/nofp\libc_nano.a(lib_a-writer.o): in function `_write_r':    hellowork           C/C++ Problem
make: *** [hellowork.elf] Error 1   hellowork           C/C++ Problem
recipe for target 'hellowork.elf' failed    makefile    /hellowork/Debug    line 56 C/C++

Problem
undefined reference to `_close' hellowork       line 0  C/C++ Problem
undefined reference to `_fstat' hellowork       line 0  C/C++ Problem
undefined reference to `_isatty'    hellowork       line 0  C/C++ Problem
undefined reference to `_lseek' hellowork       line 0  C/C++ Problem
undefined reference to `_read'  hellowork       line 0  C/C++ Problem
undefined reference to `_write' hellowork       line 0  C/C++ Problem
undefined reference to `errno'  hellowork       line 0  C/C++ Problem
undefined reference to `errno'  hellowork       line 0, external location: c:\program files (x86)\gnu arm embedded toolchain\10 2021.10\arm-none-eabi\bin\ld.exe: closer.c  C/C++ Problem
undefined reference to `errno'  hellowork       line 0, external location: c:\program files (x86)\gnu arm embedded toolchain\10 2021.10\arm-none-eabi\bin\ld.exe: fstatr.c  C/C++ Problem
undefined reference to `errno'  hellowork       line 0, external location: c:\program files (x86)\gnu arm embedded toolchain\10 2021.10\arm-none-eabi\bin\ld.exe: isattyr.c C/C++ Problem
undefined reference to `errno'  hellowork       line 0, external location: c:\program files (x86)\gnu arm embedded toolchain\10 2021.10\arm-none-eabi\bin\ld.exe: lseekr.c  C/C++ Problem
undefined reference to `errno'  hellowork       line 0, external location: c:\program files (x86)\gnu arm embedded toolchain\10 2021.10\arm-none-eabi\bin\ld.exe: readr.c   C/C++ Problem
undefined reference to `errno'  hellowork       line 0, external location: c:\program files (x86)\gnu arm embedded toolchain\10 2021.10\arm-none-eabi\bin\ld.exe: writer.c  C/C++ Problem

According to the NuEclipse User Manual, we need to set global Toolchain Settings which I did.
The path to Toolchain and Build tools is also mentioned.
Still the code keeps giving me these errors. I read online that it might be the "libc_nano.a" files issue but the those solutions have not helped me.
Can someone please help me!!
Comment: I suggest you try something simpler first and don't start with the very complex file handling. Start with toggling a io, then you may can send single characters. And then you can implement `putchar()` which is needed for `printf()` either by you or by a toolchain / library.
Comment: @12431234123412341234123  `putchar()` will already be implemented in the standard library (though you could override it of course).  What they both ultimately depend on ois `_write_r()` which is what the linker is complaining about.  The linker will continue to complain about that (and other syscalls) so long as they are not provided and the standard library is linked, no matter how simple he makes his code.
Comment: @Clifford I don't know the exact toolchain, all µC which i used `printf()` on (to be fair, i don't use `printf()` a lot on µC`) i had to supply `putchar()`. Anyway, point is that there needs to code that needs to do something with the `char`s he wants to print.
Comment: Why do you want to use `printf()` on a µC? Isn't that a bit overkill? There exist (almost) always a simpler solution than using `printf()`
Comment: @12431234123412341234123 : No, but you do not need to know the toolchain to understand the linker errors.  You can in fact provide a `putchar()` to implement `printf` as an override of the library implementation - it will bypass all the stdio infrastructure supporting redirection, stderr, stdin, and file I/O streams.  But the linker errors will not go away - it will just mean that you might be able use non-working stubs.
Comment: Please open a command line prompt and try to build there, to check where the error comes from. I doubt that it is the IDE. It should be as simple as changing into the project's directory and calling make with the same arguments as the IDE.
Comment: To check whether or not `printf()` was the problem, I wrote a basic addition code. Sadly it failed to build as well.
Answer: It looks like you are using the Newlib C library for which you need to provide the syscalls stubs to couple the library to your hardware/runtime environment.
Many of the stubs only need dummy implementations.  To support printf you need to implement _write_r().  To support a heap (malloc() et al), you need to implement _sbrk_r.
Details of the syscalls that need implementing can be found at https://sourceware.org/newlib/libc.html#Reentrant-Syscalls, along with "minimal" implementation examples at https://sourceware.org/newlib/libc.html#Stubs.  Noting that the re-entrant versions can simply map to (or be implemented in the samr way as) the non-reentrant versions if you are not multi-threading or for very simple implementations.  The _r variants allow for a thread specific errno for example.
You simply need to create a source file with these functions implemented and link them to your project to resolve the links.  It looks like your tool chain already provides for this in these files:
closer.c
fstatr.c
isattyr.c
lseekr.c
readr.c
writer.c

Those are the ones that need modifying, reimplementing or possibly they are ok, but you need to provide the errno support (a global) indicated by the linker error.  In a multi-threaded environment errno needs "switching" per thread (ideally - or just never rely on errno), but otherwise a single global is all that is needed most likely (also as described at https://sourceware.org/newlib/libc.html#Stubs).
Comment: @HarshalChavan Re. _"strongly believe that it was some Toolchain settings problem"_ - then you have understood noting I have said.  The syscalls stubs are necessarily _target specific_ - you have to provide them for your target.  Your "working" project clearly already includes those stubs.  The linker errors are very clear. The project was missing those stubs.  You only posted the error messages, had you posted the complete compile/link log with the command line invitations the precise problem would be evident (and would show all toolchain  "settings" that you think are the problem.
Comment: I got my hands on a pre-tested project file, I imported it in the Eclipse IDE, and it worked!! I just copy pasted this code in that projects main file, and that worked too. I still strongly believe that it was some Toolchain settings problem because it only works if I keep editing that exact file over and over again.

Cant build C project in Eclipse


Erro "Catchable fatal error" PHP

Question: Possuo um campo busca em que posto uma data dinâmica, postando essa data me retorna os registros do banco abaixo, porém travei neste erro que acontece no foreach. Segue código:
DAO:
public function ListaPorTipoB($obj){
    $results = array();
    $stmt = $this->conn->prepare('SELECT * FROM GTCLogist WHERE DsTpVeiculo = \'Bitruck\' AND DtBase = ?');
    $stmt->bindValue(1, $obj->getdata());
        if($stmt) {
            while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
                $prog = new Prog();
                $prog->setid($row->ID);
                $prog->setst($row->DsStatus);
                $prog->setplaca($row->NrPlaca);
                $prog->setmot(stripslashes($row->DsMotorista));
                $prog->setsaida(date('d/m/Y', strtotime($row->DtSaida)));
                $prog->setorig($row->DsOrigem);
                $prog->setdest($row->DsDestino);
                $prog->setprev(date('d/m/Y', strtotime($row->DtPrevChegDest)));
                $prog->setcarga($row->DsCarga);
                $prog->setadfin($row->DsAdFin);
                $prog->setagen($row->DsAgendas);
                $prog->setmal($row->DsMalote);
                $prog->setobs($row->DsObservacao);
                $results[] = $prog;
            }
        }
    return $results;
}

Controller:
class Comando{

  private $conn;

  public function __construct($connec) {
    $this->conn = $connec;
  }

  public function ListaPorTipoB(Prog $obj){
    $dao = new ProgDAO($this->conn);
    return $dao -> ListaPorTipoB($obj);
  }
}

Precontrol:
include_once ('../connection_open.php');

include_once ('../model/prog.php');
include_once ('progControle.php');
include_once ('../DAO/progDAO.php');

$dataPost = $_POST['dataa'];

$objProg = new Prog();
$objProg->setdata($dataPost);

$controller = new Comando($conn);
$controller->ListaPorTipoB($objProg);

header ("location: ../view/programacao.php");

include_once ('../connection_close.php');

Campo busca e abaixo retorna os registros do banco:
<form method="POST" action="../controller/buscaPrecontrole.php">

                <input type="date" id="dataa" name="dataa" value="" required>

                <input type="submit" class="tiny round button" value="Filtrar"/>

                        ST
                        BITRUCK
                        Motorista
                        Data Saída
                        Origem
                        Destino
                        Previsão chegada
                        Carga/Manifesto
                        Adiantamento Fincanceiro
                        Agendas
                        Malotes
                        Observação

                    <?php foreach ($controller->ListaPorTipoB() as $objProg) { ?>

                        <?php echo $objProg->getplaca(); ?>
                        <?php echo $objProg->getmot(); ?>
                        <?php echo $objProg->getsaida(); ?>
                        <?php echo $objProg->getorig(); ?>
                        <?php echo $objProg->getdest(); ?>
                        <?php echo $objProg->getprev(); ?>
                        <?php echo $objProg->getcarga(); ?>
                        <?php echo $objProg->getadfin(); ?>
                        <?php echo $objProg->getagen(); ?>
                        <?php echo $objProg->getmal(); ?>

                    <?php } ?>

  </form>

Catchable fatal error: Argument 1 passed to Comando::ListaPorTipoB() must be an instance of Prog, none given, called in C:\xampp\htdocs\view\programacao.php on line 76 and defined in C:\xampp\htdocs\controller\progControle.php on line 11

Não estou conseguindo resolver este erro, alguma dica ?
Comment: É o mesmo erro da [pergunta passada](http://pt.stackoverflow.com/q/119391/91), vc precisa passar um objeto `Prog` nessa linha `foreach ($controller->ListaPorTipoB() as $objProg`
Comment: Mas ela interessa sim. Preciso dela. Como passo o objeto para a linha que comentou acima ? Pois tentei passar e não funcionou, continua o mesmo erro.
Comment: Só que esta data é dinâmica conforme posto no campo busca encima do `foreach` não posso setar ela manual ai.
Comment: É obrigatório passar a data para `ListaPorTipoB()` ?
Comment: Não, se tiver outro jeito de fazer, com o mesmo fim e for mais viável . E não consegui passar o objeto prog nessa linha acima.
Comment: Se a data não interessa, é so cortar ela fora 1) do SQL. 2) Remover o bind 3) Remover do método `ListaPorTipoB($obj){` no DAO. 4) Remover do méotodo `ListaPorTipoB(Prog $obj){` em Comando.
Comment: Antes do foreach faça `$objProg = new Prog();$objProg->setdata('2016-03-24');`. depois:  `foreach ($controller->ListaPorTipoB($objProg) as $objProg`
Answer: Resolvi o erro modificando alguns códigos abaixo:
View:
<form method="POST" action="../controller/buscaPrecontrole.php">

                <input type="date" id="data" name="data" value="" required>

                <input type="submit" class="tiny round button" value="Filtrar"/>

                        ST
                        BITRUCK
                        Motorista
                        Data Saída
                        Origem
                        Destino
                        Previsão chegada
                        Carga/Manifesto
                        Adiantamento Fincanceiro
                        Agendas
                        Malotes
                        Observação

                    <?php
                    if(isset($_GET['data'])){

                        $dataPost = $_GET['data'];

                        $objProg = new Prog();
                        $objProg->setdata($dataPost);

                    }else{

                        $dataPost = date('Y-m-d');

                        $objProg = new Prog();
                        $objProg->setdata($dataPost);

                    }

                     foreach ($controller->ListaPorTipoB($objProg) as $objProg) { ?>

Precontrol:
$dataPost = $_POST['data'];

$objProg = new Prog();
$objProg->setdata($dataPost);

$controller = new Comando($conn);
$controller->ListaPorTipoB($objProg);

header ("location: ../view/programacao.php?data=".$dataPost."");

Answer: Creio que isso resolva, pois a questão basicamente é que você está chamando um método sem passar valor, na classe é obrigatório passar um valor, para resolver você pode criar um segundo método que faça o mesmo, sem ter passar um objeto, para isso que existem métodos do tipo Set e Get, entretanto, para o exemplo que você está fazendo teria que ser algo similar a isso:
<form method="POST" action="../controller/buscaPrecontrole.php">

                <input type="date" id="dataa" name="dataa" value="" required>

                <input type="submit" class="tiny round button" value="Filtrar"/>

                        ST
                        BITRUCK
                        Motorista
                        Data Saída
                        Origem
                        Destino
                        Previsão chegada
                        Carga/Manifesto
                        Adiantamento Fincanceiro
                        Agendas
                        Malotes
                        Observação

                    <?php
                         if(!$_POST) {
                           $content = null;
                           } else {
                             $obj = new Prog();
                             $type = $obj->setdata($_POST['dataa']);
                             if ($controller instanceof Comando)):
                                $content = $controller->ListaPorTipoB($type);
                             }
                        if (!empty($content)):
                           foreach ($content as $objProg): ?>

                        <?php echo $objProg->getplaca(); ?>
                        <?php echo $objProg->getmot(); ?>
                        <?php echo $objProg->getsaida(); ?>
                        <?php echo $objProg->getorig(); ?>
                        <?php echo $objProg->getdest(); ?>
                        <?php echo $objProg->getprev(); ?>
                        <?php echo $objProg->getcarga(); ?>
                        <?php echo $objProg->getadfin(); ?>
                        <?php echo $objProg->getagen(); ?>
                        <?php echo $objProg->getmal(); ?>

                    <?php endforeach; ?>
                 <?php else:>

                          Sem registros.

                 <?php endif; ?>
               <?php else:>

                          Sem registros.

             <?php endif; ?>

  </form>

veja se ao invés de fazer tudo isso que eu fiz acima, não seria melhor fazer isso:
include_once ('../connection_open.php');

include_once ('../model/prog.php');
include_once ('progControle.php');
include_once ('../DAO/progDAO.php');

$dataPost = $_POST['dataa'];

$objProg = new Prog();
$objProg->setdata($dataPost);

$controller = new Comando($conn);
//atribuindo a saída para uma variável
$data = $controller->ListaPorTipoB($objProg);

include_once ('../connection_close.php');

Na view:
<form method="POST" action="../controller/buscaPrecontrole.php">

                <input type="date" id="dataa" name="dataa" value="" required>

                <input type="submit" class="tiny round button" value="Filtrar"/>

                        ST
                        BITRUCK
                        Motorista
                        Data Saída
                        Origem
                        Destino
                        Previsão chegada
                        Carga/Manifesto
                        Adiantamento Fincanceiro
                        Agendas
                        Malotes
                        Observação

                    <?php foreach ($data as $objProg) { ?>

                        <?php echo $objProg->getplaca(); ?>
                        <?php echo $objProg->getmot(); ?>
                        <?php echo $objProg->getsaida(); ?>
                        <?php echo $objProg->getorig(); ?>
                        <?php echo $objProg->getdest(); ?>
                        <?php echo $objProg->getprev(); ?>
                        <?php echo $objProg->getcarga(); ?>
                        <?php echo $objProg->getadfin(); ?>
                        <?php echo $objProg->getagen(); ?>
                        <?php echo $objProg->getmal(); ?>

                    <?php } ?>

  </form>

Só uma observação, sobre sua classe:
Tome cuidado com métodos recursivos, pois isso pode afetar o desempenho se for mal escrito.
Comment: Me retornou duas mensagens de erro no `foreach` - Notice: Undefined variable: data in line 78 - Warning: Invalid argument supplied for foreach() in on line 78
Comment: Esse erro, indica que a variável `$data` não está  passando nada para o laço foreach... você já deu um `var_dump($controller->ListaPorTipoB($objProg)); die(); ` para ver se existe alguma saída nisso? Lembrando que você está usando método recursivo... veja se isso está correto.
Comment: Aonde eu executo esse `var_dump($controller->ListaPorTipoB($objProg)); die(); ? `

Erro "Catchable fatal error" PHP


instanceof - incompatible conditional operand types

Question: The following compiles fine:
  Object o = new Object();
  System.out.println(o instanceof Cloneable);

But this doesn't:
  String s = new String();
  System.out.println(s instanceof Cloneable);

A compiler error is thrown.
What is the problem?
Comment: if you are using eclipse, take a look at SomeGuys answer.
Answer: A related issue that I have come across recently (and which led me to this page, before I figured out what was going on) is that the Eclipse environment can report "Incompatible conditional operand types" in an 'instanceof' expression erroneously due to a missing 'import' statement for the type on the right of the 'instanceof'. I spent a while trying to figure out how the types in question could possibly be incompatible before figuring out that a missing import was causing the whole problem. Hopefully this information saves somebody some time.
Comment: ECLIPSE USERS READ THIS ANSWER!
Comment: Even with the correct import (either as an `import` declaration or using the full class name) it still happens to me in Eclipse ADT (Android) when I try to do `if (objectInstance instanceof JSONObject)` or `if (objectInstance instanceof JSONArray)`. As mentioned by @polygenelubricants if I try to perform a cast such as `JSONObject jsonObject = (JSONObject)objectInstance;` a compile-time error is shown: _Cannot cast from Object to JSONObject_. If this is a bug in Eclipse, where should I report it (though Google may not be supporting Eclipse anymore)?
Comment: Agreed. I figured this out myself when I tried to set a variable, something like MyType c = (MyType)myString... instead of giving me the expected error, it told me the type MyType was unknown. The fact that this answer got so many more upvotes than the accepted answer shows how pervasive this problem is!
Comment: IMPORTANT - As Some Guy mentioned, the missing import is in the file for the type on the *RIGHT* side of the `instanceof`.
Comment: Does not work for me ! I have the class already in my java file and its still showing the same error
Comment: Thank you very much, this is indeed the problem... I'm so confused why it recognized one fragment, but gave this error to another. Turned out one fragment extended  from `android.app`, while another extended `support.v4.app`, meanwhile the activity where they meet import `support.v4.app`, thus one from `android.app` wasn't recognized
Comment: Note that the import must be the *correct* one if there are multiple classes with the same name on your classpath. I was confused for a few minutes by "foo instanceof Item" when I know that it can be; eventually I realized that Eclipse had added an import statement for "Item" from a package inside a dependent jar, which I hadn't noticed at the time. Corrected the import statement and all was well.
Answer: A more blatant incarnation of your problem is the following:
if ("foo" instanceof Number)
   // "Incompatible conditional operand types String and Number"

This is specified in JLS 15.20.2 Type comparison operator instanceof:

RelationalExpression:
       RelationalExpression instanceof ReferenceType

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

That is, since this cast expression generates a compile time error:
(Number) "foo"

so must this expression:
("foo" instanceof Number)

Your case is a bit more subtle, but the principle is the same:

String is a final class
String does not implement Cloneable
Therefore you can't do (Cloneable) aString
Therefore also you can't do aString instanceof Cloneable
Comment: Just to add to this, if you're missing an import for the type you're trying to use in the `instanceof` expression your IDE may raise this error *instead* of complaining about the missing import.  This can lead to a confusing 'false-positive' kind of issue if you've got a valid class but have forgotten to import it.
Comment: Although this answer is very helpful, it lacks the special case mentioned by SomeGuy below, which was the issue for both me and apparently many others.
Answer: The compiler knows that String is a final class and doesn't implement Cloneable. So no instance of String can ever be an instance of Cloneable. It's stopping you from thinking you've got a meaningful test when actually it will always print "false".
Comment: @MarounMaroun: Bear in mind that if `X` is null, `instanceof` will return `false`... so the only time where it would be relevant would be for non-null constants (which is basically only strings) or `new Foo()` expressions. I think it's reasonable for that not to have a special rule in the language spec.
Comment: Yes, which is why it's odd that `if (s instanceof String)` is fine, since it always returns true...
Comment: Why it allows the opposite? I mean given a class that implements another class, `X instanceof Y` *will* compile even if it's *always* `true`.  Why the inconsistency?
Comment: @JonSkeet I know, but if `X implements Y`, then `x instanceof Y` is *always* true, why it's not a problem for the compiler? (Where it's a problem for it if the result of `instanceof` is always false).
Comment: @MarounMaroun: That doesn't make sense - either `X` is a class, in which case `X instanceof Y` won't compile, or `X` is an expression, in which case (other than for the examples listed above) it might have a value of `null`, in which case the result *isn't* always true. It's not that it's a *problem* for the compiler when it's always false - the compiler is just following the language spec which forbids it.


How to generate absolute URL for breadcrumbs?

Question: I am use Easy Breadcrumb module for a D8 site. I have everything I need with this module as it alters the existing Breadcrumb block, but it outputs relative URLs.
How can I change the relative URLs to absolute?
Current issue (Breadcrumb Output):

    level One

    level two

    level three

Current Level

Expected output:

    level One

    level two

    level three

Current Level

Answer: You can alter the breadcrumbs of other bread crumb builders (core or contrib) in a hook_system_breadcrumb_alter():
/**
 * Implements hook_system_breadcrumb_alter().
 */
function mymodule_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  $links = $breadcrumb->getLinks();
  foreach ($links as $link) {
    $url = $link->getUrl();
    $url->setAbsolute();
  }
}

Comment: I was reviewing url::setOption and stumbled upon url::setAbsolute and couldn't figure out which one is prefered. I understand that setOption takes in two parameters, but setAbsolute also works except it specifically takes 1 parameter and always sets the absolute to True (assuming default is used) or false if that is passed. What would be recommended?
Comment: Both do the same, but since the specific method exists, why not use it? I'll change it in the code.
Comment: I have used the setAbsolute() method. It works in all my test cases.


Carregar arquivo txt através de uma lista c#

Question: Faço uma consulta no banco e coloco em uma lista, depois varro cada item da lista através do foreach para consultar outras tabelas conforme o Id de cada linha percorrida. Se encontrado, gostaria de carregar um arquivo txt para cada linha consultada, saltando dentro do arquivo txt.
EX:

maria  rua 3 cidade Sao paulo
sidnei rua 3 cidade Campinas

O que não consigo fazer é delimitar o comprimento total da linha pois tem que ser fixa. Estou fazendo em C# com StringBuilder:
    Ex:
 StringBuilder sb = new StringBuilder();
    foreach (var item in registros)
    {
        string testeID = Convert.ToString(item.Cells["ID"].Value.ToString());
        string testecodigo = Convert.ToString(item.Cells["CODIGO"].Value.ToString());
    }

  StringBuilder sb = new StringBuilder();
            foreach (var item in registros)
            {
                 areaNaoConstaRecebe = " ";
                folhaRecebe = Convert.ToString(item.Cells["FOLHA"].Value.ToString());
                folhaRecebe = folhaRecebe.PadRight(5, ' ');
                sb.AppendFormat("{0}{1}{2}",
                 idRegistro = "1",
                 numeroControle = "          ",
                 folhaRecebe ="uuuuu",

A primeira consulta salva uma linha da lista, a segunda consulta pode ter 5 linhas e deverão ser populada. Depois a
 terceira por ter 2 linha e devera ser gravado, ai ele colta a lista principal e faz novamente a consulta e assim por diante.
O tamanho seria de 832 colunas.
Comment: Mostre o que fez. E diga onde está tendo dificuldade.
Comment: este é o comando que uso para gravar..Environment.NewLine);
                "File.WriteAllText(@"c:\Clientes_Formatado.txt", sb.ToString())"
Comment: Você quer dizer q cada vez q vc faz uma consulta ele limpar o arquivo e começa de novo? Se não, qual seria o problema q está tendo, não entendi bem.
Comment: O problema é que ao gravar a primeira linha, é gravado tambem a segunda na mesma linha.Fica gravado uma sequencia com os dados do primeiro e do segundo,
Answer: Acrescente um AppendLine no fim
sb.AppendFormat("{0}{1}{2}",
                     idRegistro = "1",
                     numeroControle = "          ",
                     folhaRecebe ="uuuuu")
  .AppendLine();

Comment: @JoeliasAndrade Agradeça votando e aceitando a resposta.
Comment: Que bom Bruno... deu certíssimo. Muito obrigado pela dica....


Unable to correct dependencies Update Debian 6 to 7

Question: I tried updating debian 6 to 7 and getting trouble while running apt-get dist-upgrade.
What I have done is:
edit source.list, changed squeeze to whezzy
# cat /etc/apt/sources.list

deb http://ftp.de.debian.org/debian/ wheezy main contrib non-free
deb-src http://ftp.de.debian.org/debian/ wheezy main contrib non-free

deb http://security.debian.org/ wheezy/updates main contrib non-free
deb-src http://security.debian.org/ wheezy/updates main contrib non-free

deb http://ftp.debian.org/debian/ wheezy-updates main contrib non-free
deb-src http://ftp.debian.org/debian/ wheezy-updates main contrib non-free

running
apt-get update # success
apt-get upgrade # success
apt-get dist-upgrade #failed

Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 foo2zjs : Depends: printer-driver-foo2zjs but it is not installed
 gnome-system-tools : Depends: libpolkit-gobject-1-0 (>= 0.99) but 0.96-4+squeeze2 is installed
                      Recommends: gnome-control-center (>= 1:2.10.1-1) but it is not installed
 grub2-common : Depends: grub-common (= 1.99-27+deb7u2) but 1.98+20100804-14+squeeze1 is installed
 libpolkit-agent-1-0 : Depends: libpolkit-gobject-1-0 (>= 0.105) but 0.96-4+squeeze2 is installed
 libpolkit-backend-1-0 : Depends: libpolkit-gobject-1-0 (>= 0.104) but 0.96-4+squeeze2 is installed
 perl-modules : Depends: perl (>= 5.14.2-1) but 5.10.1-17squeeze6 is installed
 policykit-1 : Depends: libpolkit-gobject-1-0 (>= 0.101) but 0.96-4+squeeze2 is installed
 policykit-1-gnome : Depends: libpolkit-gobject-1-0 (>= 0.99) but 0.96-4+squeeze2 is installed
E: Unmet dependencies. Try using -f

Fixing this with apt-get install -f fails and aptitude safe-upgrade --full-resolver is not able to resolve conflicts.
aptitude safe-upgrade --full-resolver
The following NEW packages will be installed:
  accountsservice{a} acl{a} aptitude-common{a} at-spi2-core{a} colord{a} confget{a} console-setup-linux{ab}
  cpp-4.7{a} crda{a} cryptsetup-bin{a} cups-filters{a} dconf-tools{a} enchant{a} firmware-linux-free{a}
  folks-common{a} fonts-droid{a} fonts-freefont-ttf fuse{a} gconf-service{a} gcr{a} gir1.2-atk-1.0{a}
  gir1.2-clutter-1.0{a} gir1.2-clutter-gst-1.0{a} gir1.2-cogl-1.0{a} gir1.2-coglpango-1.0{a}
  gir1.2-evince-3.0{a} gir1.2-freedesktop{ab} gir1.2-gdkpixbuf-2.0{a} gir1.2-glib-2.0{a}
  gir1.2-gnomebluetooth-1.0{a} gir1.2-gst-plugins-base-0.10{a} gir1.2-gstreamer-0.10{a} gir1.2-gtk-3.0{a}
  gir1.2-gtkclutter-1.0{a} gir1.2-gtksource-3.0{a} gir1.2-json-1.0{a} gir1.2-pango-1.0{a} git-man{a}
  glib-networking{a} glib-networking-common{a} glib-networking-services{a} gnome-desktop3-data{a}
  gnome-icon-theme-symbolic{a} gnome-sushi{a} gnome-themes-standard{a} gnome-themes-standard-data{a}
  grub-pc-bin{a} gsettings-desktop-schemas{a} gstreamer0.10-gconf{a} gstreamer0.10-pulseaudio{a}
  icedtea-6-jre-jamvm{a} imagemagick-common{a} iw{a} kmod{a} krb5-locales{a} libapt-inst1.5{a} libapt-pkg4.12{a}
  libasound2-plugins{a} libasprintf0c2{a} libatkmm-1.6-1{a} libatspi2.0-0{a} libaudiofile1{a} libavcodec53{a}
  libavformat53{a} libavutil51{a} libbind9-80{a} libboost-iostreams1.49.0{a} libboost-program-options1.49.0{a}
  libboost-thread1.49.0{a} libcamel-1.2-33{a} libcap2-bin{a} libchamplain-0.12-0{a} libchamplain-gtk-0.12-0{a}
  libcheese-gtk21{a} libcheese3{a} libclutter-1.0-common{a} libclutter-gst-1.0-0{a} libclutter-gtk-1.0-0{a}
  libclutter-imcontext-0.1-0{a} libclutter-imcontext-0.1-bin{a} libcluttergesture-0.0.2-0{a} libcogl-common{a}
  libcogl-pango0{a} libcogl9{a} libcryptsetup4{a} libcupsfilters1{a} libdevmapper-event1.02.1{a} libdns88{a}
  libdrm-nouveau1a{ab} libebackend-1.2-2{a} libebook-1.2-13{a} libecal-1.2-11{a} libedata-book-1.2-13{a}
  libedata-cal-1.2-15{a} libedataserver-1.2-16{a} libedataserverui-3.0-1{a} libencode-locale-perl{a}
  libept1.4.12{a} libescpr1{a} libevdocument3-4{a} libevent-2.0-5{a} libevview3-3{a} libexiv2-12{a}
  libfile-listing-perl{a} libfolks-eds25{a} libfolks-telepathy25{a} libfolks25{a} libfribidi0{a} libgail-3-0{a}
  libgck-1-0{a} libgconf-2-4{a} libgcr-3-1{a} libgcr-3-common{a} libgdata13{a} libgdiplus{a} libgeocode-glib0{a}
  libgettextpo0{a} libgjs0b{a} libglapi-mesa{a} libglib2.0-bin{a} libgnome-bluetooth10{a}
  libgnome-desktop-3-2{a} libgnome-keyring-common{a} libgnomekbd7{a} libgoa-1.0-0{a} libgoa-1.0-common{a}
  libgs9{a} libgs9-common{a} libgssdp-1.0-3{a} libgstreamer-plugins-bad0.10-0{a} libgtk-3-bin{a}
  libgtkhtml-4.0-0{a} libgtkhtml-4.0-common{a} libgtkhtml-editor-4.0-0{a} libgtksourceview-3.0-0{a}
  libgtksourceview-3.0-common{a} libgupnp-1.0-4{a} libgusb2{a} libgweather-3-0{a} libgxps2{a}
  libhtml-form-perl{a} libhttp-cookies-perl{a} libhttp-daemon-perl{a} libhttp-date-perl{a}
  libhttp-message-perl{a} libhttp-negotiate-perl{a} libio-socket-ip-perl{a} libio-socket-ssl-perl{a} libisc84{a}
  libisccc80{a} libisccfg82{a} libjavascriptcoregtk-1.0-0{a} libjim0debian2{a} libjson0{a} libkmod2{a}
  libkpathsea6{a} liblensfun-data{a} liblensfun0{a} liblockfile-bin{a} liblvm2app2.2{a}
  liblwp-mediatypes-perl{a} liblwp-protocol-https-perl{a} liblwres80{a} libmagick++5{a} libmagickcore5{a}
  libmagickcore5-extra{a} libmagickwand5{a} libmetacity-private0a{ab} libmhash2{a}
  libmission-control-plugins0{a} libmono-cairo4.0-cil{a} libmono-posix4.0-cil{a} libmono-sharpzip4.84-cil{a}
  libmono-system-core4.0-cil{a} libmono-system-drawing4.0-cil{a} libmount1{a} libmozjs185-1.0{a} libmp3lame0{a}
  libmpc2{a} libmtdev1{a} libmusicbrainz5-0{a} libmx-1.0-2{a} libmx-bin{a} libmx-common{a}
  libnautilus-extension1a{ab} libnet-http-perl{a} libnet-ssleay-perl{a} libnetfilter-conntrack3{a}
  libnl-3-200{a} libnl-genl-3-200{a} libnl-route-3-200{a} libnm-glib4{a} libnm-gtk-common{a} libnm-gtk0{a}
  libnm-util2{a} liboauth0{a} libopenal-data{a} libopenal1{a} libopus0{a} libpackagekit-glib2-14{a}
  libpam-cap{a} libpam-modules-bin{a} libperl5.14{a} libpipeline1{a} libpoppler-glib8{a} libpoppler19{a}
  libpostproc52{a} libprocps0{a} libpst4{a} libpython2.7{a} libraptor2-0{a} librasqal3{a} libreadline5{a}
  librest-0.7-0{a} librtmp0{a} libsamplerate0{a} libsane-common{a} libsane-extras-common{a}
  libsemanage-common{a} libsemanage1{a} libsocket-perl{a} libsoundtouch0{a} libspandsp2{a} libssh2-1{a}
  libswscale2{a} libsystemd-daemon0{a} libtelepathy-logger2{a} libtirpc1{a} libtokyocabinet9{a}
  libtracker-sparql-0.14-0{a} libustr-1.0-1{a} libv4lconvert0{a} libva1{a} libvo-aacenc0{a} libvo-amrwbenc0{a}
  libvpx1{a} libvte-2.90-9{a} libvte-2.90-common{a} libwacom-common{a} libwacom2{a} libwebkitgtk-1.0-0{a}
  libwebkitgtk-1.0-common{a} libwebkitgtk-3.0-0{a} libwebkitgtk-3.0-common{a} libwebrtc-audio-processing-0{a}
  libwildmidi-config{a} libwpd-0.9-9{a} libwpg-0.2-2{a} libwww-robotrules-perl{a} libx264-123{a} libxcb-glx0{a}
  libxcb-shape0{a} libxcb-util0{a} libxvidcore4{a} libyajl2{a} libyelp0{a} libzvbi-common{a} libzvbi0{a}
  linux-image-3.2.0-4-amd64{a} linux-image-amd64 mc-data{a} mscompress{a} nsca-client{a} packagekit{a}
  packagekit-backend-aptcc{a} packagekit-tools{a} poppler-data{a} printer-driver-all{a} printer-driver-c2050{a}
  printer-driver-c2esp{a} printer-driver-cjet{a} printer-driver-escpr{a} printer-driver-foo2zjs{a}
  printer-driver-gutenprint{a} printer-driver-hpcups{a} printer-driver-hpijs{a} printer-driver-m2300w{a}
  printer-driver-min12xxw{a} printer-driver-pnm2ppa{a} printer-driver-postscript-hp{a} printer-driver-ptouch{a}
  printer-driver-pxljr{a} printer-driver-sag-gdi{a} printer-driver-splix{a} pulseaudio{a}
  pulseaudio-module-x11{a} pulseaudio-utils{a} python-aptdaemon.pkcompat{ab} python-dbus-dev{a}
  python-debianbts{a} python-defer{a} python-fpconst{a} python-gi{a} python-gobject-2{a} python-packagekit{a}
  python-pycurl{a} python-renderpm{a} python-reportlab{a} python-reportlab-accel{a} python-soappy{a}
  python2.7{a} python2.7-minimal{a} rpcbind{ab} rtkit{a} samba-common{a} samba-common-bin{a} smbclient{a}
  tcl8.5{a} usbutils{a} wireless-regdb{a} xserver-xorg-input-mouse{a} xserver-xorg-input-vmmouse{a} yelp-xsl{a}
  zenity-common{a}
The following packages will be REMOVED:
  cpp-4.4{u} libgweather1{u}
The following packages will be upgraded:
  alsa-base{b} alsa-utils apt apt-utils aptitude aspell base-files bash bind9-host binfmt-support bluez
  bogofilter-bdb browser-plugin-gnash bsdmainutils ca-certificates ca-certificates-java cdrdao cheese-common
  console-setup coreutils cpp cups cups-bsd cups-client cups-driver-gutenprint desktop-file-utils dmsetup
  dnsmasq-base dnsutils docbook-xml dpkg e2fslibs e2fsprogs empathy-common esound-common evolution
  evolution-common evolution-data-server{b} evolution-data-server-common evolution-plugins evolution-webcal
  exim4 exim4-base exim4-daemon-light exiv2 file fontconfig foomatic-db foomatic-db-engine gconf2 gconf2-common
  gdm3 gettext gettext-base ghostscript ghostscript-cups gimp-data git gnash gnash-common gnome-bluetooth
  gnome-desktop-data gnome-doc-utils gnome-icon-theme gnome-keyring{b} gnome-power-manager gnome-session-bin
  gnome-settings-daemon gnome-terminal gnome-terminal-data gnome-user-guide grub-common grub-pc
  gstreamer0.10-ffmpeg gstreamer0.10-plugins-bad gstreamer0.10-plugins-base gstreamer0.10-plugins-good
  gstreamer0.10-plugins-ugly gstreamer0.10-x gtk2-engines hpijs hplip hplip-cups hplip-data hwdata
  icedtea-6-jre-cacao iceweasel ifupdown imagemagick info initramfs-tools initscripts inkscape iproute iptables
  iputils-ping keyboard-configuration klibc-utils less libaa1 libart-2.0-2 libaspell15 libass4 libatasmart4
  libatspi1.0-0 libavahi-client3 libavahi-common3 libavahi-core7 libavahi-glib1 libavc1394-0 libblkid1 libbsd0
  libcaca0 libcairomm-1.0-1 libcanberra-gtk-module libcanberra-gtk0 libclutter-1.0-0 libcomerr2 libcroco3
  libcups2 libcupscgi1 libcupsdriver1 libcupsimage2 libcupsmime1 libcupsppdc1 libcurl3-gnutls libcwidget3
  libdatrie1 libdc1394-22 libdevmapper1.02.1 libdirac-encoder0 libdirectfb-1.2-9 libdjvulibre21 libdrm-intel1
  libdrm-radeon1 libdrm2 libdv4 libdvdnav4 libdvdread4 libedit2 libenchant1c2a libesd0 libevolution libexempi3
  libexif12 libfaad2 libffi5 libfftw3-3 libflac8 libflite1 libfontenc1 libfs6 libgconf2-4 libgcrypt11 libgdbm3
  libgimp2.0 libgl1-mesa-dri libgl1-mesa-glx libglib2.0-cil libglibmm-2.4-1c2a libglu1-mesa
  libgnome-desktop-2-17 libgnome-keyring0 libgnome2-0 libgnome2-common libgnomecanvas2-0 libgnomekbd-common
  libgnomevfs2-0 libgnomevfs2-extra libgpg-error0 libgpgme11 libgpm2 libgsm1 libgssapi-krb5-2 libgssglue1
  libgssrpc4 libgstreamer-plugins-base0.10-0 libgstreamer0.10-0 libgtk2.0-cil libgtk2.0-common libgtkglext1
  libgtkhtml3.14-19 libgtkimageview0 libgtkmm-2.4-1c2a libgudev-1.0-0 libgutenprint2 libhpmud0
  libhtml-parser-perl libice6 libidn11 libieee1284-3 libilmbase6 libjack-jackd2-0 libjasper1 libjpeg62
  libjson-glib-1.0-0 libk5crypto3 libkeyutils1 libklibc libkrb5-3 libkrb5support0 liblcms1 libldap-2.4-2
  liblocale-gettext-perl liblockfile1 liblqr-1-0 liblua5.1-0 libmagic1 libmms0 libmono-addins-gui0.2-cil
  libmono-addins0.2-cil libmpcdec6 libncurses5 libneon27-gnutls libnet-dbus-perl libnetpbm10 libnewt0.52
  libnfsidmap2 libnl1 libnm-glib-vpn1 libopencore-amrnb0 libopencore-amrwb0 libopenjpeg2 liborc-0.4-0
  libpam-ck-connector libpam-modules libpangomm-1.4-1 libpaper1 libparted0debian1 libpcap0.8 libpci3
  libpciaccess0 libpcsclite1 libpng12-0 libpolkit-gobject-1-0{b} libpopt0 libproxy0 libpstoedit0c2a
  libpulse-mainloop-glib0 libpulse0 libraw1394-11 librdf0 librpcsecgss3 libsane libsane-extras libsane-hpaio
  libsasl2-2 libsasl2-modules libschroedinger-1.0-0 libsdl1.2debian{b} libsensors4 libsepol1 libshout3
  libsigc++-2.0-0c2a libslang2 libslv2-9 libsm6 libsmbclient libsndfile1 libsnmp15 libsoup-gnome2.4-1
  libsoup2.4-1 libspectre1 libspeex1 libspeexdsp1 libsqlite3-0 libss2 libstartup-notification0 libsvga1
  libsysfs2 libtag1-vanilla libtag1c2a libtalloc2 libtasn1-3 libtelepathy-glib0 libtext-charwidth-perl
  libtext-iconv-perl libthai0 libtheora0 libts-0.0-0 libunique-1.0-0 libunistring0 libusb-0.1-4 libusb-1.0-0
  libuuid-perl libuuid1 libv4l-0 libvisual-0.4-0 libvisual-0.4-plugins libvte-common libvte9 libwavpack1
  libwbclient0 libwildmidi1 libwmf-bin libwnck22 libwrap0 libwww-perl libx11-data libx11-xcb1 libx86-1
  libxapian22 libxau6 libxaw7 libxcb-dri2-0 libxcb-render0 libxcb1 libxcomposite1 libxcursor1 libxdamage1
  libxdmcp6 libxext6 libxfixes3 libxft2 libxi6 libxinerama1 libxkbfile1 libxml-parser-perl libxmu6 libxmuu1
  libxpm4 libxrandr2 libxrender1 libxres1 libxslt1-dev libxslt1.1 libxt6 libxtst6 libxv1 libxxf86dga1
  libxxf86vm1 libzbar0 linux-image-2.6-amd64 lsb-release man-db mc menu metacity metacity-common min12xxw
  modemmanager module-init-tools mount mousetweaks mutt nano nautilus nautilus-data nautilus-sendto
  nautilus-sendto-empathy ncurses-bin netbase netpbm network-manager network-manager-gnome nfs-common
  notification-daemon nsca ntfs-3g{b} obex-data-server obexd-client openjdk-6-jre-headless openjdk-6-jre-lib
  openssh-client openssh-server openssl passwd pciutils perl perl-base perlmagick pnm2ppa poppler-utils procps
  psmisc python python-apt python-aptdaemon python-chardet python-dbus python-debian python-gobject
  python-imaging python-libxml2 python-lxml python-minimal python-pexpect python-reportbug
  python-software-properties python-xapian python2.6 python2.6-minimal reportbug rsync rsyslog seahorse
  sgml-base sgml-data sysvinit tasksel tcl telepathy-mission-control-5 tmux ttf-freefont udisks ufraw-batch
  update-notifier-common upower usb-modeswitch usb-modeswitch-data util-linux vim vim-common vim-runtime
  vim-tiny w3m wget whiptail wpasupplicant x11-apps x11-utils xml-core xorg xsane xsane-common xserver-xorg
  xserver-xorg-core{b} xserver-xorg-input-all xserver-xorg-input-evdev xserver-xorg-input-synaptics
  xserver-xorg-input-wacom xserver-xorg-video-apm xserver-xorg-video-ark xserver-xorg-video-ati
  xserver-xorg-video-chips xserver-xorg-video-cirrus xserver-xorg-video-fbdev xserver-xorg-video-i128
  xserver-xorg-video-intel xserver-xorg-video-mach64 xserver-xorg-video-mga xserver-xorg-video-neomagic
  xserver-xorg-video-nouveau xserver-xorg-video-openchrome xserver-xorg-video-r128 xserver-xorg-video-radeon
  xserver-xorg-video-rendition xserver-xorg-video-s3 xserver-xorg-video-s3virge xserver-xorg-video-savage
  xserver-xorg-video-siliconmotion xserver-xorg-video-sis xserver-xorg-video-sisusb xserver-xorg-video-tdfx
  xserver-xorg-video-trident xserver-xorg-video-tseng xserver-xorg-video-vesa xserver-xorg-video-vmware
  xserver-xorg-video-voodoo xterm xz-utils yelp zenity
The following partially installed packages will be configured:
  foo2zjs gnome-system-tools grub2-common libmono-corlib2.0-cil libmono-posix2.0-cil libmono-security2.0-cil
  libmono-system-configuration4.0-cil libmono-system-security4.0-cil libmono-system2.0-cil libmono-system4.0-cil
  libpolkit-agent-1-0 libpolkit-backend-1-0 libswitch-perl mono-gac mono-runtime perl-modules policykit-1
  policykit-1-gnome
The following packages are RECOMMENDED but will NOT be installed:
  aptitude-doc-cs aptitude-doc-en aptitude-doc-es aptitude-doc-fi aptitude-doc-fr aptitude-doc-it
  aptitude-doc-ja gimp gnome-control-center gnome-session gnome-session-fallback libatm1
  libparse-debianchangelog-perl lxsession openbox uuid-runtime xfce4-session
463 packages upgraded, 314 newly installed, 2 to remove and 155 not upgraded.
Need to get 505 MB of archives. After unpacking 488 MB will be used.
The following packages have unmet dependencies:
  python-pyorbit: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  python-aptdaemon.pkcompat: Conflicts: packagekit but 0.7.6-3 is to be installed.
  libgnome2-vfs-perl: Depends: perlapi-5.10.0 which is a virtual package.
  libgtkhtml-editor0: Depends: libgtkhtml3.14-19 (< 3.31) but 3.32.2-2.1 is to be installed.
  cheese: Depends: cheese-common (= 2.30.1-2) but 3.4.2-2 is to be installed.
  python-openssl: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  libcairo-perl: Depends: perlapi-5.10.1 which is a virtual package.
  libgtk2-perl: Depends: perlapi-5.10.1 which is a virtual package.
  xserver-xorg-core: Breaks: xserver-xorg-video-6 which is a virtual package.
  libpython2.6: Depends: python2.6 (= 2.6.6-8+deb6u3) but 2.6.8-1.1 is to be installed.
  gir1.2-freedesktop: Conflicts: gir1.0-freedesktop but 0.6.14-1+b1 is installed.
  python-httplib2: Breaks: python (>= 2.7) but 2.7.3-4+deb7u1 is to be installed.
  evolution-exchange: Depends: libgtkhtml3.14-19 (< 3.31) but 3.32.2-2.1 is to be installed.
                      Depends: evolution (< 2.31.0) but 3.4.4-3 is to be installed.
  libpolkit-gobject-1-0: Breaks: libpolkit-gtk-1-0 (< 0.99) but 0.96-3 is installed.
  python-zope.interface: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  python-twisted-conch: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  empathy: Depends: empathy-common (= 2.30.3-1) but 220.127.116.11-2+deb7u1 is to be installed.
  console-setup-linux: Breaks: console-terminus but 4.30-2 is installed.
  gdebi-core: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  python-twisted-web: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  gnome-keyring: Breaks: seahorse-plugins (< 3.0) but 2.30.1-3 is installed.
  libpango-perl: Depends: perlapi-5.10.1 which is a virtual package.
  python-brlapi: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  libsdl1.2debian: Conflicts: libsdl1.2debian-alsa but 1.2.14-6.1 is installed.
  libmetacity-private0a: Breaks: libmetacity-private0 but 1:2.30.1-3 is installed.
  libept1: Depends: libapt-pkg4.10 which is a virtual package.
  python-gtkglext1: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  gconf-defaults-service: Depends: gconf2-common (< 2.29) but 3.2.5-1+build1 is to be installed.
  python-cairo: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  libdrm-nouveau1a: Conflicts: libdrm-nouveau1 but 2.4.21-1~squeeze3 is installed.
  libgnome2-canvas-perl: Depends: perlapi-5.10.0 which is a virtual package.
  aptdaemon: Depends: python-aptdaemon (= 0.31+bzr413-1.1) but 0.45-2 is to be installed.
  python-tagpy: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  xserver-xorg-video-nv: Depends: xorg-video-abi-6.0 which is a virtual package.
  python-twisted-core: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  libglib-perl: Depends: perlapi-5.10.1 which is a virtual package.
  libfont-freetype-perl: Depends: perlapi-5.10.0 which is a virtual package.
  libperl5.10: Depends: perl-base (= 5.10.1-17squeeze6) but 5.14.2-21+deb7u2 is to be installed.
  synaptic: Depends: libapt-inst1.2 which is a virtual package.
            Depends: libapt-pkg4.10 which is a virtual package.
  rpcbind: Conflicts: portmap but 6.0.0-2 is installed.
  alsa-base: Breaks: linux-sound-base but 1.0.23+dfsg-2 is installed.
  python-gst0.10: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  libgnome2-perl: Depends: perlapi-5.10.0 which is a virtual package.
  python-markupsafe: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  evolution-data-server: Breaks: libebook1.2-9 (< 2.32) but 2.30.3-2+squeeze1 is installed.
                         Breaks: libecal1.2-7 (< 2.32) but 2.30.3-2+squeeze1 is installed.
  libmetacity-private0: Depends: metacity-common (< 1:2.31) but 1:2.34.3-4 is to be installed.
  python-pysqlite2: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
  libnautilus-extension1a: Conflicts: libnautilus-extension1 but 2.30.1-2squeeze2 is installed.
  ntfs-3g: Conflicts: libntfs-3g75 but 1:2010.3.6-1 is installed.
  python-gconf: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
                Depends: python2.5-gobject which is a virtual package.
  python-crypto: Depends: python (< 2.7) but 2.7.3-4+deb7u1 is to be installed.
open: 6838; closed: 10653; defer: 22; conflict: 29                                                                  o
No solution found within the allotted time.  Try harder? [Y/n]

Any ideas how to fix this?
Update
# dpkg -C
The following packages have been unpacked but not yet configured.
They must be configured using dpkg --configure or the configure
menu option in dselect for them to work:
 mono-runtime         Mono runtime
 perl-modules         Core Perl modules
 libmono-posix2.0-cil Mono.Posix library (for CLI 2.0)
 libmono-system-configuration4.0-cil Mono System.Configuration library (for CLI
 libswitch-perl       switch statement for Perl
 libpolkit-agent-1-0  PolicyKit Authentication Agent API
 foo2zjs              transitional dummy package for foo2zjs printer driver
 policykit-1-gnome    GNOME authentication agent for PolicyKit-1
 libmono-system4.0-cil Mono System libraries (for CLI 4.0)
 libmono-system-security4.0-cil Mono System.Security library (for CLI 4.0)
 libpolkit-backend-1-0 PolicyKit backend API
 gnome-system-tools   Cross-platform configuration utilities for GNOME
 libmono-security2.0-cil Mono Security library (for CLI 2.0)
 grub2-common         GRand Unified Bootloader (common files for version 2)
 libmono-system2.0-cil Mono System libraries (for CLI 2.0)
 libmono-corlib2.0-cil Mono core library (for CLI 2.0)
 policykit-1          framework for managing administrative policies and privil

The following packages are only half configured, probably due to problems
configuring them the first time.  The configuration should be retried using
dpkg --configure <package> or the configure menu option in dselect:
 mono-gac             Mono GAC tool

Answer:
Between update and dist-upgrade, there is no need to an upgrade, although it shouldn't kill so many things.
You should check with a dpkg -C if every package was installed okay on the system. If not, then you should fix these problems first. I am waiting your dpkg -C output.
In such cases, there are many things which can be done. The first were to simply pick a single package, for example, see the first, the foo2zjs. Insted of a dist-upgrade, now try a simple apt-get install foo2zjs. It will probably answer, that it can't be installed because its dependency, printer-driver-foo2zjs is missing. Then try to install printer-driver-foo2zjs, and you will see, what happens (and I am also very curious :-) ).

There is not really uncommon, that some debian mirror is only synchronized partially, and that can such "not found" and "missing package" like errors cause.
There is another possibility, that your old squeeze wasn't upgraded to the last stable update. It is not really good idea, because the last updates of a debian release targetting mostly exactly the seamless update to the next release, and maybe there are some "hole" in the dependencies if you don't do that.
Anyways, maybe there weren't a bad idea to press "Y" for the "Try harder?" question at the end. It is not a really big problem if some software is maybe deleted, if something is missing, you will be able to reinstall them with some apt-get install commands.
But what the most important thing is: it is not windows. On linux, you can safely remove/reinstall system components, I did already even architectural change with dist-upgrade (i.e. upgrading an i386 to an x86_64), we can even change a debian to an ubuntu with dist-upgrade, the only thing is important: you need to know, how apt works, and be curious (some tricky dpkg --force-all --purge ... can also fix a much).

If your dpkg -C doesn't give you a full clean system, you should first fix that, and not your system upgrade. A dpkg --configure -a retries the configuration of your packages, which will give you interesting error messages, too.
If it also doesn't work, you can do a forced removal of the bad packages with a dpkg --force-all --purge bad_package.
If nothing works to remove a hardly damaged package, as an ultima ratio, you can simply delete its postremoval and preremoval scripts with rm -vf /var/lib/dpkg/info/<badly_damaged_package_name>*rm.
Comment: I mixed it a litte bit up, of couse I did upgrade before update.

I updated my initial post for dpgk -C output

"Try harder" always fails, no solution to do this.
Comment: @Zack I extended my answer. If your dpkg -C isn't clean, first handle this problem and continue your update only after.
Comment: Thanks you! Works after fixing missing things a couple of times.
Comment: @Zack Good :-) You can even dist-upgrade a debian to ubuntu, and vice versa. Since there is support on debian to install packages to alien architectures and run them by the qemu emulator, you can even dist-upgrade a distro to an architecture which isn't supported by your cpu :-)


How can i send local images in a chat by using chat API using PHP

Question: I am trying to send image in whatsApp chat by using Chat API,
by reference:  https://blog.chat-api.com/manuals_and_tutorials/api_whatsapp_send_file_php/
in this case the code is like this:
$data = json_encode(array(
    'chatId'=>$firstname.lastname@example.com',
    'body'=>'URL of the image',
    'filename'=>'picture.jpg',
    'caption'=>'Hey! There is a file!'
));

I am sending chartId,filename and caption from the html form,My html form like this:
<?php
    if(isset($_POST['submit'])){

       $apiURL = 'api.chat-api.com/instanceXXXXX/';
       $token = 'abcdefgABCDEFG';

        $phone = $_POST['phone_no'];
        $file_name = $_POST['file_name'];
        $caption = $_POST['caption'];

   $data = json_encode(array(
    'chatId'=>$email@example.com',
    'body'=>'URL of the image',  //how can i make my local image to this URL
    'filename'=>$file_name,
    'caption'=> $caption
));

     $url = $apiURL.'sendFile?token='.$token;
     $options = stream_context_create(['http' => [
           'method'  => 'POST',
           'header'  => 'Content-type: application/json',
            'content' => $data
        ]
     ]);
     $response = file_get_contents($url,false,$options);
     echo $response; exit;
}
?>

<form action = '' method = ''>
   <input type = "text" name = "phone_no" id = "phone_no" />
    // here local(from my desktop) image is i am displaying
   <input type = "text" name = "file_name" id = "file_name" />
   <input type = "text" name = "caption" id = "caption" />
   <input type = "submit" name = "submit" value =  "Send" />
</form>

Here my problem is how can I send my local image into chat,are we convert our local image to URL . I am not understanding help me on this.
It is appreciate .
Note that URL in $data like this: address of the image(https://test.com/PHP/picture.jpg)
Answer: please convert to base 64,
$photoPath = 'folder/path.jpg';
$getExtension = explode(".",$photoPath);
 $base64 = 'data:image/'.$getExtension[1].';base64,'.file_get_contents($photoPath);
 $data = json_encode(array(
    'chatId'=>$firstname.lastname@example.com',
    'body'=>  $base64,  //how can i make my local image to this URL
    'filename'=>$file_name,
    'caption'=> $caption
));


word_tokenize criando tokens com apenas um caractere em vez de palavras

Question: Quando crio a lista abaixo, com os tokens de múltiplos textos .txt, o for loop tokeniza os caracteres e não as palavras propriamente ditas:
import glob
import nltk

l = []

for file in glob.glob('C:\\Users\\User\\Desktop\\lima\\*.txt'):
    texts = open(file,'r',encoding='utf-8').read()
        for text in texts:
            tokenize = nltk.word_tokenize(text, language='portuguese')
            l.extend(tokenize)

    print(l)

output:
['N', 'ã', 'o', 'f', 'o', 'i', 'o', 'u', 'n', 'ã', 'o', 'é',]
etc

Já tentei com o append, mas ele cria uma lista de listas de caracteres. O que estou fazendo errado?
Comment: @jfaccioni, obrigado pela dica sobre a formatação do texto como um todo.
Answer: read() pega todo o conteúdo do arquivo e retorna em uma única string. Ou seja, texts é uma string.
Ao fazer for text in texts você está percorrendo os caracteres de texts, um a um. Ou seja, a cada iteração do for, a variável text conterá apenas um caractere. Por isso que o word_tokenize acaba gerando tokens com apenas um caractere.
Se a ideia é tokenizar todo o texto, não faça este for, passe toda a string de uma vez:
l = []

for file in glob.glob('C:\\Users\\User\\Desktop\\lima\\*.txt'):
    texts = open(file,'r',encoding='utf-8').read()
    tokenize = nltk.word_tokenize(texts, language='portuguese')
    l.extend(tokenize)

print(l)

Se os arquivos forem muito grandes, não recomendo ler tudo de uma vez com read() (pois aí estará carregando todo o conteúdo para a memória). Uma opção é ler o arquivo linha a linha, e aí sim precisa de um loop:
tokens = []

for file in glob.glob('C:\\Users\\User\\Desktop\\lima\\*.txt'):
    with open(file ,'r',encoding='utf-8') as arq: # abre o arquivo
        for linha in arq: # para cada linha do arquivo
            tokenize = nltk.word_tokenize(linha, language='portuguese')
            tokens.extend(tokenize)

print(tokens)

Repare que é diferente do seu loop: no seu, o for itera em cada caractere da string. No meu, estou iterando por cada linha, e passando toda a linha para word_tokenize.
Também usei with para abrir o arquivo, pois isso garante que ele será fechado ao final (mesmo se der erro durante a leitura). E mudei o nome da lista l para algo um pouco melhor - apesar de parecer besteira, dar nomes melhores ajuda na hora de programar (ainda mais quando esse nome é l, que dependendo da fonte usada, pode ser facilmente confundido com 1, I ou |).
Comment: hkotsubo, muitíssimo obrigado pela gentileza de me explicar. Realmente, agora tudo ficou claro. Mais uma vez, muito obrigado!


Why isn't Babel working on my React Native project?

Question: I used react-native init and have reached a good point with my app, but now it's giving me serious issues with babel out of nowhere.
I got Unexpected use of reserved word 'import' went through steps:
 1. clear watchman watches.
 2. re-yarn all node modules
 3. reset Metro Bundler Cache
 4. Remove haste cache.
I've also deleted my .babelrc file because RN supposedly bundles the correct babel settings.
On Android emulator i get unable to resolve module babel-polyfill.
On Xcode / Simulator i also get unable to resolve module babel-polyfill from project's index.js
At my wit's end here. Tried uninstalling various incarnations of babel.
Versions: RN v0.55.4
i still have pkg json dev dependency of:
"metro-react-native-babel-preset": "^0.50.0"
but i think thats default wrapped in RN so kind of moot.
What am i missing and is there a sane way of setting Babel for RN projects?
Comment: do you have `babel-polyfill` in your dependencies? and installed in your `node_modules`?
Answer: yes it was an import of the babel polyfill, but do you know the explanation to this?
it is because you are writing ES6 code but import hasn't been yet totally added to it so polyfill transforms this to CommonJS, interesting isn't it? in the future it is predicted that you wont need it anymore since it will be implemented 100%
Comment: yeah, very familiar with the concept of babel. But it seems like there's 15 different packages to transpile your ES6, ES7 code now.

Hopefully as JS matures my debugging will get easier :P
Comment: they say webassembly is in line to take over JS in order to save us from pre-compiled hell so who knows if JS will have time to maturate (it possibly will tho)
Answer: Ended up being an import of the babelpolyfill module i'd left uncommented-out in the index.js file.
Totally ditzy by me.


JQuery - Send inputs via ajax (which were obtained by ajax)

Question: I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
        $(document).ajaxComplete(function(){
            $('a.report_video').click(function() {
                var idbutton = $(this).attr('id');
                var idreport = idbutton.replace('report_video_', '');
                //I'm still not using these variables, can they be used to pass the input data to ajax?
                var videourl = $("#video_url_" + idreport).val();
                var videoid = $("#video_id_" + idreport).val();
                var videoserver = $("#server").val();
                ///////////

                $.ajax({
                    type : 'POST',
                    url  : 'https://example.com/script/script.php',
                    data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
                    //For example, data: $("#server").serialize()
                    //Work fine, this input is stored locally.
                    beforeSend: function(){
                        $('#video_report_' + idreport).html('');
                    }
                }).done(function(data) {
                    $('#video_report_' + idreport).html(data);
                });

                return false;
            });

        });

Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),

Comment: `("#foo" + idreport + ",#bar" + idreport)`
Comment: Your problem seems to be related to how you are building `data` for your second ajax request. Without knowing what those elements are, we can't really help all that much. .serialize when called on a form or a collection of input elements works fine, but, we don't know what you're selecting with `$("#video_url_" + idreport)` or if it's even selecting anything.
Comment: Hello Kevin B, I've updated my question.
Comment: AT the point where you're unsure, use the debugging tools available to you to be sure. insert console.logs, add break points, etc. there's no point in being unsure when you can just test it. We unfortunately can't test it.
Comment: Hi @Kevin B, I just found the problem and it is in my syntax, you can see where it is wrong, the problem is in the "data" line, I want to send two input names composed by a prefix and a variable, when I tried to send it by separate worked but when I wanted to do it together, no.
Comment: `$("#foo, #bar").serialize()` jquery selectors work just like css selectors.
Comment: But the ID is composed of a prefix and a numeric variable where "idreport" can be "1, 2, 3". The name would be # foo_1 or # foo_2.
Comment: yeah, that's fine. simple string concatenation.
Comment: Could you give me an example ?. I am not an expert in jquery. I tryed $("#foo" + idreport, "#bar" + idreport).serialize();
Comment: Thanks for the help, they are the kind of thing that happens to an amateur in jquery.
Comment: problem is it's not even jquery, potentially not even javascript. just math
Answer: I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
    $.ajax({
        type: "POST",
        url: 'someURL',
        data: someData
    }).done(function(firstCallData) {
        // This OPTIONAL method fires when the AJAC call succeeded
        // You can also put another AJAX call in here with the data returned from the first call
        $.ajax({
            type: "POST",
            url: 'someURL',
            data: firstCallData
        }).done(function(data) {
            // Do something with second AJAX call with data
        }).fail(function(data) {
            // Second AJAX call failed, handle error
        });
    }).fail(function(data) {
        // This OPTIONAL method fires when the first response failed
    }).always(function(data) {
        // This OPTIONAL method fires regardless if the first call succeeded or failed.
    });
});

Comment: don't use .success. replace it with .done. it doesn't exist in 3.x+
Comment: @KevinB Whoops, I put `.done()` in the first call but mistakenly put `.success()` in the second call. Use `.done()`.
Comment: I also don't think this answer is related to the question. If the question is unclear, request clarification and/or close it as such.


PowerPoint2007 Shape Object On Focus Event and OnFocus out event

Question: I have been searching, on capturing the event or some property that tells that a shape (text Shape Object) is onfocus. as this will help in capturing the keyboard event, so that if the text changes the rectangle width can be increased.
as shown in the link http://s2.postimg.org/scxtx0ec9/Untitled.png
Answer: There aren't any such events.  There's a SelectionChange event that's fired when the current selection changes; you can trap that then test to see what's currently selected (ie, Slides, Shapes, Text, etc) and react accordingly.
But is there some reason why you can't simply set the text container to automatically resize to fit text?  That is, set the shape's .TextFrame.AutoSize property to ppAutoSizeShapeToFitText  (Long = 1)
Comment: If you just notice the image link. there are two shapes
1) a text box and 2) a Rectangle Box. what i need was to increase the width of the rectangle. when the text is added.
Comment: You want the width of the rectangle to change as text is added to the text box, then?  I suspect you'll need to trap the selection change event then.
Comment: yes you are right,  want the width of the rectangle to change as text is added to the text box. I handled it some how. thanks.
Comment: Since StackOverflow is about helping one another solve problems, how about sharing your solution?
Comment: http://stackoverflow.com/questions/22815084/catch-mouse-events-in-powerpoint-designer-through-vsto
Comment: the last link helped me to capture the events


Analyze Packet Loss Bursts

Question: I need to analyze packet loss bursts in TCP streams. Given a number X a packet lost burst is when more then X consecutive packets got lost. So I have a pcap file and need to count how many bursts there were and what was the duration of each.
Tried Tshark but the output is by seconds.
Is there a toll or a script? should I change Tshark code?
Answer: How would you know when a packet is lost? Don't you need to compare two packet captures for that? One at the source and a second capture at the destination? Given two capture files, I can imagine doing a diff between them will result in the lost packets. With line numbers included, it should become rather easy to determine whether or not X consecutive packets were lost.
Comment: tshark/wireshark can calculate loss by counting re-transmissions or duplicate acks. no need to to capture on the source and on the destination. In real life you can capture on the server,  not on the clients.

Analyze Packet Loss Bursts


Change currency code to symbol

Question: I'm translating the Drupal Commerce site into Japanese.
I want to change the currency code JPY to symbol "円".

But keeping rest of the symbols (¥) as it is:

I referred this question and also made changes accordingly. But it didn't help me.
Please guide me.
One more question regarding it, is it possible to use 2 symbols for the same currency? Is there any way to display "円" replacing this "JPY" only? I don't want to use String Overrides.
Edit: It is ok if I completely change the symbol from "¥" to "円". I tried doing this by altering commerce.api.php file, but it didn't reflect anything.
Answer: If it is a form, you can use hook_form_alter along with the PHP function str_replace to replace JPY with 円. Let me know if you need further help.
EDIT:
<code><?php
  function YOURMODULE_form_alter(&$form, &$form_state,$form_id) {
    if ($form_id == 'your_form_id') {
      print str_replace("JPY", "円", render($content));
    }
  ?>
</code>
Comment: Yes, probably it appears in forms as shown in above images. I'll try using that hook. Is it possible to change "¥" to "円" as well? But the symbol placement should be "after".
Comment: Sure, you can do that.
Comment: Can you help me explaining how to do that? So that, now I want to replace JPY with "円" and "¥" with "円".
Comment: I can do that when I get home.
Comment: By the way, it should be str_replace. Sorry for that.
Comment: @Akshay I edited my answer.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/22107/discussion-between-akshay-and-kartagis).
Comment: @Akshay are you there? Have you found a solution yet?
Comment: can we discuss in chat?

Change currency code to symbol


How to fix a not-working key on a Hohner Melodica

Question: Hohner Melodica is a 50s-era keyboard instrument which sounds close to a harmonica and which you play with your mouth. Cool-looking, but the one I got from someone to review has a non-working G#. It's like the note is blocked for some reason, because I can't blow into the unit when I only press that key. It's a very inexpensive instrument and I don't think it can be opened up. Is there a fix, or is it hopeless?
Comment: I'm tempted to suggest holding down the key and sucking on it as hard as you can but I don't want to cause anyone to have foreign objects flying into their lungs.
Answer: You can open up a melodica.  There are screws holding the back on.  Once you're inside the cure may be obvious.
But they're still for sale, and cheap.  So don't waste too much time on it.
http://www.melodicashack.com/melodica-care-and-maintenance
Answer: Open up the Melodica. There should be screws on the back. Once inside you will be able to see the reeds and any obstructions if there are any.
This video is for one of the Yamaha melodicass, so the internals may be different, but it should give you an idea of what you should expect to find inside -


A difficult infinite product

Question: I would ask you for some hints for the calculation of the product
$$\prod_{n=1}^\infty(1-e^{-18 n\pi}).$$
Is it possible to be approached without special functions?
Comment: I do not believe so. That essentially is $\eta(9i)$, see https://en.wikipedia.org/wiki/Dedekind_eta_function
Comment: Related: https://math.stackexchange.com/questions/1334684/what-is-the-exact-value-of-eta6i/1334953#1334953
Comment: I think it is relatable to the Dedekind eta function
Answer: You need to go step by step. Let $$F(q) =\prod_{n=1}^{\infty} (1-q^{2n})\tag{1}$$ where $0<q<1$. Then you wish to seek the value of $F(q^9)$ where $q=e^{-\pi} $. Fortunately Ramanujan gave relations between $F(q), F(q^3)$ and $F(q^9)$ so that $F(q^9)$ can be evaluated in closed form if the value of $F(q) $ is known.
The value of $F(q) $ for $q=e^{-\pi} $ is well known and can be obtained using the link between such functions and elliptic integrals. Thus if $$\eta(q) =q^{1/12}F(q)\tag{2}$$ and $k$ is the elliptic modulus corresponding to nome $q$ and $K$ the corresponding complete elliptic integral then we have $$\eta(q) =2^{-1/3}\sqrt{\frac{2K}{\pi}}(kk')^{1/6}\tag{3}$$ If $q=e^{-\pi} $ then $k=k'=1/\sqrt{2}$ and $K=\Gamma^2(1/4)/4\sqrt{\pi}$ and thus $$\eta(q) =\frac{\Gamma(1/4)}{2\pi^{3/4}}$$ and hence $$F(q) =e^{\pi/12}\cdot \frac{\Gamma(1/4)}{2\pi^{3/4}}\tag{4}$$ If $L, l $ correspond to $q^3$ then we have $$\eta(q^3)=2^{-1/3}\sqrt{\frac{2L}{\pi}}(ll')^{1/6}$$ From this answer the values $L, l, l'$ are known and we have thus $$\eta(q^{3})=\frac{\Gamma(1/4)}{\pi^{3/4}}\frac{\sqrt[4]{3+2\sqrt{3}}\sqrt[3]{2-\sqrt{3}}}{2\sqrt{3}}$$ You should check that the above expression matches with the value given in Wikipedia for $\eta(3i)$ and we thus have $$\eta(q^3)=\frac{\Gamma (1/4)}{2\sqrt[3]{3}\sqrt[12]{3+2\sqrt{3}}\pi^{3/4}}$$ so that $$F(q^3)=e^{\pi/4}\cdot \frac{\Gamma (1/4)}{2\sqrt[3]{3}\sqrt[12]{3+2\sqrt{3}}\pi^{3/4}}$$ Now we need to use Ramanujan's identity $$1+9q^2\cdot\frac{F^3(q^9)}{F^3(q)}=\left(1+27q^2\cdot\frac{F^{12}(q^3)}{F^{12}(q)}\right) ^{1/3}\tag{5}$$ and we can get the value $F(q^9)$ in closed form.
We have $$1+27q^2\frac {F^{12}(q^3)}{F^{12}(q)}=\frac{2\sqrt{3}+6}{9}$$ and hence $$F(q^9)=e^{3\pi/4}\cdot\frac{\sqrt[3]{\sqrt[3]{18+6\sqrt{3}}-3}}{6}\cdot\frac{\Gamma (1/4)}{\pi^{3/4}}$$ Note that the first term of your product is practically equal to $1$ and the above complicated closed form expression is thus approximately equal to $1$. To be more precise equating the above expression with $1$ gives the value of $\Gamma(1/4)$ correct to 23 places of decimals as $$\Gamma(1/4)=3.625609908221908311930686156\dots$$ whereas the correct value is $$\Gamma(1/4)=3.625609908221908311930685155\dots$$
Answer: Not yet a complete answer
$$P=\prod_{n=1}^{\infty}(1-e^{-18\pi n})$$
I don't think it is possible without special functions, but it is worthwhile to recall the definition of the Euler function
$$\phi(q)=\prod_{n=1}^{\infty}(1-q^n)$$
Immediately we recognize the product in question as
$$P=\phi(e^{-18\pi})$$
Which may help, because Ramanujan found that
$$\phi(e^{-\pi})=\frac{e^{\pi/34}}{2^{7/8}}Y$$
$$\phi(e^{-2\pi})=\frac{e^{\pi/12}}{2}Y$$
$$\phi(e^{-4\pi})=\frac{e^{\pi/6}}{2^{11/8}}Y$$
$$\phi(e^{-8\pi})=\frac{e^{\pi/3}}{2^{29/16}}(\sqrt{2}-1)^{1/4}Y$$
Where $$Y=\frac{\Gamma(1/4)}{\pi^{3/4}}$$
There may be a pattern to these closed forms, so there could still be hope...
Also we may see that
$$
\begin{align}
\log P=&\sum_{n=1}^{\infty}\log(1-e^{-18\pi n})\\
=&\sum_{n=1}^{\infty}\log\bigg(\frac{e^{18\pi n}-1}{e^{18\pi n}}\bigg)\\
=&\sum_{n=1}^{\infty}\log(e^{18\pi n}-1)-18\pi n\\
\end{align}
$$
Which may or may not help

A difficult infinite product


Sources for sight-reading exercises that focus on subdivisions (emphasis on drums)

Question: As is the case for all drummers, for me, it's a great fun to find weird rhythmic patterns and to practice over basic beats to create some tension in the straight sections of various songs. However, due to their sick nature it's difficult for me to read these short pieces of tricky beats while playing. If I try to memorize them my trick bag becomes very limited during the heat of the song. Moreover I would like to have access to those things in the rehersals etc.
So I was trying to find ways of shortening my writing or finding better notational shortcuts. After 15 years or so I've re-remembered Steve Vai's Tempo Mental page and it's great to see that it's not aging a bit. No matter what you play, I would really recommend that you digest that short but very rich text.
On that page ( Here is the link ), there is this rare gem

which is mind-boggling at first since the triplets are tied from the middle but after some time you can figure it out (it took some time for me to get it and I still remember after so many years how I did it) that it's actually two triplet beats followed by two eighteenths (which again takes some to time to switch to and from comfortably). So the lengths are 1/12, 1/12, 1/18, 1/18, 1/8,1/8...
So after this, I would like to ask if there are any other sources that can teach more of these notational cleverness or new signs or even some software (similar to Ear Master etc.) that can generate these unconventional shortcuts. I would really appreciate if you can direct me to sources that concentrate on such aspects of notation or sight reading. I've written down many of these for myself but it's always good to seek out for smarter people out there.
The only thing I've managed to find so far is a bunch of software that detach and place orphan triplet beats here and there towards the end of the beat such that you have to keep track of that missing beat over the whole bar.
Don't get me wrong, I'm not one of those if it is difficult it should be better type of people. But experience shows that the better I get at these, the quicker I can switch on polyrhythms, subdivisions etc. so this is for my personal development kit.
I think this is not a duplicate of How To Improve My Sightreading? hence the question but feel-free to mark it CW if this is too broad.
Comment: I hope to write a full reply with an actual answer, but I don't agree with your interpretation of the notation. I think that there are lots of very interesting cases like this but this particular one is actually unnecessarily ambiguous to the performer. Can you "use it in a sentence?" (put it into a full measure of, say, 4/4)? Using elided bracketing like that is something that composers learn to avoid for fear of misinterpretation. We percussionists like it for the challenge. Also, when you explain the values I see 7 notes in the ex. but you only list 6 note values. But cheers overall!
Comment: @jordanconductor Thanks! I'll be waiting for your opinion on this. And you are right I'm missing another 1/18th in that group. But I'll fix it whenever there is an answer to avoid a pointless bump to the main page. But I can indeed use this in a sentence. I can't say for all of them but this particular one has some use cases for me especially when another player is ending their solo part in a fast pace.
Comment: This question has close votes because it asks for resources. As usual, there could be valid related questions, but I choose not to edit because 1) the alteration would be significant, 2) the question "What alternate or shorthand rhythmic notation systems are there" lends itself to list-answers, and 3), should the OP be listening... if we're looking for novel, invented shorthand systems, you'll be best served by inviting your own personal one.
Answer: I would advise you to take a look at konokol, it's a big part of carnatic music, and can be use in ours to comprehend and use rythms more easily. It's very efficient, and frankly, quite simple. Famous drummers but also guitarits such as Mc Laughlin use it.
Comment: Thank you. Unfortunately, I'm already into it and my problem is using a compact notation not coming up with complex polyrhythms.


"eigenfunction" of a transformation

Question: Fourier transform of a gaussian is another gaussian. Fourier/Laplace transforms of $\frac{1}{\sqrt t}$ is something like $\frac{1}{\sqrt \omega}$.
I realize that we can't call these eigenfunctions since the variable is also changed, but is there a special name, are there other interesting stuff to know about these?
Comment: The change of the variable's "name" should be disregarded in this context. While in some physical situations a "transform" may have qualitatively incomparable source and target, the mathematically abstracted question about eigenfunctions effectively ignores those interpretations.
Answer: I'll just add some detail to to Cameron William's answer. Cameron's answer is correct.
The term eigenvector is usually reserved for a linear a operator $A : X\rightarrow X$ on some particular linear space $X$; $x$ is an eigenvector of $A$ if $Ax=\lambda x$ for some scalar $\lambda$. If the linear space consists of functions, then eigenfunction is used interchangeably with eigenvector.
The Fourier transform $\mathscr{F}$ maps $X=L^{2}(\mathbb{R})$ to itself. So it makes sense to talk about eigenfucntions of $\mathscr{F}$ on $L^{2}(\mathbb{R})$. $\mathscr{F}$ is unitary, meaning that (a) $\|\mathscr{F}f\|=\|f\|$ for all $f\in L^{2}$, and (b) $\mathscr{F}$ is surjective. It turns out that $\mathscr{F}$ has an orthonormal basis of eigenfunctions, and the eigenvalues are $1,i,-1,-i$. The normalized eigenfunction are the Hermite functions
$$
         h_{n}(x) = \frac{(-1)^{n}e^{x^{2}/2}}{(2\pi)^{1/4}2^{n/2-1/4}\sqrt{n!}}\frac{d^{n}}{dx^{n}}e^{-x^{2}},\;\;\; n=0,1,2,3,\cdots .
$$
The Hermite functions satisfy
$$
              \mathscr{F} h_{n} = i^{n}h_{n},\;\;\|h_{n}\|_{L^{2}}=1,\;\; n=0,1,2,3,\cdots .
$$
These functions also satisfy the Hermite differential equation
$$
                  -h''+x^{2}h = 0.
$$
This equation is invariant under the Fourier transform.
The Laplace transform of $1/\sqrt{t}$ is
\begin{align}
    \int_{0}^{\infty}\frac{1}{\sqrt{t}}e^{-st}dt
        & = \frac{1}{\sqrt{s}} \int_{0}^{\infty}\frac{1}{\sqrt{st}}e^{-st}d(ts) \\
        & = \frac{1}{\sqrt{s}}\int_{0}^{\infty}\frac{1}{\sqrt{u}}e^{-u}du \\
        & = \Gamma(1/2)\frac{1}{\sqrt{s}} = \sqrt{\pi}\frac{1}{\sqrt{s}}
\end{align}
In this context, it is unusual to think of $1/\sqrt{x}$ as an eigenfunction because it is difficult to formulate the Laplace transform $\mathscr{L}$ in such a way that it maps some space to itself. It is more natural to think of $\mathscr{L} : L^{2}[0,\infty) \rightarrow H^{2}(\Pi_{+})$ where $H^{2}(\Pi_{+})$ is the Hardy space of holomorphic functions on the right half-plane $\Pi_{+}$ with $L^{2}$ boundary values; this correspondence is also unitary from one Hilbert space to a different Hilbert space, but, in this context, eigenfunction doesn't make sense.
Answer: Eigenfunction is exactly the word you're looking for. It does not matter what the "variable" is. The functional form is the important part. Eigenfunctions play an extremely similar role to eigenvectors for matrices. There are marked differences and the biggest issues are the domain/range issues associated to operators on function spaces. The Fourier transform - in its most natural setting - is densely defined on $L^2(\Bbb R)$.
The domain and range of the Laplace transform are not quite as nice as this so the notion of "eigenfunction" is not quite as clear. The functional form of $\frac{1}{\sqrt{t}}$ is preserved under the Laplace transform, but its interpretation in the domain and range are quite different so some might take issue with calling it an eigenfunction. In cases like this, it might be better to say that $\frac{1}{\sqrt{t}}$ is (form) invariant under the Laplace transform.
Answer: Eigenvector/function as vocabulary is somewhat reserved (although not entirely) for linear functions. In the sense that that is the place you'll heat of them most commonly. It certainly wouldn't be wrong here.
The terminology I would use is is that the set of Gaussian functions is invariant under the Fourier transform. That is, call the set of Gausians $U$ and the fourier operator $F$. Then $F(U)\subset U$.
Comment: hear heat, potato, potahto
Answer: That transforms of gaussians are gaussians ( but with other parameters ) is not a pure eigen-relation, but in a more general sense it is. You can block-diagonalize such that the set of gaussian functions are mapped exclusively within the same block. In some sense this is a generalization of the eigenvector concept. If you study more algebra you will be able to specify and quantify such relations more in detail.
Answer: The derivative of sin is cos and cos is -sin (for any particular frequency) so if we make a suitable base change to pairs of such sin and cos will be able to describe this differentiation in block matrix form with for each 2x2 block:
$$\left(\begin{array}{rr}0&1\\-1&0\end{array}\right)$$
This is not a pure "eigen" decomposition, since is not a diagonal matrix, but it is block-diagonal, since there will be 2x2 blocks looking like the above all along the watchtower and nowhere else. For gaussians in fourier transforms there will instead be blocks looking like
$$\left(\begin{array}{rr}0&1\\1&0\end{array}\right)$$

"eigenfunction" of a transformation


How to add confidence intervals to predicted data when the response variable is log transformed

Question: I'm trying to predict the impact of avg grasshopper density(ghavg) on plant biomass. Both the response and predictor are continuous data. I had to log transform biomass (logmass) for a normal distribution, giving the following dataset:
logmass = c(8.032393925,7.439531107,7.307924891,7.036315375,6.679316231,6.545784839,6.414481385,6.39297518,6.209312602,6.209312602,5.698486978,4.862609605,4.367692388,3.608137836)

ghavg = c(30.4,30.4,7.7,124.8,7.7,7.7,123.2,30.4,21.1,21.1,21.1,123.2,47.9,124.8)

In R I ran a glm:
biomass<-glm(logmass~ghavg,data.txt).

To predict the effect of grasshoppers on plant biomass (up to 300 m2) I ran:
nd<-data.frame(ghavg=0:300)
pred_mass<-predict.glm(biomass,type="response",newdata=nd)

Then back transformed the output with:
trans_pred<-(exp(1)^(pred_mass))

I think this works well but I would now like to add confidence intervals to the prediciton. I tried:
pred_massSE<-predict.glm(biomass,type="response",se.fit=TRUE,newdata=nd)

but the standard errors are clearly off when back transformed.
Any assistance on how to properly add CI's to predicted values from transformed data would be greatly appreciated
Answer: @ogrisel: bootstrap seems overkill here! rather:
preds <- predict.glm(biomass,type="response",se.fit=TRUE,newdata=nd)
logci <- preds$fit+(preds$se)%*%t(qnorm(c(0.025,0.5,0.975)))
ci <- exp(logci)
dimnames(ci)[[2]]<-c("lower95", "est", "upper95")

should work (if confidence intervals for predictions are actually what you want)
cheers
Answer: I am not proficient with R but your problem sounds amenable to using the bootstrap method. You can use the boot function of the boot package and take 95-percentiles of the output.
Comment: Actually there is a `ci` method on the resulting boot object: http://www.statmethods.net/advstats/bootstrapping.html


clarification on the concept of Java thread

Question: which is the thread that will begin as soon as the execution of a java program begins?
This was asked in an interview for me.
so can anyone suggest the answer here
Answer: From Thread API document

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class).

And this thread will be called as main thread.
Answer: The thread which is created when you start is called the main thread. It is the one which invokes the main method.
Edit: apparently someone beat me to the answer.
Answer:
The 'main()' method in Java is referred to the thread that is running,
  whenever a Java program runs. It calls the main thread because it is
  the first thread that starts running when a program begins. Other
  threads can be spawned from this main thread. The main thread must be
  the last thread in the program to end. When the main thread stops, the
  program stops running.
Main thread is created automatically, but it can be controlled by the
  program by using a Thread object. The Thread object will hold the
  reference of the main thread with the help of currentThread() method
  of the Thread class.

for more details check this link

'Main' Thread in Java
Comment: Please note that the main thread is not required to quit last. The program stops running when the last non-deamon thread stops, which may, but need not to be the main thread.
Comment: "Main thread...can be controlled by...using a Thread object [...that] will hold the reference of the main thread with the help of currentThread() method of the Thread class."  I think what you are trying to say is that code running in any thread (including the main thread) can get a reference to its own Thread object by calling Thread.currentThread().