问:
DataInputStream for input text files?
I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?</p>

```<code>import java.io.*;
import java.util.*;

class ReadWriteData
{
    public static void main(String[] args) throws Exception
    {

        //create ouput file
        PrintWriter output = new PrintWriter("output2.txt");

        DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
        DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));

        try
        {

        // read data from file
        while (true)
        {
            double number1 = file1.readDouble();
            double number2 = file2.readDouble();
            double result = number1 * number2 ;
            output.println(result);

        }

        }

        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }

        output.close() ;

    }
}
</code>```

答:
The DataInputStream class reads from a binary file (or other source such as socket). This means that it is going to be completely misinterpreting those input text files, with possibly amusing (or very irritating) results. To read numbers from a text file, you should use a BufferedReader wrapping an InputStreamReader to read lines and then convert those to numbers with suitable parsing methods (e.g., Double.parseDouble if you're wanting to produce a floating-point number).

When testing these things, it's often helpful to put in some debugging output inside the loop that prints out each value as you read it. Like that, you can see if things have got stuck in some unexpected way.

Title: DataInputStream for input text files?

Body:
I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?

import java.io.*;
import java.util.*;

class ReadWriteData
{
    public static void main(String[] args) throws Exception
    {

        //create ouput file
        PrintWriter output = new PrintWriter("output2.txt");

        DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
        DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));

        try
        {

        // read data from file
        while (true)
        {
            double number1 = file1.readDouble();
            double number2 = file2.readDouble();
            double result = number1 * number2 ;
            output.println(result);

        }

        }

        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }

        output.close() ;

    }
}


来源: stackexchange

问:
# in URL SAP Gateway SAPUI5
In SAP gateway and SAPUI5, When we has Filter parameter like projectid = "TEST Project #123".

When the request comes to backend service, getting projectid = "TEST Project only not anything after #.

can anyone help to resolve this.

答: I am encoding encodeURIComponent() and sending the url.. Its working now</p>

ContentLicense: CC BY-SA 3.0

Title: # in URL SAP Gateway SAPUI5


问:
Storing state in Elixir
Recently I tackled a problem which involved updating a large number of key values.

Naturally, I considered using a Map, with operations like Map.put/3.

However this seemed insufficient, given the immutable nature of data structures in Elixir:

iex> m = Map.put(%{}, :a, 1)
%{a: 1}
iex> Map.put(m, :b, 2)
%{a: 1, b: 2}
iex> m
%{a: 1}
```

I then solved the problem by holding the state of the Map in a GenServer, and updating it using handle_cast/3 calls.

Generally, is this the right approach, or was this too much here?

答:
Your first approach was right, you just got one thing wrong.

You should rebind the variable when you update the map, like here:

```<code>iex> m = Map.put(%{}, :a, 1)
%{a: 1}
iex> m = Map.put(m, :b, 2)
%{a: 1, b: 2}
iex> m
%{a: 1, b: 2}
</code>```

But you gotta undestand here that it doesn't mutate the variable, it creates a new map and rebinds it to the same variable.

Now, this approach is the most simple one and you'd have to pass this map to every function that uses it. As an alternative, you may consider using the Agent module. All the info what it is and what it is used for can be found in its docs.

Title: Storing state in Elixir

Body:
Recently I tackled a problem which involved updating a large number of key values.

Naturally, I considered using a Map, with operations like Map.put/3.

However this seemed insufficient, given the immutable nature of data structures in Elixir:

iex> m = Map.put(%{}, :a, 1)
%{a: 1}
iex> Map.put(m, :b, 2)
%{a: 1, b: 2}
iex> m
%{a: 1}

I then solved the problem by holding the state of the Map in a GenServer, and updating it using handle_cast/3 calls.

Generally, is this the right approach, or was this too much here?

Body:
Your first approach was right, you just got one thing wrong.

You should rebind the variable when you update the map, like here:

iex> m = Map.put(%{}, :a, 1)
%{a: 1}
iex> m = Map.put(m, :b, 2)
%{a: 1, b: 2}
iex> m
%{a: 1, b: 2}

But you gotta undestand here that it doesn't mutate the variable, it creates a new map and rebinds it to the same variable.

Now, this approach is the most simple one and you'd have to pass this map to every function that uses it. As an alternative, you may consider using the Agent module. All the info what it is and what it is used for can be found in its docs.


问:
How to override BACKOFF_MAX while working with requests retry
I am using requests module with python3 to implement Retry mechanism on failure.

Following is my code-

```<code>session = session or requests.Session()
retry = Retry(
    total=retries,
    read=retries,
    connect=retries,
    backoff_factor=backoff_factor,
    status_forcelist=status_forcelist,
    method_whitelist=method_whitelist)
retry.BACKOFF_MAX = 60
adapter = HTTPAdapter(max_retries=retry)
session.mount(BASE_URL, adapter)
return session
</code>```

I do not see any named argument to set maximum backoff (BACKOFF_MAX in Retry class). I do not want sleep time between retries more than 60 seconds.
How can I achieve it? Resetting BACKOFF_MAX doesn't work

答:
I got this working by overriding get_backoff_time() of Retry class

```<code>class RetryRequest(Retry):

    DEFAULT_METHOD_WHITELIST = frozenset([
    'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])

    def __init__(self, total=10, connect=None, read=None, redirect=None, status=None,
             method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,
             backoff_factor=0, raise_on_redirect=True, raise_on_status=True,
             history=None, respect_retry_after_header=True, max_backoff=60):
        super(RetryRequest, self).__init__(total=total, connect=connect, read=read, redirect=redirect, status=status,
             method_whitelist=method_whitelist, status_forcelist=status_forcelist,
             backoff_factor=backoff_factor, raise_on_redirect=raise_on_redirect, raise_on_status=raise_on_status,
             history=history, respect_retry_after_header=respect_retry_after_header)
        self.backoff_max = max_backoff

    def get_backoff_time(self):
    """ Formula for computing the current backoff
    :rtype: float
    """
        # We want to consider only the last consecutive errors sequence (Ignore redirects).
        consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None,
                                                reversed(self.history))))
        if consecutive_errors_len <= 1:
            return 0

        backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
        return min(self.backoff_max, backoff_value)
</code>```

and using this class instead of Retry

```<code>session = session or requests.Session()
retry = RetryRequest(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
        method_whitelist=method_whitelist,
        max_backoff=max_backoff # in my case 60
)
adapter = HTTPAdapter(max_retries=retry)
session.mount(BASE_URL, adapter)
return session
</code>```

Body:
I am using requests module with python3 to implement Retry mechanism on failure.

Following is my code-

session = session or requests.Session()
retry = Retry(
    total=retries,
    read=retries,
    connect=retries,
    backoff_factor=backoff_factor,
    status_forcelist=status_forcelist,
    method_whitelist=method_whitelist)
retry.BACKOFF_MAX = 60
adapter = HTTPAdapter(max_retries=retry)
session.mount(BASE_URL, adapter)
return session

I do not see any named argument to set maximum backoff (BACKOFF_MAX in Retry class). I do not want sleep time between retries more than 60 seconds.
How can I achieve it? Resetting BACKOFF_MAX doesn't work

Body:
I got this working by overriding get_backoff_time() of Retry class

class RetryRequest(Retry):

    DEFAULT_METHOD_WHITELIST = frozenset([
    'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])

    def __init__(self, total=10, connect=None, read=None, redirect=None, status=None,
             method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,
             backoff_factor=0, raise_on_redirect=True, raise_on_status=True,
             history=None, respect_retry_after_header=True, max_backoff=60):
        super(RetryRequest, self).__init__(total=total, connect=connect, read=read, redirect=redirect, status=status,
             method_whitelist=method_whitelist, status_forcelist=status_forcelist,
             backoff_factor=backoff_factor, raise_on_redirect=raise_on_redirect, raise_on_status=raise_on_status,
             history=history, respect_retry_after_header=respect_retry_after_header)
        self.backoff_max = max_backoff

    def get_backoff_time(self):
    """ Formula for computing the current backoff
    :rtype: float
    """
        # We want to consider only the last consecutive errors sequence (Ignore redirects).
        consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None,
                                                reversed(self.history))))
        if consecutive_errors_len <= 1:
            return 0

        backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
        return min(self.backoff_max, backoff_value)

and using this class instead of Retry

session = session or requests.Session()
retry = RetryRequest(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
        method_whitelist=method_whitelist,
        max_backoff=max_backoff # in my case 60
)
adapter = HTTPAdapter(max_retries=retry)
session.mount(BASE_URL, adapter)
return session


问:
trying to select data in mysql table in between two dates but code showing error
This is my php code which i am using for my requirment guide me the right one pls. Hope this is enough for understand .</p>

```<code><?php
$t1 = $_POST['t1'];
$t2 = $_POST['t2'];
$con=mysqli_connect("localhost","root","agni","gyaninfra");
$s=mysqli_query($con,"select * from shahabad where 'date' between '$t1' and
'$t2';");
echo "<br>";
echo "<table border='2'><tr class='autostyle'><td colspan='4'>SHAHABAD
RESORT ACCOUNT BOOK</td></tr>
  <tr><td>SR.NO.</td><td>Date</td>
  <td>Particulars</td><td>Debit/Credit</td>
  <td>Amount</td><td>Note</td><td>Recipt Image</td></tr>";
while($k=mysqli_fetch_array($s))
{
$a= $k['tr_img'];
echo "<tr><td>".$k['sr_no']."</td><td>".$k['date'].
   "</td><td>".$k['particulars']."</td><td>".$k['transaction'].
   "</td><td>".$k['amount']."</td><td>".$k['note'].
   "</td><td>"."<img height=100 widht=100 src ='$a'>"."</td></tr>";
}
echo "</table>";
?>
</code>```

答:
Change Your code by this. You place Single Quote in table field that is not valid.</p>

```<code><?php
    $t1 = $_POST['t1'];
    $t2 = $_POST['t2'];

    $con=mysqli_connect("localhost","root","agni","gyaninfra");
    $s=mysqli_query($con,"select * from shahabad where `date` between '$t1' and '$t2';");
    echo "<br>";
    echo "<table border='2'><tr class='autostyle'><td colspan='4'>SHAHABAD
    RESORT ACCOUNT BOOK</td></tr>
      <tr><td>SR.NO.</td><td>Date</td>
      <td>Particulars</td><td>Debit/Credit</td>
      <td>Amount</td><td>Note</td><td>Recipt Image</td></tr>";
    while($k=mysqli_fetch_array($s))
    {
    $a= $k['tr_img'];
    echo "<tr><td>".$k['sr_no']."</td><td>".$k['date'].
       "</td><td>".$k['particulars']."</td><td>".$k['transaction'].
       "</td><td>".$k['amount']."</td><td>".$k['note'].
       "</td><td>"."<img height=100 widht=100 src ='$a'>"."</td></tr>";
    }
    echo "</table>";
?>
</code>```

Body:
This is my php code which i am using for my requirment guide me the right one pls. Hope this is enough for understand .

<?php
$t1 = $_POST['t1'];
$t2 = $_POST['t2'];
$con=mysqli_connect("localhost","root","agni","gyaninfra");
$s=mysqli_query($con,"select * from shahabad where 'date' between '$t1' and
'$t2';");
echo "
";
echo "

SHAHABAD
RESORT ACCOUNT BOOK

SR.NO.	Date
  Particulars	Debit/Credit
  Amount	Note	Recipt Image
";
while($k=mysqli_fetch_array($s))
{
$a= $k['tr_img'];
echo "
".$k['sr_no']."	".$k['date'].
   "	".$k['particulars']."	".$k['transaction'].
   "	".$k['amount']."	".$k['note'].
   "	".""."
";
}
echo "
";
?>

Body:
Change Your code by this. You place Single Quote in table field that is not valid.

<?php
    $t1 = $_POST['t1'];
    $t2 = $_POST['t2'];

    $con=mysqli_connect("localhost","root","agni","gyaninfra");
    $s=mysqli_query($con,"select * from shahabad where `date` between '$t1' and '$t2';");
    echo "<br>";
    echo "<table border='2'><tr class='autostyle'><td colspan='4'>SHAHABAD
    RESORT ACCOUNT BOOK</td></tr>
      <tr><td>SR.NO.</td><td>Date</td>
      <td>Particulars</td><td>Debit/Credit</td>
      <td>Amount</td><td>Note</td><td>Recipt Image</td></tr>";
    while($k=mysqli_fetch_array($s))
    {
    $a= $k['tr_img'];
    echo "<tr><td>".$k['sr_no']."</td><td>".$k['date'].
       "</td><td>".$k['particulars']."</td><td>".$k['transaction'].
       "</td><td>".$k['amount']."</td><td>".$k['note'].
       "</td><td>"."<img height=100 widht=100 src ='$a'>"."</td></tr>";
    }
    echo "</table>";
?>


问:
XPath axis, get all following nodes until
I have the following example of HTML:

```<code><!-- lots of html -->
<h2>Foo bar</h2>
<p>lorem</p>
<p>ipsum</p>
<p>etc</p>

<h2>Bar baz</h2>
<p>dum dum dum</p>
<p>poopfiddles</p>
<!-- lots more html ... -->
</code>```

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

答:
In XPath 2.0 (I know this doesn't help you...) the simplest solution is probably

h2[. = 'Foo
  bar']/following-sibling::*  except
   h2[. = 'Bar
  baz']/(.|following-sibling::* )

But like other solutions presented, this is likely (in the absence of an optimizer that recognizes the pattern) to be linear in the number of elements beyond the second h2, whereas you would really like a solution whose performance depends only on the number of elements selected. I've always felt it would be nice to have an until operator:

```<code>h2[. = 'Foo bar']/(following-sibling::* until . = 'Bar baz')
</code>```

In its absence an XSLT or XQuery solution using recursion is likely to perform better when the number of nodes to be selected is small compared with the number of following siblings.

ContentLicense: CC BY-SA 2.5

Body:
I have the following example of HTML:

Foo bar

lorem

ipsum

etc

Bar baz

dum dum dum

poopfiddles

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

Body:
In XPath 2.0 (I know this doesn't help you...) the simplest solution is probably

h2[. = 'Foo
  bar']/following-sibling::*  except
   h2[. = 'Bar
  baz']/(.|following-sibling::* )

But like other solutions presented, this is likely (in the absence of an optimizer that recognizes the pattern) to be linear in the number of elements beyond the second h2, whereas you would really like a solution whose performance depends only on the number of elements selected. I've always felt it would be nice to have an until operator:

h2[. = 'Foo bar']/(following-sibling::* until . = 'Bar baz')

In its absence an XSLT or XQuery solution using recursion is likely to perform better when the number of nodes to be selected is small compared with the number of following siblings.


问:
Opaque struct with C linkage & C++ implementation
Say I want a struct foo with C linkage. I'll declare it in a C-style header file (foo.h) opaquely:

```<code>struct foo;
typedef struct foo foo;
</code>```

But I want to use C++ in the implementation of foo. Say I want foo to contain a std::vector<int>. Since C code wouldn't have access to foo's fields, I don't see why the compiler (or language standards) should prohibit this. But how would I do that? Can I just put extern "C" around the implementation of foo in foo.cc like this?

```<code>extern "C" {
    struct foo {
        ....
        std::vector<int> bar;
    }
}
</code>```

答:
I've ended up stuffing C++ under C a lot...here's the general gist of it.  (And as an aside, letting C++ exceptions unwind the C stack can cause issues for the C code that is unaware such things can happen...so it's advisable to do some catch(...) blocks in the C++ interface functions.)

lib.h: A header file that declares a few functions with C calling convention no matter whether it's compiled as C or C++

```<code>#pragma once

#if defined(__cplusplus)
extern "C" {
#endif

/* Looks like a typical C library interface */

struct c_class;

struct c_class *do_init();
void do_add(struct c_class *tgt, int a);
int  do_get_size(const struct c_class *tgt);
void do_cleanup(struct c_class *tgt);

#if defined(__cplusplus)
}
#endif
</code>```

lib.cpp: A C++ library with a few functions declared with C calling convention

```<code>#include "lib.h"

#include <iostream>
#include <vector>
#include <cstdlib>

class Foo
{
  std::vector<int> m_vec;
public:
  Foo() : m_vec() {}
  virtual ~Foo() {}

  void add(int a) {
    m_vec.push_back(a);
  }

  int getSize() {
    return m_vec.size();
  }
};

/* Exposed C interface with C++ insides */
extern "C" {

  struct c_class
  {
    Foo *guts;
  };

  struct c_class *do_init()
  {
    struct c_class *obj = static_cast<c_class*>(malloc(sizeof(struct c_class)));
    obj->guts = new Foo();
    return obj;
  }

  void do_add(struct c_class *tgt, int a) {
    tgt->guts->add(a);
  }

  int do_get_size(const struct c_class *tgt) {
    return tgt->guts->getSize();
  }

  void do_cleanup(struct c_class *tgt) {
    delete tgt->guts;
    free(tgt);
  }
}
</code>```

main.c: A C program that uses the C calling convention functions exported from lib

```<code>#include <stdio.h>
#include "lib.h"

int main(int argc, char *argv[])
{
  int i;
  struct c_class *obj;

  obj = do_init();

  for(i = 0; i< 100; i++)
  {
    do_add(obj, i);
  }

  printf("Size: %d\n", do_get_size(obj));

  do_cleanup(obj);
}
</code>```

Makefile: a makefile that builds the C as C, and the C++ as C++, then uses the C++ compiler to do the link

```<code>CXXFLAGS ?= -Wall -Werror -pedantic
CFLAGS ?= -Wall -Werror -pedantic

.PHONY: all
all : test

test: lib.o main.o
    $(CXX) $(CXXFLAGS) -o test lib.o main.o

lib.o: lib.cpp lib.h
    $(CXX) $(CXXFLAGS) -c $< -o $@

main.o: main.c lib.h
    $(CC) $(CFLAGS) -c $< -o $@

clean:
    -rm lib.o main.o test
</code>```

Output:

```<code>$ make
g++ -Wall -Werror -pedantic -c lib.cpp -o lib.o
cc -Wall -Werror -pedantic -c main.c -o main.o
g++ -Wall -Werror -pedantic -o test lib.o main.o

$ ./test
Size: 100
</code>```

Body:
Say I want a struct foo with C linkage. I'll declare it in a C-style header file (foo.h) opaquely:

struct foo;
typedef struct foo foo;

But I want to use C++ in the implementation of foo. Say I want foo to contain a std::vector<int>. Since C code wouldn't have access to foo's fields, I don't see why the compiler (or language standards) should prohibit this. But how would I do that? Can I just put extern "C" around the implementation of foo in foo.cc like this?

extern "C" {
    struct foo {
        ....
        std::vector<int> bar;
    }
}

Body:
I've ended up stuffing C++ under C a lot...here's the general gist of it.  (And as an aside, letting C++ exceptions unwind the C stack can cause issues for the C code that is unaware such things can happen...so it's advisable to do some catch(...) blocks in the C++ interface functions.)

lib.h: A header file that declares a few functions with C calling convention no matter whether it's compiled as C or C++

#pragma once

#if defined(__cplusplus)
extern "C" {
#endif

/* Looks like a typical C library interface */

struct c_class;

struct c_class *do_init();
void do_add(struct c_class *tgt, int a);
int  do_get_size(const struct c_class *tgt);
void do_cleanup(struct c_class *tgt);

#if defined(__cplusplus)
}
#endif

lib.cpp: A C++ library with a few functions declared with C calling convention

#include "lib.h"

#include <iostream>
#include <vector>
#include <cstdlib>

class Foo
{
  std::vector<int> m_vec;
public:
  Foo() : m_vec() {}
  virtual ~Foo() {}

  void add(int a) {
    m_vec.push_back(a);
  }

  int getSize() {
    return m_vec.size();
  }
};

/* Exposed C interface with C++ insides */
extern "C" {

  struct c_class
  {
    Foo *guts;
  };

  struct c_class *do_init()
  {
    struct c_class *obj = static_cast<c_class*>(malloc(sizeof(struct c_class)));
    obj->guts = new Foo();
    return obj;
  }

  void do_add(struct c_class *tgt, int a) {
    tgt->guts->add(a);
  }

  int do_get_size(const struct c_class *tgt) {
    return tgt->guts->getSize();
  }

  void do_cleanup(struct c_class *tgt) {
    delete tgt->guts;
    free(tgt);
  }
}

main.c: A C program that uses the C calling convention functions exported from lib

#include <stdio.h>
#include "lib.h"

int main(int argc, char *argv[])
{
  int i;
  struct c_class *obj;

  obj = do_init();

  for(i = 0; i< 100; i++)
  {
    do_add(obj, i);
  }

  printf("Size: %d\n", do_get_size(obj));

  do_cleanup(obj);
}

Makefile: a makefile that builds the C as C, and the C++ as C++, then uses the C++ compiler to do the link

CXXFLAGS ?= -Wall -Werror -pedantic
CFLAGS ?= -Wall -Werror -pedantic

.PHONY: all
all : test

test: lib.o main.o
    $(CXX) $(CXXFLAGS) -o test lib.o main.o

lib.o: lib.cpp lib.h
    $(CXX) $(CXXFLAGS) -c $< -o $@

main.o: main.c lib.h
    $(CC) $(CFLAGS) -c $< -o $@

clean:
    -rm lib.o main.o test

Output:

$ make
g++ -Wall -Werror -pedantic -c lib.cpp -o lib.o
cc -Wall -Werror -pedantic -c main.c -o main.o
g++ -Wall -Werror -pedantic -o test lib.o main.o

$ ./test
Size: 100


问:
Concat creates a still image before the video
I am creating a cutlist like this

```<code>file 't1.MP4'
inpoint 1.45067
outpoint 3.18133
file 't2.MP4'
inpoint 3.45067
outpoint 6.18133
...
</code>```

and I use it like this

```<code>ffmpeg -y -f concat -safe 0 -i list.txt -c:v libx264 -c:a aac -af aresample=async=1 -pix_fmt yuv420p output.mp4
</code>```

The output almost always contains a still image at the start, sometimes half the video time, sometimes less, showing the first frame then the final video starts. I noticed, the less inpoint and outpoint are apart, the longer the still image at the start. Maybe its also connected to the amount of inpoint and outpoint.

How do I solve this?

答:
The concat demuxer is outputting more packets than that specified in the ranges, since video will need earlier frames to decode.

Try

```<code>ffmpeg -y -f concat -safe 0 -copyts -segment_time_metadata 1 -i list.txt -vf select=concatdec_select,setpts=N/FRAME_RATE/TB,format=yuv420p -c:v libx264 -af aselect=concatdec_select,asetpts=N/SR/TB -c:a aac output.mp4
</code>```

I assume all files have videos and audios with same properties i.e. framerate, resolution, audio sampling rate, channels..etc

Body:
I am creating a cutlist like this

file 't1.MP4'
inpoint 1.45067
outpoint 3.18133
file 't2.MP4'
inpoint 3.45067
outpoint 6.18133
...

and I use it like this

ffmpeg -y -f concat -safe 0 -i list.txt -c:v libx264 -c:a aac -af aresample=async=1 -pix_fmt yuv420p output.mp4

The output almost always contains a still image at the start, sometimes half the video time, sometimes less, showing the first frame then the final video starts. I noticed, the less inpoint and outpoint are apart, the longer the still image at the start. Maybe its also connected to the amount of inpoint and outpoint.

How do I solve this?

Body:
The concat demuxer is outputting more packets than that specified in the ranges, since video will need earlier frames to decode.

Try

ffmpeg -y -f concat -safe 0 -copyts -segment_time_metadata 1 -i list.txt -vf select=concatdec_select,setpts=N/FRAME_RATE/TB,format=yuv420p -c:v libx264 -af aselect=concatdec_select,asetpts=N/SR/TB -c:a aac output.mp4

I assume all files have videos and audios with same properties i.e. framerate, resolution, audio sampling rate, channels..etc


问:
How to remove all numbers from a file name or a string - Python3
I have a Python script that will walk through all of the directories within the Test Folder(in this case) and will remove all numbers at the beginning of each of the file names. So my question is how would I modify my script in order to remove numbers from the whole file name? Not just the beginning or the end of it.

Thanks,
Alex

import os

for root, dirs, files in os.walk("Test Folder", topdown=True):
    for name in files:
        if (name.startswith("01") or name.startswith("02") or name.startswith("03") or name.startswith("04") or name.startswith("04") or name.startswith("05") or name.startswith("06") or name.startswith("07") or name.startswith("08") or name.startswith("09") or name[0].isdigit()):
            old_filepath = (os.path.join(root, name))
            _, new_filename = name.split(" ", maxsplit=1)
            new_filepath = (os.path.join(root, new_filename))
            os.rename(old_filepath, new_filepath)
```

答:
```<code>import os

def rename_files():
    # Get files names from the directory
    files_names = os.listdir(" file r directory path")

    saved_dir = os.chdir(files_name)

    # To get cutrrent working directiry name
     print os.getcwd() # This is to verify whether you are in correct path

    for file_name in files_names:
        os.rename(file_name,file_name.translate(None,'0123456789'))
        # Above translate function remove all the number from file name
rename_files()
</code>```


问:
Rspec command to skip view specs
When we rspec command it runs all of the specs. I do not want to run view specs.

Is there way to disable/skip view specs??

Other than making those specs pending..

答:
You should try something like this -

Use an --exclude-pattern

```<code>rspec --exclude-pattern "spec/views/**/*_spec.rb"
</code>```

https://www.relishapp.com/rspec/rspec-core/v/3-3/docs/configuration/exclude-pattern

Title: Rspec command to skip view specs

Body:
You should try something like this -

Use an --exclude-pattern

rspec --exclude-pattern "spec/views/**/*_spec.rb"

https://www.relishapp.com/rspec/rspec-core/v/3-3/docs/configuration/exclude-pattern


问:
Awk: understanding how comments are removed in php
Apologies in advance for a rather simplistic question.

In a big pile of "note to self", I have this little awk one-liner that works perfectly for my needs, which is to remove comments from a php file. But I would like to better understand it:

awk '/^\/\*/{c++} c!=1; /^ \*\//{c++}'

I cannot, unfortunately, find the original post in order to better understand how it works.

Googling it turns up a ton of things on c++ but not the original post. Neither Explain Shell nor Symbol Hound has helped.

I don't particularly stumped by the {c++} c!=1; bit. Any help would be greatly appreciated.

答:
I have tested your awk script and it does not work properly!!!
You should use the following one to remove :

```<code> gawk '/^\/\*/{c++} c!=1; /^.*\*\//{c=0}' php_file
</code>```

to remove /* comments */ multi-lines comments or single lines with only /* comments */!!!

TESTED on:

In a nutshell,

awk will read the input file line by line and will do its default action: printing

when the condition /^\/\*/ is met ( /* comment that is directly located at the start of the line) the block {c++} will be executed!, in awk variable are by default initiated to 0, so after the block c=1 and c!=1 will be false so nothing will be printed.

as long as we are in the comment section c!=1 will be false so nothing will be printed.

then we reach the last line of comment and c is set back to 0, so from the following line everything will be printed again.

REMARK:

lines with commands followed /* */  are still printed as-is

// comments are not removed

If there are some super important commands on the same line directly following a comment block they will be lost!!!

```<code>/* comment starts
/* still some comments
end of comments */some super important commands;
</code>```

IMPROVEMENT:

change c=!1 by c<1 to improve the stability of the script, with c!=1 your script will stop functioning properly in the case:

```<code>/* comment starts
/* still some comments
end of comments */
</code>```

Body:
I have tested your awk script and it does not work properly!!!
You should use the following one to remove :

 gawk '/^\/\*/{c++} c!=1; /^.*\*\//{c=0}' php_file

to remove /* comments */ multi-lines comments or single lines with only /* comments */!!!

TESTED on:

In a nutshell,

awk will read the input file line by line and will do its default action: printing

when the condition /^\/\*/ is met ( /* comment that is directly located at the start of the line) the block {c++} will be executed!, in awk variable are by default initiated to 0, so after the block c=1 and c!=1 will be false so nothing will be printed.

as long as we are in the comment section c!=1 will be false so nothing will be printed.

then we reach the last line of comment and c is set back to 0, so from the following line everything will be printed again.

REMARK:

lines with commands followed /* */  are still printed as-is

// comments are not removed

If there are some super important commands on the same line directly following a comment block they will be lost!!!

/* comment starts
/* still some comments
end of comments */some super important commands;

IMPROVEMENT:

change c=!1 by c<1 to improve the stability of the script, with c!=1 your script will stop functioning properly in the case:

/* comment starts
/* still some comments
end of comments */


问:
Hiding text in a button
I have a certain set of buttons registered so that they can be executed using letters in a keyboard or by mouse click. But I want to hide the text in the button from the user so that it looks more natural.

Heres part of the code:

```<code>ToggleButton btn1 = new ToggleButton("");
btn1.setMnemonicParsing(true); // instruction to parse mnemonic
btn1.setText("_7");
</code>```

Now instead of the button showing a 7 in the middle I want it to be hidden but still function the same. I have a feeling it has something to do with the setVisible() method but I'm not sure how to use it for just the text inside the button instead of the entire button itself.

答:
Most probably you can't do both at the same time. If you want to trigger the button using MneomonicParsing, then you have set the text and it will be visible in the button.

Why don't you use a onKeyPressed method of the container of those buttons instead? Then you don't have to set any text on the button. Like this:

```<code>container.setOnKeyPressed(k->{
    switch(k.getCode()){
        case NUMPAD7:
        case DIGIT7: btn1.fire();
            break;
        //implement other cases
    }
});
</code>```

Title: Hiding text in a button

Body:
I have a certain set of buttons registered so that they can be executed using letters in a keyboard or by mouse click. But I want to hide the text in the button from the user so that it looks more natural.

Heres part of the code:

ToggleButton btn1 = new ToggleButton("");
btn1.setMnemonicParsing(true); // instruction to parse mnemonic
btn1.setText("_7");

Now instead of the button showing a 7 in the middle I want it to be hidden but still function the same. I have a feeling it has something to do with the setVisible() method but I'm not sure how to use it for just the text inside the button instead of the entire button itself.

Body:
Most probably you can't do both at the same time. If you want to trigger the button using MneomonicParsing, then you have set the text and it will be visible in the button.

Why don't you use a onKeyPressed method of the container of those buttons instead? Then you don't have to set any text on the button. Like this:

container.setOnKeyPressed(k->{
    switch(k.getCode()){
        case NUMPAD7:
        case DIGIT7: btn1.fire();
            break;
        //implement other cases
    }
});


问:
How would I calculate the standard deviation from a file of floating point numbers?
I'm trying to write a Java program to calculate the maximum, minimum, mean and standard deviation after reading a text file full of floating point numbers. As you can see, I've calculated the max, min, mean, but for the standard deviation, I'm confused. Any ideas how I should implement this?

Also, I'm fairly new to programming, so sorry if things aren't structured correctly.

Here's my code:

```<code>/*
 * Create a Java program to read a file of floating point numbers and compute
 * the following statistics from the data file:
 *
 * 1. Maximum
 * 2. Minimum
 * 3. Arithmetic Average (Mean)
 * 4. Standard Deviation
 *
 * Do not assume anything about the large numbers in the file. They could be
 * positive or negative, and their magnitude could be extremely large or
 * extremely small.
 */

import java.io.*;
import java.util.Scanner;

public class DataFile {

public static void main(String[] args) {
    // declare variables
    double number, maximum, minimum, sum, mean, standardDeviation;
    int count;

    Scanner file = null;

/* -------------------------------------------------------------------------- */
    try {
        file = new Scanner(new File("RawData.txt"));
    }

    catch(FileNotFoundException e) {
        System.out.print("Error; The program was terminated!");
        System.exit(1);
    }

/* -------------------------------------------------------------------------- */
    // initialize variables
    maximum = file.nextDouble();
    minimum = maximum;
    sum = 0;
    count = 1;

    while(file.hasNextDouble()) {
        number = file.nextDouble();

        if(number > maximum)
            maximum = number;

        else if(number < minimum)
            minimum = number;

        sum += number;
        count += 1;

    } // end while loop

    file.close();

/* -------------------------------------------------------------------------- */
    // mean calculation
    mean = sum / count;

    // standard deviation calculation
    // .....

    // display statistics
    System.out.println("Maximum ------------> " + maximum                   );
    System.out.println("Minimum ------------> " + minimum                   );
    System.out.println("Sum ----------------> " + sum                       );
    System.out.println("Count --------------> " + count                     );
    System.out.println("Mean ---------------> " + mean                      );

} // end method main

} // end class DataFile
</code>```

答:
As suggested by Przemysław MoskalI, I believe something like this is what you are after! Lists are incredibly useful in Java. This was done very quickly, so make sure you are happy with the final calcs! Happy Programming!

Edited - used computational formula thanks to a suggestion from Bathsheba, which allows you to not make use of a list at all (which is more memory efficient).

See this website for an easy way to understand the calculation:
https://www.mathsisfun.com/data/standard-deviation-formulas.html

```<code>// initialize variables
maximum = file.nextDouble();
minimum = maximum;
sum = 0;
count = 1;
double computationalSum = 0;
double squareSum = 0;

while(file.hasNextDouble()) {
    number = file.nextDouble();

    squareSum += Math.pow(number, 2);
    computationalSum += number;

    if(number > maximum)
        maximum = number;

    else if(number < minimum)
        minimum = number;

    sum += number;
    count += 1;

} // end while loop

file.close();

/* ------------------------------------------------------------------------*/
// mean calculation
mean = sum / count;
double stdDevSum = 0;
double stdDevMean = 0;
double stdDev = 0;

double sumOfSquares = squareSum - ((Math.pow(computationalSum, 2)/(count-1)));
double sSquared = sumOfSquares/(count-1);
double otherStdDev = Math.sqrt(sSquared);

// display statistics
System.out.println("Maximum ------------> " + maximum                   );
System.out.println("Minimum ------------> " + minimum                   );
System.out.println("Sum ----------------> " + sum                       );
System.out.println("Count --------------> " + count                     );
System.out.println("Mean ---------------> " + mean                      );
System.out.println("StdDev -------------> " + otherStdDev);

} // end method main
</code>```

Body:
I'm trying to write a Java program to calculate the maximum, minimum, mean and standard deviation after reading a text file full of floating point numbers. As you can see, I've calculated the max, min, mean, but for the standard deviation, I'm confused. Any ideas how I should implement this?

Also, I'm fairly new to programming, so sorry if things aren't structured correctly.

Here's my code:

/*
 * Create a Java program to read a file of floating point numbers and compute
 * the following statistics from the data file:
 *
 * 1. Maximum
 * 2. Minimum
 * 3. Arithmetic Average (Mean)
 * 4. Standard Deviation
 *
 * Do not assume anything about the large numbers in the file. They could be
 * positive or negative, and their magnitude could be extremely large or
 * extremely small.
 */

import java.io.*;
import java.util.Scanner;

public class DataFile {

public static void main(String[] args) {
    // declare variables
    double number, maximum, minimum, sum, mean, standardDeviation;
    int count;

    Scanner file = null;

/* -------------------------------------------------------------------------- */
    try {
        file = new Scanner(new File("RawData.txt"));
    }

    catch(FileNotFoundException e) {
        System.out.print("Error; The program was terminated!");
        System.exit(1);
    }

/* -------------------------------------------------------------------------- */
    // initialize variables
    maximum = file.nextDouble();
    minimum = maximum;
    sum = 0;
    count = 1;

    while(file.hasNextDouble()) {
        number = file.nextDouble();

        if(number > maximum)
            maximum = number;

        else if(number < minimum)
            minimum = number;

        sum += number;
        count += 1;

    } // end while loop

    file.close();

/* -------------------------------------------------------------------------- */
    // mean calculation
    mean = sum / count;

    // standard deviation calculation
    // .....

    // display statistics
    System.out.println("Maximum ------------> " + maximum                   );
    System.out.println("Minimum ------------> " + minimum                   );
    System.out.println("Sum ----------------> " + sum                       );
    System.out.println("Count --------------> " + count                     );
    System.out.println("Mean ---------------> " + mean                      );

} // end method main

} // end class DataFile

Body:
As suggested by Przemysław MoskalI, I believe something like this is what you are after! Lists are incredibly useful in Java. This was done very quickly, so make sure you are happy with the final calcs! Happy Programming!

Edited - used computational formula thanks to a suggestion from Bathsheba, which allows you to not make use of a list at all (which is more memory efficient).

See this website for an easy way to understand the calculation:
https://www.mathsisfun.com/data/standard-deviation-formulas.html

// initialize variables
maximum = file.nextDouble();
minimum = maximum;
sum = 0;
count = 1;
double computationalSum = 0;
double squareSum = 0;

while(file.hasNextDouble()) {
    number = file.nextDouble();

    squareSum += Math.pow(number, 2);
    computationalSum += number;

    if(number > maximum)
        maximum = number;

    else if(number < minimum)
        minimum = number;

    sum += number;
    count += 1;

} // end while loop

file.close();

/* ------------------------------------------------------------------------*/
// mean calculation
mean = sum / count;
double stdDevSum = 0;
double stdDevMean = 0;
double stdDev = 0;

double sumOfSquares = squareSum - ((Math.pow(computationalSum, 2)/(count-1)));
double sSquared = sumOfSquares/(count-1);
double otherStdDev = Math.sqrt(sSquared);

// display statistics
System.out.println("Maximum ------------> " + maximum                   );
System.out.println("Minimum ------------> " + minimum                   );
System.out.println("Sum ----------------> " + sum                       );
System.out.println("Count --------------> " + count                     );
System.out.println("Mean ---------------> " + mean                      );
System.out.println("StdDev -------------> " + otherStdDev);

} // end method main


问:
User comments in Web Application
I am learning on building an HTML page where the user can comment on the page using javascript and preferably using HTML 5 local storage.

I have made a lot of research and have this code below which will give a html form for putting comment, name and date, then adds the comment below I have not touched the storage part till now.

The problem I am facing right now is that it is not working in Chrome or IE but when I start to debug in JSfiddle it is doing exactly what needs to be done. Can anyone help me the problem I am facing here?

function render(data) {

  var html = "

" + data.name + "
" + data.date + "

" + data.body + "

";

  $('#container').append(html);

}

$(document).ready(function() {

  var coment = [{
    "name": "username",
    "date": "01 Apr, 2017",
    "body": "this is a comment 1"
  }];

  for (var i = 0; i < coment.length; i++) {
    render(coment[i]);

  }

  $('#addComent').click(function() {
    var addObj = {
      "name": $('#name').val(),
      "date": $('#date').val(),
      "body": $('#bodyText').val()
    };

    coment.push(addObj);
    render(addObj);
    $('#name').val('');
    $('#date').val('dd/mm/yyyy');
    $('#bodyText').val('');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  width: 100%;
  height: 100%;
}

body {
  width: 100%;
  height: 100%;
}

.commentBox {
  padding: 1%;
  width: 96%;
  border: 1px solid #000;
  background-color: #f0f0f0;
  margin-bottom: 10px;
}

.leftPanelImg {
  width: 10%;
  float: left;
}

.leftPanelImg img {
  border-radius: 100%
}

.rightPanel {
  width: 85%;
  float: left;
  margin-left: 1%;
}

.clear {
  clear: both;
}

.form {
  padding: 10px;
  border: 1px solid #000;
  margin-bottom: 10px;
  text-align: center;
}

.form input[type="text"],
.form textarea,
.form imput[type="date"] {
  border: 1px solid #000;
  padding: 2px;
  width: 300px;
}</code>```

Add Comments

  Name: <input type="text" id="name" />

 Date: <input type="date" id="date" />

 Body: <textarea rows="5" col "30" id="bodyText"></textarea>

  <input type="button" id="addComent" value="Add Comment" />

```

答:
Actually code works. You've probably inserted your script in the wrong order. Here's an example

```<code>    <html>
<body>
<style>
    html {
        width: 100%;
        height: 100%;
    }

    body {
        width: 100%;
        height: 100%;
    }

    .commentBox {
        padding: 1%;
        width: 96%;
        border: 1px solid #000;
        background-color: #f0f0f0;
        margin-bottom: 10px;
    }

    .leftPanelImg {
        width: 10%;
        float: left;
    }

    .leftPanelImg img {
        border-radius: 100%
    }

    .rightPanel {
        width: 85%;
        float: left;
        margin-left: 1%;
    }

    .clear {
        clear: both;
    }

    .form {
        padding: 10px;
        border: 1px solid #000;
        margin-bottom: 10px;
        text-align: center;
    }

    .form input[type="text"],
    .form textarea,
    .form imput[type="date"] {
        border: 1px solid #000;
        padding: 2px;
        width: 300px;
    }
</style>
<div class='form'>
    <h5>Add Comments</h5>
    Name: <input type="text" id="name" /> <br/><br /> Date: <input type="date" id="date" /> <br/><br /> Body: <textarea rows="5" col "30" id="bodyText"></textarea><br /><br />
    <input type="button" id="addComent" value="Add Comment" />
</div>
<div id='container'>

</div>

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script>
    function render(data) {

        var html = "<div class='commentBox'><div class='leftPanelImg'><img src='http://via.placeholder.com/100x100'/></div><div class='rightPanel'><span>" + data.name + "</span><div class='date'>" + data.date + "</div><p>" + data.body + "</p></div><div class='clear'></div></div>";

        $('#container').append(html);

    }

    $(document).ready(function() {

        var coment = [{
            "name": "username",
            "date": "01 Apr, 2017",
            "body": "this is a comment 1"
        }];

        for (var i = 0; i < coment.length; i++) {
            render(coment[i]);

        }

        $('#addComent').click(function() {
            var addObj = {
                "name": $('#name').val(),
                "date": $('#date').val(),
                "body": $('#bodyText').val()
            };

            coment.push(addObj);
            render(addObj);
            $('#name').val('');
            $('#date').val('dd/mm/yyyy');
            $('#bodyText').val('');
        });
    });
</script>
</body>
</html>
</code>```

Additionally you can take a look here plunker

Title: User comments in Web Application

Body:
I am learning on building an HTML page where the user can comment on the page using javascript and preferably using HTML 5 local storage.

I have made a lot of research and have this code below which will give a html form for putting comment, name and date, then adds the comment below I have not touched the storage part till now.

The problem I am facing right now is that it is not working in Chrome or IE but when I start to debug in JSfiddle it is doing exactly what needs to be done. Can anyone help me the problem I am facing here?

function render(data) {

  var html = "

" + data.name + "
" + data.date + "

" + data.body + "

";

  $('#container').append(html);

}

$(document).ready(function() {

  var coment = [{
    "name": "username",
    "date": "01 Apr, 2017",
    "body": "this is a comment 1"
  }];

  for (var i = 0; i < coment.length; i++) {
    render(coment[i]);

  }

  $('#addComent').click(function() {
    var addObj = {
      "name": $('#name').val(),
      "date": $('#date').val(),
      "body": $('#bodyText').val()
    };

    coment.push(addObj);
    render(addObj);
    $('#name').val('');
    $('#date').val('dd/mm/yyyy');
    $('#bodyText').val('');
  });
});

html {
  width: 100%;
  height: 100%;
}

body {
  width: 100%;
  height: 100%;
}

.commentBox {
  padding: 1%;
  width: 96%;
  border: 1px solid #000;
  background-color: #f0f0f0;
  margin-bottom: 10px;
}

.leftPanelImg {
  width: 10%;
  float: left;
}

.leftPanelImg img {
  border-radius: 100%
}

.rightPanel {
  width: 85%;
  float: left;
  margin-left: 1%;
}

.clear {
  clear: both;
}

.form {
  padding: 10px;
  border: 1px solid #000;
  margin-bottom: 10px;
  text-align: center;
}

.form input[type="text"],
.form textarea,
.form imput[type="date"] {
  border: 1px solid #000;
  padding: 2px;
  width: 300px;
}

Add Comments

  Name: <input type="text" id="name" />

 Date: <input type="date" id="date" />

 Body: <textarea rows="5" col "30" id="bodyText"></textarea>

  <input type="button" id="addComent" value="Add Comment" />

Body:
Actually code works. You've probably inserted your script in the wrong order. Here's an example

    <html>
<body>
<style>
    html {
        width: 100%;
        height: 100%;
    }

    body {
        width: 100%;
        height: 100%;
    }

    .commentBox {
        padding: 1%;
        width: 96%;
        border: 1px solid #000;
        background-color: #f0f0f0;
        margin-bottom: 10px;
    }

    .leftPanelImg {
        width: 10%;
        float: left;
    }

    .leftPanelImg img {
        border-radius: 100%
    }

    .rightPanel {
        width: 85%;
        float: left;
        margin-left: 1%;
    }

    .clear {
        clear: both;
    }

    .form {
        padding: 10px;
        border: 1px solid #000;
        margin-bottom: 10px;
        text-align: center;
    }

    .form input[type="text"],
    .form textarea,
    .form imput[type="date"] {
        border: 1px solid #000;
        padding: 2px;
        width: 300px;
    }
</style>
<div class='form'>
    <h5>Add Comments</h5>
    Name: <input type="text" id="name" /> <br/><br /> Date: <input type="date" id="date" /> <br/><br /> Body: <textarea rows="5" col "30" id="bodyText"></textarea><br /><br />
    <input type="button" id="addComent" value="Add Comment" />
</div>
<div id='container'>

</div>

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script>
    function render(data) {

        var html = "<div class='commentBox'><div class='leftPanelImg'><img src='http://via.placeholder.com/100x100'/></div><div class='rightPanel'><span>" + data.name + "</span><div class='date'>" + data.date + "</div><p>" + data.body + "</p></div><div class='clear'></div></div>";

        $('#container').append(html);

    }

    $(document).ready(function() {

        var coment = [{
            "name": "username",
            "date": "01 Apr, 2017",
            "body": "this is a comment 1"
        }];

        for (var i = 0; i < coment.length; i++) {
            render(coment[i]);

        }

        $('#addComent').click(function() {
            var addObj = {
                "name": $('#name').val(),
                "date": $('#date').val(),
                "body": $('#bodyText').val()
            };

            coment.push(addObj);
            render(addObj);
            $('#name').val('');
            $('#date').val('dd/mm/yyyy');
            $('#bodyText').val('');
        });
    });
</script>
</body>
</html>

Additionally you can take a look here plunker


问:
App crashes when i use Cursor method to get data from SQlite
This is my code, the Cursor cursor= db.rawQuery is the reason. My app keep crashing

please tell me what's wrong:-

```<code>public QuestionController(Context context) {
    dbHelper= new DBHelper(context);
}

//Lấy danh sách câu hỏi
public ArrayList<Question> getQuestion(int num_exam, String subject){
    ArrayList<Question> lsData= new ArrayList<Question>();
    SQLiteDatabase db= dbHelper.getReadableDatabase();

    Cursor cursor= db.rawQuery("SELECT * FROM tracnghiem WHERE num_exam = '"+ num_exam+"' AND subject='"+subject+"' ORDER BY random()",null);
    cursor.moveToFirst();
    do {
        Question item;
        item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
                cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
        lsData.add(item);
    }while (cursor.moveToNext());
    cursor.close();
    return lsData;
</code>```

答:
In your case, there can be only 3 leaks for crashing app,

Established connection with DB is not proper.

Wrong query (table or fields in table not exist in DB).

Your cursor returns 0 rows.

Body:
This is my code, the Cursor cursor= db.rawQuery is the reason. My app keep crashing

please tell me what's wrong:-

public QuestionController(Context context) {
    dbHelper= new DBHelper(context);
}

//Lấy danh sách câu hỏi
public ArrayList<Question> getQuestion(int num_exam, String subject){
    ArrayList<Question> lsData= new ArrayList<Question>();
    SQLiteDatabase db= dbHelper.getReadableDatabase();

    Cursor cursor= db.rawQuery("SELECT * FROM tracnghiem WHERE num_exam = '"+ num_exam+"' AND subject='"+subject+"' ORDER BY random()",null);
    cursor.moveToFirst();
    do {
        Question item;
        item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
                cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
        lsData.add(item);
    }while (cursor.moveToNext());
    cursor.close();
    return lsData;


答:
Maybe you want to use a BufferedReader for this.

```<code>  BufferedReader in = new BufferedReader(
                          new FileReader(args[0]));
</code>```

Then:

```<code>  String num = null;
  while((num = in.readLine()) != null){
        double d = Double.parseDouble(num);
        //now you have a double value
  }
</code>```

This way you do not depend on the exception to indicate the end of file.

Title: DataInputStream for input text files?

Body:
I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?

import java.io.*;
import java.util.*;

class ReadWriteData
{
    public static void main(String[] args) throws Exception
    {

        //create ouput file
        PrintWriter output = new PrintWriter("output2.txt");

        DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
        DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));

        try
        {

        // read data from file
        while (true)
        {
            double number1 = file1.readDouble();
            double number2 = file2.readDouble();
            double result = number1 * number2 ;
            output.println(result);

        }

        }

        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }

        output.close() ;

    }
}

Body:
Maybe you want to use a BufferedReader for this.

  BufferedReader in = new BufferedReader(
                          new FileReader(args[0]));

Then:

  String num = null;
  while((num = in.readLine()) != null){
        double d = Double.parseDouble(num);
        //now you have a double value
  }

This way you do not depend on the exception to indicate the end of file.


问:
Error: [ng:areq] Argument 'CartCrtl' is not a function, got undefined
Here I'm trying to add products from the products list to the cart.Products list is in the ProductCrtl. Using CartCrtl I'm trying to get the product values.

How can I fix the above error?

My Code-

```<code><!doctype html>
<html lang="en" ng-app="MyApp4">
<head>
  <meta charset="utf-8">
  <title>Controllers</title>
  <script src="angular.js"></script>
    <script src="app4.js"></script>
  </head>
<body  ng-controller="MyApp4Crtl">
    <table  ng-controller="ProductCtrl">
        <h1>Products</h1>
        <thead>
            <tr>
                <th>#</th>
                <th>Product Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="product in products">
                <td>{{$index+1}}</td>
                <td>{{product.name}}</td>
                <td>{{product.price | currency}}</td>
                <td><button ng-click=addToCart(product)>Add to Cart</button></td>
            </tr>
        </tbody>
    </table>

    <div ng-controller="CartCrtl">
        <h1>Cart</h1>
    Adding products!
    </div>
</body>
</html>
</code>```

app4.js

```<code>name="MyApp4";
requires=[];
app4=angular.module(name,requires);

app4.controller("MyApp4Crtl",function($scope){
$scope.name1="Aluuu!";

});
app4.controller("ProductCtrl",function($scope,$rootScope){
$scope.products=[{name:"Computer",price:233},
                  {name:"Book",price:20},
                  {name:"Pen",price:2000},
                  {name:"Pencil",price:10},
                  {name:"box",price:11},
                  {name:"Laptop",price:10000},
                  {name:"CD",price:34},
                  {name:"DVD",price:3}
  ];
  $scope.addToCart=function(item){
    $rootScope.$broadcast("addProductEvent",item);
  }
});

app4.controller("CartCtrl",function($scope){
$scope.cartItems=[];

$scope.$on("addProductEvent",addingCartFunction);
function addingCartFunction(evt,product){
  $scope.cartItems.push(product);
}

});
</code>```

The Cartctrl is not defined.I have included the ng-app in the html tag also.

答:
here is a working example of yours

name="MyApp4";
requires=[];
app4=angular.module(name,requires);

app4.controller("MyApp4Crtl",function($scope){
   $scope.name1="Aluuu!";
});
app4.controller("ProductCtrl",function($scope,$rootScope){
$scope.products=[{name:"Computer",price:233},
                  {name:"Book",price:20},
                  {name:"Pen",price:2000},
                  {name:"Pencil",price:10},
                  {name:"box",price:11},
                  {name:"Laptop",price:10000},
                  {name:"CD",price:34},
                  {name:"DVD",price:3}
  ];
  $scope.addToCart=function(item){
   $rootScope.$broadcast("addProductEvent",item);
  }
});
app4.controller("CartCtrl",function($scope){
  $scope.cartItems=[];

   $scope.$on("addProductEvent",addingCartFunction);
   function addingCartFunction(evt,product){
     $scope.cartItems.push(product);
   }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div  ng-app="MyApp4"  ng-controller="MyApp4Crtl">
  <div ng-controller="ProductCtrl">
     <table >
        <h1>Products</h1>
        <thead>
            <tr>
                <th>#</th>
                <th>Product Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="product in products">
                <td>{{$index+1}}</td>
                <td>{{product.name}}</td>
                <td>{{product.price | currency}}</td>
                <td><button ng-click=addToCart(product)>Add to Cart</button></td>
            </tr>
        </tbody>
    </table>
  </div>
  <div ng-controller="CartCtrl">
     <h1>Cart</h1>
    Adding products!
    {{cartItems}}
  </div>
  </div></code>```

Body:
Here I'm trying to add products from the products list to the cart.Products list is in the ProductCrtl. Using CartCrtl I'm trying to get the product values.

How can I fix the above error?

My Code-

<!doctype html>

  <meta charset="utf-8">
  <title>Controllers</title>

Products

                #
                Product Name
                Price

                {{$index+1}}
                {{product.name}}
                {{product.price | currency}}
                <button ng-click=addToCart(product)>Add to Cart</button>

Cart

    Adding products!

app4.js

name="MyApp4";
requires=[];
app4=angular.module(name,requires);

app4.controller("MyApp4Crtl",function($scope){
$scope.name1="Aluuu!";

});
app4.controller("ProductCtrl",function($scope,$rootScope){
$scope.products=[{name:"Computer",price:233},
                  {name:"Book",price:20},
                  {name:"Pen",price:2000},
                  {name:"Pencil",price:10},
                  {name:"box",price:11},
                  {name:"Laptop",price:10000},
                  {name:"CD",price:34},
                  {name:"DVD",price:3}
  ];
  $scope.addToCart=function(item){
    $rootScope.$broadcast("addProductEvent",item);
  }
});

app4.controller("CartCtrl",function($scope){
$scope.cartItems=[];

$scope.$on("addProductEvent",addingCartFunction);
function addingCartFunction(evt,product){
  $scope.cartItems.push(product);
}

});

The Cartctrl is not defined.I have included the ng-app in the html tag also.

Body:
here is a working example of yours

name="MyApp4";
requires=[];
app4=angular.module(name,requires);

app4.controller("MyApp4Crtl",function($scope){
   $scope.name1="Aluuu!";
});
app4.controller("ProductCtrl",function($scope,$rootScope){
$scope.products=[{name:"Computer",price:233},
                  {name:"Book",price:20},
                  {name:"Pen",price:2000},
                  {name:"Pencil",price:10},
                  {name:"box",price:11},
                  {name:"Laptop",price:10000},
                  {name:"CD",price:34},
                  {name:"DVD",price:3}
  ];
  $scope.addToCart=function(item){
   $rootScope.$broadcast("addProductEvent",item);
  }
});
app4.controller("CartCtrl",function($scope){
  $scope.cartItems=[];

   $scope.$on("addProductEvent",addingCartFunction);
   function addingCartFunction(evt,product){
     $scope.cartItems.push(product);
   }

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div  ng-app="MyApp4"  ng-controller="MyApp4Crtl">
  <div ng-controller="ProductCtrl">
     <table >
        <h1>Products</h1>
        <thead>
            <tr>
                <th>#</th>
                <th>Product Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="product in products">
                <td>{{$index+1}}</td>
                <td>{{product.name}}</td>
                <td>{{product.price | currency}}</td>
                <td><button ng-click=addToCart(product)>Add to Cart</button></td>
            </tr>
        </tbody>
    </table>
  </div>
  <div ng-controller="CartCtrl">
     <h1>Cart</h1>
    Adding products!
    {{cartItems}}
  </div>
  </div>


问:
Get File Extension C#
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following

```<code>string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);
</code>```

In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?

Things  I have
1.) File name without extension in

```<code>string filename = ddl.SelectedItem.Text;
</code>```

2.) Path where the file is located

```<code>string path = "F:\\WorkingCopy\\files\\" + filename
</code>```

I am trying to get the file extension with these . Can any one suggest on this?

答:
You can simply split them by dot, For example, try this code

```<code>        string folder = @"F:\\WorkingCopy\\files\\";
        var files = System.IO.Directory.GetFiles(folder, filename + ".*");

        if (files.Any())
        {
            string ext = System.IO.Path.GetExtension(files.First()).Substring(1);
        }
</code>```

This code gives me result that the extension for this is txt file.

Title: Get File Extension C#

Body:
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following

string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);

In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?

Things  I have
1.) File name without extension in

string filename = ddl.SelectedItem.Text;

2.) Path where the file is located

string path = "F:\\WorkingCopy\\files\\" + filename

I am trying to get the file extension with these . Can any one suggest on this?

Body:
You can simply split them by dot, For example, try this code

        string folder = @"F:\\WorkingCopy\\files\\";
        var files = System.IO.Directory.GetFiles(folder, filename + ".*");

        if (files.Any())
        {
            string ext = System.IO.Path.GetExtension(files.First()).Substring(1);
        }

This code gives me result that the extension for this is txt file.


问:
MySQL connection made but query failing
Im trying to create a login page.
Connection is successful but query is not fetching the required result.
login page sends data through post method to action_page.php.

Action_page.php

```<code><?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "MyDB";

$con = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$uname = $_POST['uname'];
$pass = $_POST['psw'];
$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;
echo "<br/>$sql<br/>";

//$result = $con->query($sql);

echo var_dump($con->query($sql));

$con->close();
</code>```

?>

could someone please help.!

答:
It is recommended to use either the mysqli or PDO_MySQL extensions. It
  is not recommended to use the old mysql extension for new development,
  as it was deprecated in PHP 5.5.0 and was removed in PHP 7.

Example Your code Comparing with three MySQL APIs

```<code><?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = $result->fetch_assoc();
echo htmlentities($row['uname']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['uname']);

// mysql
$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['uname']);
?>
</code>```

check link

Title: MySQL connection made but query failing

Body:
Im trying to create a login page.
Connection is successful but query is not fetching the required result.
login page sends data through post method to action_page.php.

Action_page.php

<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "MyDB";

$con = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$uname = $_POST['uname'];
$pass = $_POST['psw'];
$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;
echo "
$sql
";

//$result = $con->query($sql);

echo var_dump($con->query($sql));

$con->close();

?>

could someone please help.!

Body:
It is recommended to use either the mysqli or PDO_MySQL extensions. It
  is not recommended to use the old mysql extension for new development,
  as it was deprecated in PHP 5.5.0 and was removed in PHP 7.

Example Your code Comparing with three MySQL APIs

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = $result->fetch_assoc();
echo htmlentities($row['uname']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['uname']);

// mysql
$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['uname']);
?>

check link


问:
Dynamic content share on social media
I am trying to share dynamic content on Facebook using localhost xampp.My project not uploaded on any domain.Problem is that when I click on facebook link then new dialog box open but the path is using search bar is not working correctly https://www.facebook.com/dialog/feed?app_id=141722133242641&link=http://localhost/JustClick/Professional/show_professional_detail/13..
But when I use the same path http://localhost/JustClick/Professional/show_professional_detail/13 in a separate tab then it's working it's showing my website data.when I use both this URL   https://www.facebook.com/dialog/feed?app_id=141722133242641&link=http://localhost/JustClick/Professional/show_professional_detail/13   then it showing " Sorry, something went wrong. " this error.Please help me how I solve this problem.
localhost is my baseurl
Professional is my controller
show_professional_detail is method of controller
13 is the id of professional</p>

```<code>Here is my code of show_professional_detail method:

    <meta property="og:url"           content="http://localhost/JustClick/Professional/show_professional_detail?id=<?php  echo $row->pro_id; ?>" />
    <meta property="og:type"          content="website" />
    <meta property="og:title"         content="<?php  echo $row->pro_business_name; ?>" />
    <meta property="og:description"   content="<?php  echo $row->pro_email; ?>" />
    <meta property="og:image"         content="http://localhost/JustClick/Professional/show_professional_detail<?php  echo $row->professional_image; ?>" />

            <li><p class="icon show_detail_icon_fb"><a data-toggle="tooltip" data-placement="right" title="Facebook" href="javascript:void(0);" onclick="fb_share('<?php echo base_url('Professional/show_professional_detail/'.$row->pro_id) ?>','<?php echo $row->pro_business_name?>')" class="fbBtm">
            <img src="<?php echo base_url('assets/graphics/facebook-icon.png') ?>" width="40" height="40" alt="Facebook" />
            </a></p></li>

Here is my javascript code:

<div id="fb-root"></div>

<script type='text/javascript'>`enter code here`

(function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id))
            return;
        js = d.createElement(s);
        js.id = id;
        js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.3&appId=141722133242641";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

function fb_share(dynamic_link,dynamic_title) {
    var app_id = '141722133242641';
    var pageURL="https://www.facebook.com/dialog/feed?app_id=" + app_id + "&link=" + dynamic_link;
    var w = 600;
    var h = 400;
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);
    window.open(pageURL, dynamic_title, 'toolbar=no, location=no, directories=no, status=no, menubar=yes, scrollbars=no, resizable=no, copyhistory=no, width=' + 800 + ', height=' + 650 + ', top=' + top + ', left=' + left)
    return false;
}

</script>

Please help me.
</code>```

答:
Follow the below steps:

Step #1: Use the bellow script at the bottom of the page before  tag.

```<code><script type="text/javascript">
      (function (d, s, id){
        var js, fjs=d.getElementsByTagName(s)[0];
        if(d.getElementById(id))
          return;
        js=d.createElement(s);
        js.id=id;
        js.src="//connect.facebook.net/en_GB/sdk.jsBxfbml=1&version=v2.3&appId=facebook_app_id";
        fjs.parentNode.insertBefore(js, fjs);
      }(document, 'script', 'facebook-jssdk'));

    function fb_share(dynamic_link,dynamic_title){
      var app_id='facebook_app_id';
      var pageURL="https://www.facebook.com/dialog/feed?app_id="+ app_id +
      "&link" + dynamic_link;
      var w=600;
      var h=400;
      var left = (screen.width / 2) - (w / 2);
      var top = (screen.height / 2) - (h / 2);

    window.open(pageURL, dynamic_title,
    'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=no,
    resizable=no,copyhistory=no, width=' + 800 + ',height=' + 650 + ',top=' +
    top + ',left=' + left)
    return false;
    }
    </script>

</code>```

Step #2: Add this meta tags in under  tag and get content from Database.

```<code><meta property="og:url" content="dynamic_page_full_link">
<!-- for inastance http://mywebname.com/View_news/<?php echo $id; ?> -->
<meta property="og:type" content="website">
<meta property="og:title" content="<?php echo $news_title; ?>">
<meta property="og:description" content="<?php echo $news_message; ?>">
<meta property="og:image" content="<?php echo base_url(); ?>admin/files<?php echo $news_image; ?>">
</code>```

Step #3: Your own link for facebook share button.

```<code><li>
<p class="icon show_detail_icon_fb">
<a data-toggle="tooltip" data-placement="right" title="Facebook" href="javascript:void(0);" onclick="fb_share('<?php echo base_url('Professional/show_professional_detail/'.$row->pro_id) ?>','<?php echo $row->pro_business_name?>')" class="fbBtm">
<img src="<?php echo base_url('assets/graphics/facebook-icon.png') ?>" width="40" height="40" alt="Facebook" />
</a></p></li>
</code>```

That's it.

Title: Dynamic content share on social media

Body:
I am trying to share dynamic content on Facebook using localhost xampp.My project not uploaded on any domain.Problem is that when I click on facebook link then new dialog box open but the path is using search bar is not working correctly https://www.facebook.com/dialog/feed?app_id=141722133242641&link=http://localhost/JustClick/Professional/show_professional_detail/13..
But when I use the same path http://localhost/JustClick/Professional/show_professional_detail/13 in a separate tab then it's working it's showing my website data.when I use both this URL   https://www.facebook.com/dialog/feed?app_id=141722133242641&link=http://localhost/JustClick/Professional/show_professional_detail/13   then it showing " Sorry, something went wrong. " this error.Please help me how I solve this problem.
localhost is my baseurl
Professional is my controller
show_professional_detail is method of controller
13 is the id of professional

Here is my code of show_professional_detail method:

    <meta property="og:url"           content="http://localhost/JustClick/Professional/show_professional_detail?id=<?php  echo $row->pro_id; ?>" />
    <meta property="og:type"          content="website" />
    <meta property="og:title"         content="<?php  echo $row->pro_business_name; ?>" />
    <meta property="og:description"   content="<?php  echo $row->pro_email; ?>" />
    <meta property="og:image"         content="http://localhost/JustClick/Professional/show_professional_detail<?php  echo $row->professional_image; ?>" />

<a data-toggle="tooltip" data-placement="right" title="Facebook" href="javascript:void(0);" onclick="fb_share('<?php echo base_url('Professional/show_professional_detail/'.$row->pro_id) ?>','<?php echo $row->pro_business_name?>')" class="fbBtm">
            <img src="<?php echo base_url('assets/graphics/facebook-icon.png') ?>" width="40" height="40" alt="Facebook" />

Here is my javascript code:

Please help me.

Body:
Follow the below steps:

Step #1: Use the bellow script at the bottom of the page before </body> tag.

<script type="text/javascript">
      (function (d, s, id){
        var js, fjs=d.getElementsByTagName(s)[0];
        if(d.getElementById(id))
          return;
        js=d.createElement(s);
        js.id=id;
        js.src="//connect.facebook.net/en_GB/sdk.jsBxfbml=1&version=v2.3&appId=facebook_app_id";
        fjs.parentNode.insertBefore(js, fjs);
      }(document, 'script', 'facebook-jssdk'));

    function fb_share(dynamic_link,dynamic_title){
      var app_id='facebook_app_id';
      var pageURL="https://www.facebook.com/dialog/feed?app_id="+ app_id +
      "&link" + dynamic_link;
      var w=600;
      var h=400;
      var left = (screen.width / 2) - (w / 2);
      var top = (screen.height / 2) - (h / 2);

    window.open(pageURL, dynamic_title,
    'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=no,
    resizable=no,copyhistory=no, width=' + 800 + ',height=' + 650 + ',top=' +
    top + ',left=' + left)
    return false;
    }
    </script>

Step #2: Add this meta tags in under  tag and get content from Database.

<meta property="og:url" content="dynamic_page_full_link">
<!-- for inastance http://mywebname.com/View_news/<?php echo $id; ?> -->
<meta property="og:type" content="website">
<meta property="og:title" content="<?php echo $news_title; ?>">
<meta property="og:description" content="<?php echo $news_message; ?>">
<meta property="og:image" content="<?php echo base_url(); ?>admin/files<?php echo $news_image; ?>">

Step #3: Your own link for facebook share button.

<li>
<p class="icon show_detail_icon_fb">
<a data-toggle="tooltip" data-placement="right" title="Facebook" href="javascript:void(0);" onclick="fb_share('<?php echo base_url('Professional/show_professional_detail/'.$row->pro_id) ?>','<?php echo $row->pro_business_name?>')" class="fbBtm">
<img src="<?php echo base_url('assets/graphics/facebook-icon.png') ?>" width="40" height="40" alt="Facebook" />
</a></p></li>

That's it.

ContentLicense: CC BY-SA 4.0


问:
Echo Class Inside of HTML Tag with PHP
Trying to get this piece of code to run:

```<code><li><a <? if ($tab=='Home') echo 'class="activetab"' ?> href="/">Home</a></li>
</code>```

Right now, my PHP/Apache on EC2 setup spits out

```<code>href="/">Home
</code>```

It looks like the php inside the tag is messing up the rendering, and I'd like the tab to be rendered.

The  site is hosted somewhere else and works, so it seems like a configuration issue with either php or apache.

答:
<? ... ?> – This is called as PHP short tags which will work based on the value set with short_open_tag directive of PHP configuration file.

Otherwise use <?php ... ?> as delimiters which are also preferable, since, PHP code enclosed with in <?php ... ?> could be recognized with other PHP servers independent of the tag related configuration directives.

Title: Echo Class Inside of HTML Tag with PHP

Body:
Trying to get this piece of code to run:

<a <? if ($tab=='Home') echo 'class="activetab"' ?> href="/">Home

Right now, my PHP/Apache on EC2 setup spits out

href="/">Home

It looks like the php inside the tag is messing up the rendering, and I'd like the tab to be rendered.

The  site is hosted somewhere else and works, so it seems like a configuration issue with either php or apache.


问:
Get current object URL with JavaScript
I have a webpage uses object that are external websites (or other web pages).
for example:

```<code><object data="external.html"></object>
</code>```

on this page (external.html), the URL changes according to the navigation of the user. I want to know if there's a way to get the new URL using JavaScript/jQuery.

For example, when using:

```<code><object data="www.google.com"></object>
</code>```

If the user went from www.google.com to www.google.com/#q=JavaScript, I would like to get the second URL.
This won't work with Google, but theoretically speaking.

Alternatively, is there a way to display an external website and have access to the changing URL? Meaning, having a div populated by another website and somehow get the URL (after the user navigated through the site and the URL changes) with JavaScript/jQuery/some other way?
No need to manipulate this URL, just read access.

答:
```<code>$('button').click(function() {
  var urlSplit = 'www.google.com/#q=JavaScript'.split('/');
  alert(urlSplit[urlSplit.length - 1]);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
  Click Me
</button>
</code>```

Title: Get current object URL with JavaScript

Body:
I have a webpage uses object that are external websites (or other web pages).
for example:

<object data="external.html"></object>

on this page (external.html), the URL changes according to the navigation of the user. I want to know if there's a way to get the new URL using JavaScript/jQuery.

For example, when using:

<object data="www.google.com"></object>

If the user went from www.google.com to www.google.com/#q=JavaScript, I would like to get the second URL.
This won't work with Google, but theoretically speaking.

Alternatively, is there a way to display an external website and have access to the changing URL? Meaning, having a div populated by another website and somehow get the URL (after the user navigated through the site and the URL changes) with JavaScript/jQuery/some other way?
No need to manipulate this URL, just read access.


问:
angular2-multiselect-dropdown shows empty list
I am using angular2-multiselect-dropdown but the dropdown is empty.

Following is the data in ts file:

```<code>this.list = [
{
   "docid":1,
   "value": "Europe"
},
{
   "docid":2,
   "value": "ASIA"
},
{
   "docid":3,
   "value": "AFRICA"
},
{
   "docid":4,
   "value": "LATIN AMERICA"
},
{
   "docid":5,
   "value": "NORTH AMERICA"
}

]
</code>```

In HTML :

```<code><angular2-multiselect [data]="List" [(ngModel)]="selectedItems"
        (onSelect)="onItemSelect($event)"
        (onDeSelect)="OnItemDeSelect($event)"
        (onSelectAll)="onSelectAll($event)"
        (onDeSelectAll)="onDeSelectAll($event)">
      </angular2-multiselect>
</code>```

In examples, he is using {"id":9,"itemName":"Italy"} which works well. So is there any way that the field itemName can be configured.

https://github.com/CuppaLabs/angular2-multiselect-dropdown
https://cuppalabs.github.io/angular2-multiselect-dropdown/#/basic

答:
Maybe, I found an error in your code.

```<code><angular2-multiselect [data]="list" [(ngModel)]="selectedItems"
        (onSelect)="onItemSelect($event)"
        (onDeSelect)="OnItemDeSelect($event)"
        (onSelectAll)="onSelectAll($event)"
        (onDeSelectAll)="onDeSelectAll($event)">
      </angular2-multiselect>
</code>```

Instead of [data]="List" you need to write [data]="list".

Then, add a method map as say in comment above.

Body:
I am using angular2-multiselect-dropdown but the dropdown is empty.

Following is the data in ts file:

this.list = [
{
   "docid":1,
   "value": "Europe"
},
{
   "docid":2,
   "value": "ASIA"
},
{
   "docid":3,
   "value": "AFRICA"
},
{
   "docid":4,
   "value": "LATIN AMERICA"
},
{
   "docid":5,
   "value": "NORTH AMERICA"
}

]

In HTML :

<angular2-multiselect [data]="List" [(ngModel)]="selectedItems"
        (onSelect)="onItemSelect($event)"
        (onDeSelect)="OnItemDeSelect($event)"
        (onSelectAll)="onSelectAll($event)"
        (onDeSelectAll)="onDeSelectAll($event)">
      </angular2-multiselect>

In examples, he is using {"id":9,"itemName":"Italy"} which works well. So is there any way that the field itemName can be configured.

https://github.com/CuppaLabs/angular2-multiselect-dropdown
https://cuppalabs.github.io/angular2-multiselect-dropdown/#/basic

Body:
Maybe, I found an error in your code.

<angular2-multiselect [data]="list" [(ngModel)]="selectedItems"
        (onSelect)="onItemSelect($event)"
        (onDeSelect)="OnItemDeSelect($event)"
        (onSelectAll)="onSelectAll($event)"
        (onDeSelectAll)="onDeSelectAll($event)">
      </angular2-multiselect>

Instead of [data]="List" you need to write [data]="list".

Then, add a method map as say in comment above.


问:
Can't compile project when I'm using Lombok under IntelliJ IDEA
I'm trying to use Lombok in my project that I'm developing using IntelliJ IDEA 11.

I've installed 3rd-party plugin for IDEA and it seems working fine because IDEA sees all autogenerated methods/fields.

So I have a class that uses Slf4j. I annotated it like this

```<code>import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestClass
{
    public TestClass()
    {
        log.info("Hello!");
    }
}
</code>```

But when I build my project compiler spits: cannot find symbol variable log.

Could you please tell me what I'm missing here?

Update: It turned out it's RequestFactory annotation process that fails.

```<code>input files: {com.zasutki.courierApp.server.TestServlet, com.mine.courierApp.server.model.DatastoreObject}

annotations: [javax.inject.Singleton, javax.inject.Inject, lombok.Getter, lombok.Setter, com.googlecode.objectify.annotation.Id, com.googlecode.objectify.annotation.OnSave]

Processor com.google.web.bindery.requestfactory.apt.RfValidator matches [lombok.Getter, com.googlecode.objectify.annotation.Id, javax.inject.Inject, lombok.Setter, com.googlecode.objectify.annotation.OnSave, javax.inject.Singleton] and returns false.

cannot find symbol variable log
</code>```

Any ideas on workarounds?

Update2: Perhaps it's not something readers want to hear but I ended up switching to Scala.

答:
1、install lombok plugin for IDEA

Intellij Idea -> Preferences -> Plugins -> type in lombok -> Search in Repositories -> install -> restart IDEA

2、 config lombok plugin

Enabling annotation processing will make it work

But if you are on a Mac, make sure you enable annotation processing in the following two places:

Intellij Idea -> Preferences -> Build, Execution, Deployment -> Compiler -> Annotation Processors, check the checkbox of "Enable annotation processing".
File -> Other Settings -> Default Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors, check the checkbox of "Enable annotation processing".

Body:
I'm trying to use Lombok in my project that I'm developing using IntelliJ IDEA 11.

I've installed 3rd-party plugin for IDEA and it seems working fine because IDEA sees all autogenerated methods/fields.

So I have a class that uses Slf4j. I annotated it like this

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestClass
{
    public TestClass()
    {
        log.info("Hello!");
    }
}

But when I build my project compiler spits: cannot find symbol variable log.

Could you please tell me what I'm missing here?

Update: It turned out it's RequestFactory annotation process that fails.

input files: {com.zasutki.courierApp.server.TestServlet, com.mine.courierApp.server.model.DatastoreObject}

annotations: [javax.inject.Singleton, javax.inject.Inject, lombok.Getter, lombok.Setter, com.googlecode.objectify.annotation.Id, com.googlecode.objectify.annotation.OnSave]

Processor com.google.web.bindery.requestfactory.apt.RfValidator matches [lombok.Getter, com.googlecode.objectify.annotation.Id, javax.inject.Inject, lombok.Setter, com.googlecode.objectify.annotation.OnSave, javax.inject.Singleton] and returns false.

cannot find symbol variable log

Any ideas on workarounds?

Update2: Perhaps it's not something readers want to hear but I ended up switching to Scala.


问:
cursor count is 1 whereas the table has 3 rows
I m trying to populate sql table and then retrieve data from it. Following is my code.

```<code>public void addQuestion(Question quest)
{
    int id = 1;
    ContentValues values = new ContentValues();
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST1);
    onCreate(db);
    values.put(KEY_QUES, quest.getQuestion());
    values.put(KEY_ANSWER, quest.getAnswer());
    values.put(KEY_OPTA, quest.getOptA());
    values.put(KEY_OPTB, quest.getOptB());
    values.put(KEY_OPTC, quest.getOptC());
    db.insert(TABLE_QUEST1, null, values);
    System.out.println("Added in database: " + quest.getQuestion());
}

public ArrayList<Question> getAllQuestions() {
    System.out.println("getting rows 1");
    ArrayList<Question> quesList = new ArrayList<Question>();
    System.out.println("getting rows 2");
    Cursor cursor = null;
    SQLiteDatabase db = getReadableDatabase();
    System.out.println("getting rows ");
    cursor = db.rawQuery("SELECT * FROM " + TABLE_QUEST1, null);
    if (!cursor.moveToFirst()) {
        System.out.println("No data in the database ");
    } else {
        System.out.println("theres data in the database ");
        quesList = new ArrayList<Question>();
        do {
            System.out.print("total rows " + cursor.getCount());
            Question quest = new Question();
            quest.setID(cursor.getInt(0));
            quest.setQuestion(cursor.getString(1));
            quest.setAnswer(cursor.getString(2));
            quest.setOptA(cursor.getString(3));
            quest.setOptB(cursor.getString(4));
            quest.setOptC(cursor.getString(5));
            quesList.add(quest);
        } while (cursor.moveToNext());
        cursor.close();
    }
}
</code>```

I have 4 rows of data in my table and I can see that with the print statement "added in database"

but when i actually read it the cursor just reads row 1 and moves out of the while loop. what could potentially be wrong.

tia

答:
As Santosh has pointed out DROPPING the table (as per db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST1);) and then re-creating it (as per onCreate(db);) will delete the table and then re-create the table removing any rows/data that had previously been added to the table.

As such it's simply a matter of removing those two lines of code, Also there appears to be no need for the line int id = 1;, so perhaps remove this,  as per :-

```<code>public void addQuestion(Question quest)
{
    ContentValues values = new ContentValues();
    SQLiteDatabase db = this.getWritableDatabase();
    values.put(KEY_QUES, quest.getQuestion());
    values.put(KEY_ANSWER, quest.getAnswer());
    values.put(KEY_OPTA, quest.getOptA());
    values.put(KEY_OPTB, quest.getOptB());
    values.put(KEY_OPTC, quest.getOptC());
    db.insert(TABLE_QUEST1, null, values);
    System.out.println("Added in database: " + quest.getQuestion());
}
</code>```

P.S. you may consider not using hard coded column offsets but instead obtain offsets according to column names by utilising the getColumnIndex(column_name) Cursor method. e.g. :-

```<code>        Question quest = new Question();
        quest.setID(cursor.getInt(cursor.getColumnIndex("name_of_your_id_columm")));
        quest.setQuestion(cursor.getString(cursor.getColumnIndex(KEY_QUES)));
        quest.setAnswer(cursor.getString(cursor.getColumnIndex(KEY_ANSWER)));
        quest.setOptA(cursor.getString(cursor.getColumnIndex(KEY_OPTA)));
        quest.setOptB(cursor.getString(cursor.getColumnIndex(KEY_OPTB)));
        quest.setOptC(cursor.getString(cursor.getColumnIndex(KEY_OPTC)));
        quesList.add(quest);
</code>```

Noting that instead of "name_of_your_id_columm", you may have something like KEY_ID defined, if so use that, thus you have a single definition so it reduces the chance of inadvertently mispelling column names or miscalculating the offsets.

Body:
I m trying to populate sql table and then retrieve data from it. Following is my code.

public void addQuestion(Question quest)
{
    int id = 1;
    ContentValues values = new ContentValues();
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST1);
    onCreate(db);
    values.put(KEY_QUES, quest.getQuestion());
    values.put(KEY_ANSWER, quest.getAnswer());
    values.put(KEY_OPTA, quest.getOptA());
    values.put(KEY_OPTB, quest.getOptB());
    values.put(KEY_OPTC, quest.getOptC());
    db.insert(TABLE_QUEST1, null, values);
    System.out.println("Added in database: " + quest.getQuestion());
}

public ArrayList<Question> getAllQuestions() {
    System.out.println("getting rows 1");
    ArrayList<Question> quesList = new ArrayList<Question>();
    System.out.println("getting rows 2");
    Cursor cursor = null;
    SQLiteDatabase db = getReadableDatabase();
    System.out.println("getting rows ");
    cursor = db.rawQuery("SELECT * FROM " + TABLE_QUEST1, null);
    if (!cursor.moveToFirst()) {
        System.out.println("No data in the database ");
    } else {
        System.out.println("theres data in the database ");
        quesList = new ArrayList<Question>();
        do {
            System.out.print("total rows " + cursor.getCount());
            Question quest = new Question();
            quest.setID(cursor.getInt(0));
            quest.setQuestion(cursor.getString(1));
            quest.setAnswer(cursor.getString(2));
            quest.setOptA(cursor.getString(3));
            quest.setOptB(cursor.getString(4));
            quest.setOptC(cursor.getString(5));
            quesList.add(quest);
        } while (cursor.moveToNext());
        cursor.close();
    }
}

I have 4 rows of data in my table and I can see that with the print statement "added in database"

but when i actually read it the cursor just reads row 1 and moves out of the while loop. what could potentially be wrong.

tia

Body:
As Santosh has pointed out DROPPING the table (as per db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST1);) and then re-creating it (as per onCreate(db);) will delete the table and then re-create the table removing any rows/data that had previously been added to the table.

As such it's simply a matter of removing those two lines of code, Also there appears to be no need for the line int id = 1;, so perhaps remove this,  as per :-

public void addQuestion(Question quest)
{
    ContentValues values = new ContentValues();
    SQLiteDatabase db = this.getWritableDatabase();
    values.put(KEY_QUES, quest.getQuestion());
    values.put(KEY_ANSWER, quest.getAnswer());
    values.put(KEY_OPTA, quest.getOptA());
    values.put(KEY_OPTB, quest.getOptB());
    values.put(KEY_OPTC, quest.getOptC());
    db.insert(TABLE_QUEST1, null, values);
    System.out.println("Added in database: " + quest.getQuestion());
}

P.S. you may consider not using hard coded column offsets but instead obtain offsets according to column names by utilising the getColumnIndex(column_name) Cursor method. e.g. :-

        Question quest = new Question();
        quest.setID(cursor.getInt(cursor.getColumnIndex("name_of_your_id_columm")));
        quest.setQuestion(cursor.getString(cursor.getColumnIndex(KEY_QUES)));
        quest.setAnswer(cursor.getString(cursor.getColumnIndex(KEY_ANSWER)));
        quest.setOptA(cursor.getString(cursor.getColumnIndex(KEY_OPTA)));
        quest.setOptB(cursor.getString(cursor.getColumnIndex(KEY_OPTB)));
        quest.setOptC(cursor.getString(cursor.getColumnIndex(KEY_OPTC)));
        quesList.add(quest);

Noting that instead of "name_of_your_id_columm", you may have something like KEY_ID defined, if so use that, thus you have a single definition so it reduces the chance of inadvertently mispelling column names or miscalculating the offsets.