问:
How to pass enum as method parameter?
The task is to write a simple method that can sort int array (in ascending or descending order - should be set as enum type parameter of this method). I have written the method itself and enum, but I have no idea how to set enum as method parameter:( </p>

<p>Would be great to get any help from you, guys, cause I am completely new to coding. </p>

```<code>class Program
{

    public enum options
    {
        UpSortOption,
        DownSortOption
    }

    public static void Main(string[] args)
    {
        int[] arr = new int[] { 3, 8, 0, 2, 16 };
    }

    static void orderArray(int [] array, options op)
    {
        switch(op)
        {
            case options.UpSortOption:
                Array.Sort(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

            case options.DownSortOption:
                Array.Sort(array);
                Array.Reverse(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

        }
    }
}
</code>```

答:
Let's take a step back to see if it helps your understanding.

If you have a method that takes a string and an int like this

```<code>string MyMethod(string str, int num)
{
    // Do something
}
</code>```

You'd use it like this

```<code>string rslt = MyMethod("Hello", 123);
</code>```

What you've got here is something that takes in some stuff, does something to it, and gives you something in return. In this case MyMethod takes a string and an int, does something with them and returns a string which you then call rslt.

Your example follows the same basic pattern so you need to take your method - orderArray and give it the two things it wants - an int array and an option like this

```<code>int[] arr = new int[] { 3, 8, 0, 2, 16 };

orderArray(arr, options.UpSortOption);
</code>```

Alternatively, you could create an options much like you'd create a string and then call your method like this

```<code>int[] arr = new int[] { 3, 8, 0, 2, 16 };
options myOption = options.UpSortOption;

orderArray(arr, myOption);
</code>```

To fully illustrate the point that an enum as a parameter isn't any different from say a string you could modify your method like this

```<code>static void orderArray(int[] array, string op)
{
    if (op == "UpSortOption")
    {
        Array.Sort(array);
        foreach (int number in array)
        {
            Console.Write(number + " ");
        }
    }
    else
    {
        Array.Sort(array);
        Array.Reverse(array);
        foreach (int number in array)
        {
            Console.Write(number + " ");
        }
    }
}
</code>```

Then call it like this

```<code>int[] arr = new int[] { 3, 8, 0, 2, 16 };
string myOption = "UpSortOption";

orderArray(arr, myOption);
</code>```

Title: How to pass enum as method parameter?

Body:
The task is to write a simple method that can sort int array (in ascending or descending order - should be set as enum type parameter of this method). I have written the method itself and enum, but I have no idea how to set enum as method parameter:(

Would be great to get any help from you, guys, cause I am completely new to coding.

class Program
{

    public enum options
    {
        UpSortOption,
        DownSortOption
    }

    public static void Main(string[] args)
    {
        int[] arr = new int[] { 3, 8, 0, 2, 16 };
    }

    static void orderArray(int [] array, options op)
    {
        switch(op)
        {
            case options.UpSortOption:
                Array.Sort(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

            case options.DownSortOption:
                Array.Sort(array);
                Array.Reverse(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

        }
    }
}

Body:
Let's take a step back to see if it helps your understanding.

If you have a method that takes a string and an int like this

string MyMethod(string str, int num)
{
    // Do something
}

You'd use it like this

string rslt = MyMethod("Hello", 123);

What you've got here is something that takes in some stuff, does something to it, and gives you something in return. In this case MyMethod takes a string and an int, does something with them and returns a string which you then call rslt.

Your example follows the same basic pattern so you need to take your method - orderArray and give it the two things it wants - an int array and an option like this

int[] arr = new int[] { 3, 8, 0, 2, 16 };

orderArray(arr, options.UpSortOption);

Alternatively, you could create an options much like you'd create a string and then call your method like this

int[] arr = new int[] { 3, 8, 0, 2, 16 };
options myOption = options.UpSortOption;

orderArray(arr, myOption);

To fully illustrate the point that an enum as a parameter isn't any different from say a string you could modify your method like this

static void orderArray(int[] array, string op)
{
    if (op == "UpSortOption")
    {
        Array.Sort(array);
        foreach (int number in array)
        {
            Console.Write(number + " ");
        }
    }
    else
    {
        Array.Sort(array);
        Array.Reverse(array);
        foreach (int number in array)
        {
            Console.Write(number + " ");
        }
    }
}

Then call it like this

int[] arr = new int[] { 3, 8, 0, 2, 16 };
string myOption = "UpSortOption";

orderArray(arr, myOption);


来源: stackexchange

问:
How to insert in .php?id= in my php code
Pls am new to programming

Pls sir I have being seeing this in many php files .php?id=3

But I don't understand how it works or how to put it in my code,

答:
This is called the query string, it's a way of passing parameters to your page.

You can access them in the php using the $_GET superglobal like so:

```<code>var_dump( $_GET['id'] );
</code>```

Tips for using query string variables:

Check it is set before trying to use it: isset($_GET['id']) because you can't be sure it will be there.

This is "user input" and so you should not trust it implicitly. Whatever you do with user input you should use the appropriate security mechanism to sanitize it to prevent vulnerabilities.

If you generate a link with dynamic query string variables then be sure to use URL encoding/Percent encoding which can be done with urlencode().

ContentLicense: CC BY-SA 3.0

Body:
This is called the query string, it's a way of passing parameters to your page.

You can access them in the php using the $_GET superglobal like so:

var_dump( $_GET['id'] );

Tips for using query string variables:

Check it is set before trying to use it: isset($_GET['id']) because you can't be sure it will be there.

This is "user input" and so you should not trust it implicitly. Whatever you do with user input you should use the appropriate security mechanism to sanitize it to prevent vulnerabilities.

If you generate a link with dynamic query string variables then be sure to use URL encoding/Percent encoding which can be done with urlencode().


问:
Why does Spark not allocate new YARN containers when current memory level is not sufficient?
I have Cloudera Cluster With the YARN capacity of 600 Vcores and 3600 GiB of Memory.  But Admin team has configured the maximum memory for yarn container to be 6 GB. My User has as permission to allocate as many containers as he can .

When i Try to run a spark Job on data set of size 50 Gb Job fails with error of Executor Memory Overhead.

When one container Memory isnt sufficient why cant spark try for new container?

答:
When one container Memory isnt sufficient why cant spark try for new container?

...because Spark does not do this by default (and you have not configured it otherwise).

The number of executors and more importantly the total number of CPU cores and RAM memory is controlled by you at spark-submit time. That's where --driver-memory, --executor-memory, --driver-cores, --total-executor-cores, --executor-cores, --num-executors and others.

```<code>$ ./bin/spark-submit --help
...
  --driver-memory MEM         Memory for driver (e.g. 1000M, 2G) (Default: 1024M).
  --driver-java-options       Extra Java options to pass to the driver.
  --driver-library-path       Extra library path entries to pass to the driver.
  --driver-class-path         Extra class path entries to pass to the driver. Note that
                              jars added with --jars are automatically included in the
                              classpath.

  --executor-memory MEM       Memory per executor (e.g. 1000M, 2G) (Default: 1G).
...
 Spark standalone with cluster deploy mode only:
  --driver-cores NUM          Cores for driver (Default: 1).
...
 Spark standalone and Mesos only:
  --total-executor-cores NUM  Total cores for all executors.

 Spark standalone and YARN only:
  --executor-cores NUM        Number of cores per executor. (Default: 1 in YARN mode,
                              or all available cores on the worker in standalone mode)

 YARN-only:
  --driver-cores NUM          Number of cores used by the driver, only in cluster mode
                              (Default: 1).
  --queue QUEUE_NAME          The YARN queue to submit to (Default: "default").
  --num-executors NUM         Number of executors to launch (Default: 2).
                              If dynamic allocation is enabled, the initial number of
                              executors will be at least NUM.
...
</code>```

Some are deploy mode-specific while others depend on the cluster manager in use (which would be YARN in your case).

Wrapping up...it's you to decide how many resources to assign to a Spark application using spark-submit's options.

Read up on Submitting Applications in the official documentation of Spark.

Body:
When one container Memory isnt sufficient why cant spark try for new container?

...because Spark does not do this by default (and you have not configured it otherwise).

The number of executors and more importantly the total number of CPU cores and RAM memory is controlled by you at spark-submit time. That's where --driver-memory, --executor-memory, --driver-cores, --total-executor-cores, --executor-cores, --num-executors and others.

$ ./bin/spark-submit --help
...
  --driver-memory MEM         Memory for driver (e.g. 1000M, 2G) (Default: 1024M).
  --driver-java-options       Extra Java options to pass to the driver.
  --driver-library-path       Extra library path entries to pass to the driver.
  --driver-class-path         Extra class path entries to pass to the driver. Note that
                              jars added with --jars are automatically included in the
                              classpath.

  --executor-memory MEM       Memory per executor (e.g. 1000M, 2G) (Default: 1G).
...
 Spark standalone with cluster deploy mode only:
  --driver-cores NUM          Cores for driver (Default: 1).
...
 Spark standalone and Mesos only:
  --total-executor-cores NUM  Total cores for all executors.

 Spark standalone and YARN only:
  --executor-cores NUM        Number of cores per executor. (Default: 1 in YARN mode,
                              or all available cores on the worker in standalone mode)

 YARN-only:
  --driver-cores NUM          Number of cores used by the driver, only in cluster mode
                              (Default: 1).
  --queue QUEUE_NAME          The YARN queue to submit to (Default: "default").
  --num-executors NUM         Number of executors to launch (Default: 2).
                              If dynamic allocation is enabled, the initial number of
                              executors will be at least NUM.
...

Some are deploy mode-specific while others depend on the cluster manager in use (which would be YARN in your case).

Wrapping up...it's you to decide how many resources to assign to a Spark application using spark-submit's options.

Read up on Submitting Applications in the official documentation of Spark.


答: This ran without error with cv libraries FindHomography as opposed to cv2 FindHomography. The issue must be with cv2 v2.4.9</p>

Title: python opencv2 findHomography

Body:
Using opencv2 - 2.4.9  I get the following error when attempting to compute a homography matrix with cv2.findHomography. There is something obviously wrong with the values that I am using, in particular the rect_points matrix. If I change the values of the matrix to make them smaller the computation succeeds on some matrices.

(Pdb) findHomography(pts_dst,pts_src)
(array([[  1.80258009e+00,   1.55276411e+00,  -7.76398173e+02],
       [ -8.09994414e-01,   2.13295256e+00,  -1.07909987e+02],
       [  5.79313440e-04,   7.57830547e-04,   1.00000000e+00]]), array([[1],
       [1],
       [1],
       [1]], dtype=uint8))
(Pdb) findHomography(tc,pts_dst)
(array([[  5.86310680e-01,  -1.02457072e+00,   3.18000000e+02],
       [  2.73257186e-01,   4.37679421e-01,   2.56000000e+02],
       [ -4.88292404e-04,  -8.73786408e-04,   1.00000000e+00]]), array([[1],
       [1],
       [1],
       [1]], dtype=uint8))
(Pdb) findHomography(rect_points/2,tc)
(array([[  3.12565925e+00,  -4.01560389e-01,  -1.46710631e+02],
       [  6.46267255e-01,   3.94065399e-01,  -7.32725203e+01],
       [ -1.24144088e-02,   9.62934110e-04,   1.00000000e+00]]), array([[1],
       [1],
       [1],
       [1]], dtype=uint8))
(Pdb) findHomography(rect_points-50,tc)
(array([[  2.18971678e+00,  -2.81317781e-01,  -1.10139713e+02],
       [  4.52750009e-01,   2.76067079e-01,  -6.62229708e+01],
       [ -8.69705784e-03,   6.74594641e-04,   1.00000000e+00]]), array([[1],
       [1],
       [1],
       [1]], dtype=uint8))
(Pdb) findHomography(rect_points,tc)
OpenCV Error: Assertion failed (npoints >= 0 && points2.checkVector(2) == npoints && points1.type() == points2.type()) in findHomography, file /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/calib3d/src/fundam.cpp, line 1074
*** error: /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/calib3d/src/fundam.cpp:1074: error: (-215) npoints >= 0 && points2.checkVector(2) == npoints && points1.type() == points2.type() in function findHomography

    (Pdb) rect_points
    array([[ 117.,  180.],
           [ 142.,  139.],
           [ 160.,  314.],
           [ 154.,  468.]], dtype=float32)
    (Pdb) tc
    array([[   0.,    0.],
           [ 255.,    0.],
           [ 255.,  255.],
           [   0.,  255.]], dtype=float32)
    (Pdb)

(Pdb) pts_src
array([[ 141.,  131.],
       [ 480.,  159.],
       [ 493.,  630.],
       [  64.,  601.]], dtype=float32)
(Pdb) pts_dst
array([[ 318.,  256.],
       [ 534.,  372.],
       [ 316.,  670.],
       [  73.,  473.]], dtype=float32)
(Pdb)


问:
ORDER BY the IN value list
I have a simple SQL query in PostgreSQL 8.3 that grabs a bunch of comments. I provide a sorted list of values to the IN construct in the WHERE clause:

```<code>SELECT * FROM comments WHERE (comments.id IN (1,3,2,4));
</code>```

This returns comments in an arbitrary order which in my happens to be ids like 1,2,3,4.

I want the resulting rows sorted like the list in the IN construct: (1,3,2,4).

How to achieve that?

答:
```<code>select * from comments where comments.id in
(select unnest(ids) from bbs where id=19795)
order by array_position((select ids from bbs where id=19795),comments.id)
</code>```

here, [bbs] is the main table that has a field called ids,
and, ids is the array that store the comments.id .

passed in postgresql 9.6

Title: ORDER BY the IN value list

Body:
I have a simple SQL query in PostgreSQL 8.3 that grabs a bunch of comments. I provide a sorted list of values to the IN construct in the WHERE clause:

SELECT * FROM comments WHERE (comments.id IN (1,3,2,4));

This returns comments in an arbitrary order which in my happens to be ids like 1,2,3,4.

I want the resulting rows sorted like the list in the IN construct: (1,3,2,4).

How to achieve that?

Body:
select * from comments where comments.id in
(select unnest(ids) from bbs where id=19795)
order by array_position((select ids from bbs where id=19795),comments.id)

here, [bbs] is the main table that has a field called ids,
and, ids is the array that store the comments.id .

passed in postgresql 9.6


问:
Magento Installation stuck at configuration
I am not sure what is going wrong when I am trying to install magento to my local ubuntu machine.
I did all the steps mentionsed in the magento wiki. Everything goes well until I reach the point where I am here which is the magento config page. When I try and continue after entering the necessary details like host, database name and user name and submit it comes back to the same page. I checked for everything like db in my phomyadmin panel and it still gets stuck there. What is the possible reason for that.

Thanks

答:
You have to create a database first and then proceed further.

Step 1 - First create a database with name of your choice like magento

Step 2 - Use that database name in the installation form now

Step 3 - Continue

Hope this solves your problem.

ContentLicense: CC BY-SA 2.5


问:
How do I create a link to pre-select a form option
I have the following code on another webpage on my site with a form (say on page index.html): JSFiddle

```<code><select class="select form-control" id="dropdown" name="dropdown" onchange="showForm()">
</code>```

i.e a dropdown form.

I want to have a link on another webpage that will go to this page, and have the "Sales" option already selected.

```<code><option value="1">
    Sales
</option>
</code>```

from the drop down menu (instead of the current default option), how do I create this?

答:
Try with append() function of jquery .and pass this with in onchange function call .And also added with document.ready for create the link on document load with selected value

function showForm(that){
var s = $(that).children('option:selected').text()
$('#link_box').append(''+s+'
')
}
$(document).ready(function(){ // for window load
showForm($('select'))
})```
<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>
<div class="form-group ">
  <label class="control-label" for="dropdown">
       What can we help you with?

      </label>
  <select class="select form-control" id="dropdown" name="dropdown" onchange="showForm(this)">
       <option value="0" disabled>
   Select an option
       </option>
       <option value="1" selected>
     Sales
       </option>
       <option value="2">
     Complaints
       </option>
       <option value="3">
     Queries
       </option>
       <option value="4">
     Ideas
       </option>
      </select>
</div>
<div id="link_box">
<!-- its a link append  box-->
</div></code>```

Body:
I have the following code on another webpage on my site with a form (say on page index.html): JSFiddle

<select class="select form-control" id="dropdown" name="dropdown" onchange="showForm()">

i.e a dropdown form.

I want to have a link on another webpage that will go to this page, and have the "Sales" option already selected.

<option value="1">
    Sales
</option>

from the drop down menu (instead of the current default option), how do I create this?

Body:
Try with append() function of jquery .and pass this with in onchange function call .And also added with document.ready for create the link on document load with selected value

function showForm(that){
var s = $(that).children('option:selected').text()
$('#link_box').append('<a href="'+s+'">'+s+'</a></br>')
}
$(document).ready(function(){ // for window load
showForm($('select'))
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group ">
  <label class="control-label" for="dropdown">
       What can we help you with?

      </label>
  <select class="select form-control" id="dropdown" name="dropdown" onchange="showForm(this)">
       <option value="0" disabled>
   Select an option
       </option>
       <option value="1" selected>
     Sales
       </option>
       <option value="2">
     Complaints
       </option>
       <option value="3">
     Queries
       </option>
       <option value="4">
     Ideas
       </option>
      </select>
</div>
<div id="link_box">
<!-- its a link append  box-->
</div>


问:
Why some methods in JavaScript make a copy of the object invoked?
In JavaScript, some methods make a copy of the object that invoked it while others do not.

For example:

```<code>var numbers = [1, 2, 3, 4, 5];
numbers.map(function(x) { return x + 1 });
console.log(numbers); // [1, 2, 3, 4, 5];
</code>```

It makes a copy of "numbers" that you have to set to another variable.

Whereas:

```<code>var numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1];
</code>```

It changes the "numbers" directly. Could anyone please explain why?

答:
The array methods in javascript is broadly classified into three
- Mutator methods
- Accessor methods
- Iteration methods

Mutator methods - Ex : reverse(), push () etc : modify the array . As the name suggest these methods mutates the array on which they are called upon.

Accessor methods - Ex : include(), concat() etc : - do not modify the array and return some representation of the array.i.e a new array is returned which is modified array.

Iteration methods -Ex : filter(), map()- take as arguments functions to be called back while processing the array. In these methods the length of the array is already sampled/copied and the callback is performed on this arrary.

Generic methods (non-standard) - EX: join() These methods are generic in nature and is applicable to objects which “look like” Arrays.

The detailed explanation on this can be found in the below link :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype

Hope this helps!!!

Body:
In JavaScript, some methods make a copy of the object that invoked it while others do not.

For example:

var numbers = [1, 2, 3, 4, 5];
numbers.map(function(x) { return x + 1 });
console.log(numbers); // [1, 2, 3, 4, 5];

It makes a copy of "numbers" that you have to set to another variable.

Whereas:

var numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1];

It changes the "numbers" directly. Could anyone please explain why?


问:
Copy and replace multiple files (with their full path) from one directory to another directory's corresponding paths
Say I have two folders : SOURCE and DEST

I have been provided with relative path of bunch of files of SOURCE. e.g

```<code>SOURCE/A/B/C/file1.cpp
SOURCE/A/B/D/file2.cpp
SOURCE/M/B/G/file3.cpp
...
</code>```

to replace the corresponding files in DEST directory

```<code>DEST/A/B/C/file1.cpp
DEST/A/B/D/file2.cpp
DEST/M/B/G/file3.cpp
...
</code>```

Can I achieve this with minimal effort using command prompt?

FYI, usually I need to repeatedly go back and forth from SOURCE to DEST to copy each individual file, which is very time consuming and error prone.

答:
There is robocopy utility, which can help you to do what you want:</p>

```<code>robocopy <Original Folder> <Destination Folder> /mir
</code>```

Body:
Say I have two folders : SOURCE and DEST

I have been provided with relative path of bunch of files of SOURCE. e.g

SOURCE/A/B/C/file1.cpp
SOURCE/A/B/D/file2.cpp
SOURCE/M/B/G/file3.cpp
...

to replace the corresponding files in DEST directory

DEST/A/B/C/file1.cpp
DEST/A/B/D/file2.cpp
DEST/M/B/G/file3.cpp
...

Can I achieve this with minimal effort using command prompt?

FYI, usually I need to repeatedly go back and forth from SOURCE to DEST to copy each individual file, which is very time consuming and error prone.

Body:
There is robocopy utility, which can help you to do what you want:

robocopy <Original Folder> <Destination Folder> /mir


问:
QSerialPort with thread
I have been struggling a project that it communicates through the serial port in Qt for around two weeks. First I tried signal/slot method, it missed some data. Then I decided to use a thread for this, but I got the same result. While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data. Please help me this condition.

The MainWindow Constructor:

```<code>SerialPort *serial= new SerialPort();
serial->moveToThread(&cThread);

connect(this , &MainWindow::finished, &cThread, &QThread::quit);
connect(this , &MainWindow::destroyed, this, &SerialPort::deleteLater);
connect(serial, &SerialPort::getData, this, &MainWindow::displayData);

cThread.start();
</code>```

The Serial Port read thread:

```<code>void SerialPort::newData()
{
     mutex.lock();
     bArray.insert(bArray.length(),serial->readAll());
     mutex.unlock();

     emit getData(&bArray,&mutex);
}
</code>```

The SerialPort Constructor:

```<code>serial = new QSerialPort();
connect(serial, &QSerialPort::readyRead, this,  &SerialPort::newData);

bArray.clear();

fill_serial_ports();
portName = find_stm32_port();

serial->setReadBufferSize(20*1024*1024); // it's a huge buffer.
bArray.reserve(20*1024*1024);  // it's a huge buffer.

open_serial_port();
</code>```

Also, I thought that this can be a bug what misses some data and wrote to the bug tracker. Assignee said that QSerialPort never loses data furthermore, my code is wrong. I'm very confused, I don't know where to make mistakes. Please, could you check my other solution? Where is the mistake?

My bug tracker report (Not accepted) : https://bugreports.qt.io/browse/QTBUG-61233

答:
As it's been clarified in the comment, the problem is that

The USBCan device is giving an error about can't send data, so its error led is becoming on.

Try adding the following line right after creating QSerialPort instance serial:

```<code>serial->setFlowControl(QSerialPort::HardwareControl);
</code>```

If your device supports RFC232 standard, this should enable RTS (Request to Send / CTS (Clear to Send) lines and cause your transmitter to request for the receiver's readiness before sending any data. See here for details.

Title: QSerialPort with thread

Body:
I have been struggling a project that it communicates through the serial port in Qt for around two weeks. First I tried signal/slot method, it missed some data. Then I decided to use a thread for this, but I got the same result. While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data. Please help me this condition.

The MainWindow Constructor:

SerialPort *serial= new SerialPort();
serial->moveToThread(&cThread);

connect(this , &MainWindow::finished, &cThread, &QThread::quit);
connect(this , &MainWindow::destroyed, this, &SerialPort::deleteLater);
connect(serial, &SerialPort::getData, this, &MainWindow::displayData);

cThread.start();

The Serial Port read thread:

void SerialPort::newData()
{
     mutex.lock();
     bArray.insert(bArray.length(),serial->readAll());
     mutex.unlock();

     emit getData(&bArray,&mutex);
}

The SerialPort Constructor:

serial = new QSerialPort();
connect(serial, &QSerialPort::readyRead, this,  &SerialPort::newData);

bArray.clear();

fill_serial_ports();
portName = find_stm32_port();

serial->setReadBufferSize(20*1024*1024); // it's a huge buffer.
bArray.reserve(20*1024*1024);  // it's a huge buffer.

open_serial_port();

Also, I thought that this can be a bug what misses some data and wrote to the bug tracker. Assignee said that QSerialPort never loses data furthermore, my code is wrong. I'm very confused, I don't know where to make mistakes. Please, could you check my other solution? Where is the mistake?

My bug tracker report (Not accepted) : https://bugreports.qt.io/browse/QTBUG-61233

Body:
As it's been clarified in the comment, the problem is that

The USBCan device is giving an error about can't send data, so its error led is becoming on.

Try adding the following line right after creating QSerialPort instance serial:

serial->setFlowControl(QSerialPort::HardwareControl);

If your device supports RFC232 standard, this should enable RTS (Request to Send / CTS (Clear to Send) lines and cause your transmitter to request for the receiver's readiness before sending any data. See here for details.


问:
Unable to build Chromium for Android on Ubuntu 13.10 64 bit
I have Ubuntu 13.10 64 bit OS and i just try to build android content shell by this Step from Code.google.com

Following Steps and command are running fine in my Ubuntu system.

```<code>gclient sync --nohooks
. build/android/envsetup.sh
gclient runhooks
</code>```

I have also update my android build script as per issue patch from this https://codereview.chromium.org/222183002/#ps20001 so as per that two patch i update my install-build-deps-android.sh which located as src/build/install-build-deps-android.sh

According to this SO answer -->failures-during-chromium-build-on-ubuntu

i have set all this as well :

```<code>sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk1.8.0/bin/javac 50000
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk1.8.0/bin/java 50000
sudo update-alternatives --install /usr/bin/javaws javaws /usr/lib/jvm/jdk1.8.0/bin/javaws 50000
sudo update-alternatives --install /usr/bin/javap javap /usr/lib/jvm/jdk1.8.0/bin/javap 50000
sudo update-alternatives --install /usr/bin/jar jar /usr/lib/jvm/jdk1.8.0/bin/jar 50000
sudo update-alternatives --install /usr/bin/jarsigner jarsigner /usr/lib/jvm/jdk1.8.0/bin/jarsigner 50000

 ninja -C out/Release content_shell_apk
ninja: Entering directory `out/Release'
ninja: warning: multiple rules generate icudtl.dat. builds involving this target will not be correct; continuing anyway
[16/10277] ACTION Generating JNI bindings f...roid-19/android.jar/java/util/HashSet.class
FAILED: cd ../../content; ../base/android/jni_generator/jni_generator.py -j /home/ubbvand2/himanshu/FreshCheckout/src/third_party/android_tools/sdk//platforms/android-19/android.jar --input_file java/util/HashSet.class --output_dir ../out/Release/gen/content/jni --includes base/android/jni_generator/jni_generator_helper.h --optimize_generation 0
Traceback (most recent call last):
  File "../base/android/jni_generator/jni_generator.py", line 1346, in <module>
    sys.exit(main(sys.argv))
  File "../base/android/jni_generator/jni_generator.py", line 1342, in main
    GenerateJNIHeader(input_file, output_file, options)
  File "../base/android/jni_generator/jni_generator.py", line 1230, in GenerateJNIHeader
    jni_from_javap = JNIFromJavaP.CreateFromClass(input_file, options)
  File "../base/android/jni_generator/jni_generator.py", line 576, in CreateFromClass
    jni_from_javap = JNIFromJavaP(stdout.split('\n'), options)
  File "../base/android/jni_generator/jni_generator.py", line 524, in __init__
    signature=JniParams.ParseJavaPSignature(contents[lineno + 1]))]
  File "../base/android/jni_generator/jni_generator.py", line 172, in ParseJavaPSignature
    return '"%s"' % signature_line[signature_line.index(prefix) + len(prefix):]
ValueError: substring not found
[16/10277] ACTION Generating JNI bindings f.../android.jar/android/view/MotionEvent.class
FAILED: cd ../../content; ../base/android/jni_generator/jni_generator.py -j /home/ubbvand2/himanshu/FreshCheckout/src/third_party/android_tools/sdk//platforms/android-19/android.jar --input_file android/view/MotionEvent.class --output_dir ../out/Release/gen/content/jni --includes base/android/jni_generator/jni_generator_helper.h --optimize_generation 0
Traceback (most recent call last):
  File "../base/android/jni_generator/jni_generator.py", line 1346, in <module>
    sys.exit(main(sys.argv))
  File "../base/android/jni_generator/jni_generator.py", line 1342, in main
    GenerateJNIHeader(input_file, output_file, options)
  File "../base/android/jni_generator/jni_generator.py", line 1230, in GenerateJNIHeader
    jni_from_javap = JNIFromJavaP.CreateFromClass(input_file, options)
  File "../base/android/jni_generator/jni_generator.py", line 576, in CreateFromClass
    jni_from_javap = JNIFromJavaP(stdout.split('\n'), options)
  File "../base/android/jni_generator/jni_generator.py", line 524, in __init__
    signature=JniParams.ParseJavaPSignature(contents[lineno + 1]))]
  File "../base/android/jni_generator/jni_generator.py", line 172, in ParseJavaPSignature
    return '"%s"' % signature_line[signature_line.index(prefix) + len(prefix):]
ValueError: substring not found
[16/10277] CC obj/third_party/icu/source/common/icuuc.ucnvmbcs.o
ninja: build stopped: subcommand failed.
</code>```

Can any one known how to come out from this issue.

答: I meet this problem, and the reason is use the make version 4.x, when change to make v3.81, it's ok.</p>

Body:
I have Ubuntu 13.10 64 bit OS and i just try to build android content shell by this Step from Code.google.com

Following Steps and command are running fine in my Ubuntu system.

gclient sync --nohooks
. build/android/envsetup.sh
gclient runhooks

I have also update my android build script as per issue patch from this https://codereview.chromium.org/222183002/#ps20001 so as per that two patch i update my install-build-deps-android.sh which located as src/build/install-build-deps-android.sh

According to this SO answer -->failures-during-chromium-build-on-ubuntu

i have set all this as well :

sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk1.8.0/bin/javac 50000
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk1.8.0/bin/java 50000
sudo update-alternatives --install /usr/bin/javaws javaws /usr/lib/jvm/jdk1.8.0/bin/javaws 50000
sudo update-alternatives --install /usr/bin/javap javap /usr/lib/jvm/jdk1.8.0/bin/javap 50000
sudo update-alternatives --install /usr/bin/jar jar /usr/lib/jvm/jdk1.8.0/bin/jar 50000
sudo update-alternatives --install /usr/bin/jarsigner jarsigner /usr/lib/jvm/jdk1.8.0/bin/jarsigner 50000

 ninja -C out/Release content_shell_apk
ninja: Entering directory `out/Release'
ninja: warning: multiple rules generate icudtl.dat. builds involving this target will not be correct; continuing anyway
[16/10277] ACTION Generating JNI bindings f...roid-19/android.jar/java/util/HashSet.class
FAILED: cd ../../content; ../base/android/jni_generator/jni_generator.py -j /home/ubbvand2/himanshu/FreshCheckout/src/third_party/android_tools/sdk//platforms/android-19/android.jar --input_file java/util/HashSet.class --output_dir ../out/Release/gen/content/jni --includes base/android/jni_generator/jni_generator_helper.h --optimize_generation 0
Traceback (most recent call last):
  File "../base/android/jni_generator/jni_generator.py", line 1346, in <module>
    sys.exit(main(sys.argv))
  File "../base/android/jni_generator/jni_generator.py", line 1342, in main
    GenerateJNIHeader(input_file, output_file, options)
  File "../base/android/jni_generator/jni_generator.py", line 1230, in GenerateJNIHeader
    jni_from_javap = JNIFromJavaP.CreateFromClass(input_file, options)
  File "../base/android/jni_generator/jni_generator.py", line 576, in CreateFromClass
    jni_from_javap = JNIFromJavaP(stdout.split('\n'), options)
  File "../base/android/jni_generator/jni_generator.py", line 524, in __init__
    signature=JniParams.ParseJavaPSignature(contents[lineno + 1]))]
  File "../base/android/jni_generator/jni_generator.py", line 172, in ParseJavaPSignature
    return '"%s"' % signature_line[signature_line.index(prefix) + len(prefix):]
ValueError: substring not found
[16/10277] ACTION Generating JNI bindings f.../android.jar/android/view/MotionEvent.class
FAILED: cd ../../content; ../base/android/jni_generator/jni_generator.py -j /home/ubbvand2/himanshu/FreshCheckout/src/third_party/android_tools/sdk//platforms/android-19/android.jar --input_file android/view/MotionEvent.class --output_dir ../out/Release/gen/content/jni --includes base/android/jni_generator/jni_generator_helper.h --optimize_generation 0
Traceback (most recent call last):
  File "../base/android/jni_generator/jni_generator.py", line 1346, in <module>
    sys.exit(main(sys.argv))
  File "../base/android/jni_generator/jni_generator.py", line 1342, in main
    GenerateJNIHeader(input_file, output_file, options)
  File "../base/android/jni_generator/jni_generator.py", line 1230, in GenerateJNIHeader
    jni_from_javap = JNIFromJavaP.CreateFromClass(input_file, options)
  File "../base/android/jni_generator/jni_generator.py", line 576, in CreateFromClass
    jni_from_javap = JNIFromJavaP(stdout.split('\n'), options)
  File "../base/android/jni_generator/jni_generator.py", line 524, in __init__
    signature=JniParams.ParseJavaPSignature(contents[lineno + 1]))]
  File "../base/android/jni_generator/jni_generator.py", line 172, in ParseJavaPSignature
    return '"%s"' % signature_line[signature_line.index(prefix) + len(prefix):]
ValueError: substring not found
[16/10277] CC obj/third_party/icu/source/common/icuuc.ucnvmbcs.o
ninja: build stopped: subcommand failed.

Can any one known how to come out from this issue.


问:
Comparing same date is giving me -1 in JAVA
I am comparing two same date and output that I am getting is -1. As far as I know it should be 0 for same date.

The image from the debug mode is attached here. How could this issue will be solved?

答:
You can use this post to compare two date without time like this.</p>

```<code>if (removeTime(questionDate).equals(removeTime(today))
  ...

public Date removeTime(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}
</code>```

Body:
You can use this post to compare two date without time like this.

if (removeTime(questionDate).equals(removeTime(today))
  ...

public Date removeTime(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}


问:
Getting Mail Through `PHP IMAP`
Here is my code for get sent mails

```<code>    $inbox = imap_open('{'.$domainURL.':143/notls}INBOX.Sent',$emailAddress,$emailPassword) or die('Cannot connect to domain:' . imap_last_error());
</code>```

But it doesnot return sent mails..When i try to print the response it shows only the number of sent messages..below is that..

```<code>Array ( [0] => 1 )
</code>```

答:
For retreive  Domain Server Mail

```<code>{domain.com:993/imap/ssl/novalidate-cert}INBOX
</code>```

For retreive  Gmail

```<code>{imap.gmail.com:993/imap/ssl}INBOX
</code>```

Title: Getting Mail Through `PHP IMAP`

Body:
Here is my code for get sent mails

    $inbox = imap_open('{'.$domainURL.':143/notls}INBOX.Sent',$emailAddress,$emailPassword) or die('Cannot connect to domain:' . imap_last_error());

But it doesnot return sent mails..When i try to print the response it shows only the number of sent messages..below is that..

Array ( [0] => 1 )

Body:
For retreive  Domain Server Mail

{domain.com:993/imap/ssl/novalidate-cert}INBOX

For retreive  Gmail

{imap.gmail.com:993/imap/ssl}INBOX


问:
SPARQL Wikidata - Retrieve members of Wikimedia Category
I want to retrieve the members of the Wikimedia Category American rock singers. I must use Wikidata and it tells me to use P31 with Q4167836 . The query below only returns information about the Category page and not about its members.

Is there any other way to retrieve the members of the Wikimedia Category? I also tried using the term dcterms:subject, which I use successfully with DBpedia, but in Wikidata the query returns empty results.

```<code>prefix wdt: <http://www.wikidata.org/prop/direct/>
prefix wd: <http://www.wikidata.org/entity/>
prefix wikibase: <http://wikiba.se/ontology#>
prefix bd: <http://www.bigdata.com/rdf#>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?subject ?predicate ?object ?objectLabel WHERE {
     ?subject ?predicate ?object ; wdt:P31 wd:Q4167836 ;
     rdfs:label "Category:American rock singers"@en
SERVICE wikibase:label { bd:serviceParam wikibase:language "en" .}
}
</code>```

Try here

答:
Try this query on Wikidata:

SELECT ?subjectLabel WHERE {
    ?subject wdt:P27 wd:Q30;
             wdt:P136 wd:Q11399 .
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en" .}
}
```

<p>Or try this query on DBpedia (as Mark Miller linked to):</p>

<pre class="lang-sql prettyprint-override"><code>SELECT str(?label) WHERE {
  ?subject dct:subject dbc:American_rock_singers ;
           rdfs:label ?label .
  FILTER (lang(?label) = "en")
}
</code>```

Or if you must use Wikidata, try this federated query on Wikidata:

PREFIX dbc: <http://dbpedia.org/resource/Category:>
PREFIX dct: <http://purl.org/dc/terms/>
SELECT ?wsubjectLabel WHERE {
    SERVICE <http://dbpedia.org/sparql> {
         ?subject dct:subject dbc:American_rock_singers .
         ?subject owl:sameAs ?wsubject .
         FILTER (STRSTARTS(STR(?wsubject), "http://www.wikidata.org"))
    }
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
```

Body:
I want to retrieve the members of the Wikimedia Category American rock singers. I must use Wikidata and it tells me to use P31 with Q4167836 . The query below only returns information about the Category page and not about its members.

Is there any other way to retrieve the members of the Wikimedia Category? I also tried using the term dcterms:subject, which I use successfully with DBpedia, but in Wikidata the query returns empty results.

prefix wdt: <http://www.wikidata.org/prop/direct/>
prefix wd: <http://www.wikidata.org/entity/>
prefix wikibase: <http://wikiba.se/ontology#>
prefix bd: <http://www.bigdata.com/rdf#>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?subject ?predicate ?object ?objectLabel WHERE {
     ?subject ?predicate ?object ; wdt:P31 wd:Q4167836 ;
     rdfs:label "Category:American rock singers"@en
SERVICE wikibase:label { bd:serviceParam wikibase:language "en" .}
}

Try <a href="https://query.wikidata.org/#prefix%20wdt%3A%20%3Chttp%3A%2F%2Fwww.wikidata.org%2Fprop%2Fdirect%2F%3E%0Aprefix%20wd%3A%20%3Chttp%3A%2F%2Fwww.wikidata.org%2Fentity%2F%3E%0Aprefix%20wikibase%3A%20%3Chttp%3A%2F%2Fwikiba.se%2Fontology%23%3E%0Aprefix%20bd%3A%20%3Chttp%3A%2F%2Fwww.bigdata.com%2Frdf%23%3E%0Aprefix%20rdfs%3A%20%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%20%0ASELECT%20DISTINCT%20%3Fsubject%20%3Fpredicate%20%3Fobject%20%3FobjectLabel%20WHERE%20%7B%0A%09%3Fsubject%20%3Fpredicate%20%3Fobject%20%3B%20wdt%3AP31%20wd%3AQ4167836%20%3B%20rdfs%3Alabel%20%22Category%3AAmerican%20rock%20singers%22%40en%20%0ASERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22%20.%7D%0A%7D%0A" rel="noreferrer">here

Body:
Try this query on Wikidata:

SELECT ?subjectLabel WHERE {
    ?subject wdt:P27 wd:Q30;
             wdt:P136 wd:Q11399 .
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en" .}
}

Or try this query on DBpedia (as Mark Miller linked to):

SELECT str(?label) WHERE {
  ?subject dct:subject dbc:American_rock_singers ;
           rdfs:label ?label .
  FILTER (lang(?label) = "en")
}

Or if you must use Wikidata, try this federated query on Wikidata:

PREFIX dbc: <http://dbpedia.org/resource/Category:>
PREFIX dct: <http://purl.org/dc/terms/>
SELECT ?wsubjectLabel WHERE {
    SERVICE <http://dbpedia.org/sparql> {
         ?subject dct:subject dbc:American_rock_singers .
         ?subject owl:sameAs ?wsubject .
         FILTER (STRSTARTS(STR(?wsubject), "http://www.wikidata.org"))
    }
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}


问:
Python and pytest testing
I have to do some testing using pytest, but I have no idea where to start.
Here is piece of a code which i would like to test:

```<code>def print_url_and_id():
    for item in movie_link[:100]:
        print item.contents[1], "The ID of this movie is:", '"' + item.contents[1]['href'][7:16] + '"'
</code>```

Could anyone tell me how it suppose to look like?

答:
You can do something like this:</p>

```<code>import pytest

def parametrized():
    expected_results = ["movie_link_01", "movie_link_02"]
    movie_link = ["movie_link_01", "movie_link_02", "movie_link_03"]
    # you can define your new_movie_link list like this as you have done, but instead of
    # printing it, add it to a this new_movie_link list
    return [(item_1, item_2) for item_1, item_2 in zip(movie_link[:2], expected_results)]

@pytest.mark.parametrize("movie_link, expected", parametrized())
def test_parametrizer(movie_link, expected):
    assert movie_link == expected
</code>```

Title: Python and pytest testing

Body:
I have to do some testing using pytest, but I have no idea where to start.
Here is piece of a code which i would like to test:

def print_url_and_id():
    for item in movie_link[:100]:
        print item.contents[1], "The ID of this movie is:", '"' + item.contents[1]['href'][7:16] + '"'

Could anyone tell me how it suppose to look like?

Body:
You can do something like this:

import pytest

def parametrized():
    expected_results = ["movie_link_01", "movie_link_02"]
    movie_link = ["movie_link_01", "movie_link_02", "movie_link_03"]
    # you can define your new_movie_link list like this as you have done, but instead of
    # printing it, add it to a this new_movie_link list
    return [(item_1, item_2) for item_1, item_2 in zip(movie_link[:2], expected_results)]

@pytest.mark.parametrize("movie_link, expected", parametrized())
def test_parametrizer(movie_link, expected):
    assert movie_link == expected


问:
How do I bind resource strings in XAML to multiple attributes within the same control?
Is it possible to bind an additional resource string to another attribute within a control. I already have one attribute bound to a resource but also need another. I can't see a way of doing it as I would need an extra DataContext but oviously can only have one.

The additional attribute I need to bind to is Content within the hyperlink control.

The xaml file is as follows:-

```<code><UserControl x:Class="SilverlightApplication1.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mystuff="clr-namespace:my.assembly.name;assembly=my.assembly.name"
    Width="100" Height="100">

    <UserControl.Resources>
        <mystuff:TxtResConv x:Key="TxtResConv" />
        <mystuff:TxtResPar x:Key="LabelTitle" ResourceUri="LabelTitle" DefaultValue="default label title" />
        <mystuff:TxtResPar x:Key="LinkURL" ResourceUri="LinkURL"  DefaultValue="default label title" />
    </UserControl.Resources>

   <Grid x:Name="LayoutRoot" Background="White">
            <HyperlinkButton DataContext="{StaticResource LinkURL}" x:Name="HyperLink1" Content="NEED TO ADD RESOURCE STRING LABELTITLE HERE !!" NavigateUri="{Binding Mode=OneWay,Converter={StaticResource TxtResConv}}"></HyperlinkButton>
   </Grid>
</UserControl>
</code>```

Thanks in advance.

答:
You use the Binding syntax to bind to the Content property in the same way you bind to the NavigateUri property.  If it comes from a different source than LinkUri then you specify that in the binding syntax Source property:

```<code>Content="{Binding Source={StaticResource LabelTitle},
                  Converter={StaticResource TxtResConv}}"
</code>```

Body:
Is it possible to bind an additional resource string to another attribute within a control. I already have one attribute bound to a resource but also need another. I can't see a way of doing it as I would need an extra DataContext but oviously can only have one.

The additional attribute I need to bind to is Content within the hyperlink control.

The xaml file is as follows:-

<UserControl x:Class="SilverlightApplication1.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mystuff="clr-namespace:my.assembly.name;assembly=my.assembly.name"
    Width="100" Height="100">

    <UserControl.Resources>
        <mystuff:TxtResConv x:Key="TxtResConv" />
        <mystuff:TxtResPar x:Key="LabelTitle" ResourceUri="LabelTitle" DefaultValue="default label title" />
        <mystuff:TxtResPar x:Key="LinkURL" ResourceUri="LinkURL"  DefaultValue="default label title" />
    </UserControl.Resources>

   <Grid x:Name="LayoutRoot" Background="White">
            <HyperlinkButton DataContext="{StaticResource LinkURL}" x:Name="HyperLink1" Content="NEED TO ADD RESOURCE STRING LABELTITLE HERE !!" NavigateUri="{Binding Mode=OneWay,Converter={StaticResource TxtResConv}}"></HyperlinkButton>
   </Grid>
</UserControl>

Thanks in advance.

Body:
You use the Binding syntax to bind to the Content property in the same way you bind to the NavigateUri property.  If it comes from a different source than LinkUri then you specify that in the binding syntax Source property:

Content="{Binding Source={StaticResource LabelTitle},
                  Converter={StaticResource TxtResConv}}"

OwnerDisplayName: Michael S. Scherotter


问:
Output an Array of objects to terminal, as a table with attributes in fixed-width columns
I am attempting to output a 2D array to the console; I want the information in the array to be nicely formatted as shown in my desired output at the end of this question. My array is created as follows (instances are created of the FamilyMember class):

```<code>#family_members.rb

class FamilyMember

attr_accessor :name, :sex, :status, :age
def initialize (name, sex, type, role, age)
   @name = name
   @sex = sex
   @type = type
   @role = role
   @age = age
end

end

# Below, an array is created called fm; instances of the class are then instantiated within the array elements
fm = {}
fm[1] = FamilyMember.new('Andrew','Male', 'Child', 'Son' , '27' )
fm[2] = FamilyMember.new('Bill','Male', 'Parent', 'Father' , '63' )
fm[3] = FamilyMember.new('Samantha','Female', 'Parent', 'Mother' , '62' )
fm[4] = FamilyMember.new('Thomas','Male', 'Child', 'Dog' , '10' )
fm[5] = FamilyMember.new('Samantha', 'Female', 'Child', 'Dog' , '4' )
</code>```

I want to be able to output the contents of the array to the console formatted as a string. I need to be able to do this two ways - using each and seperately by using do.

What I have attempted (inspired by a previous SO question):

```<code>def eacharray(an_array)
  an_array.each do |inner|
      puts inner.join(" ")
  end
end

eacharray(fm)
</code>```

However the output from the above is as follows:

```<code>1 #<FamilyMember:0x000000027e7d48>
2 #<FamilyMember:0x000000027e7c58>
3 #<FamilyMember:0x000000027e7b68>
4 #<FamilyMember:0x000000027e7a78>
5 #<FamilyMember:0x000000027e7988>
</code>```

How do I output the 2D array elements nicely formatted using each and do?. Any help appreciated. Thanks.

Ideally, my output would be like this:

```<code>Family Member   Name     Sex     Type    Role    Age
1               Andrew   Male    Child   Son     27
2               Bill     Male    Parent  Father  63
3               Samantha Female  Parent  Mother  62
4               Thomas   Male    Child   Dog     10
5               Samantha Female  Child   Dog     4
</code>```

答:
I understand that, This may be not relevant now. But Just sharing this so someone can take advantage.

Try This Gem - terminal-table

terminal-table

Body:
I am attempting to output a 2D array to the console; I want the information in the array to be nicely formatted as shown in my desired output at the end of this question. My array is created as follows (instances are created of the FamilyMember class):

#family_members.rb

class FamilyMember

attr_accessor :name, :sex, :status, :age
def initialize (name, sex, type, role, age)
   @name = name
   @sex = sex
   @type = type
   @role = role
   @age = age
end

end

# Below, an array is created called fm; instances of the class are then instantiated within the array elements
fm = {}
fm[1] = FamilyMember.new('Andrew','Male', 'Child', 'Son' , '27' )
fm[2] = FamilyMember.new('Bill','Male', 'Parent', 'Father' , '63' )
fm[3] = FamilyMember.new('Samantha','Female', 'Parent', 'Mother' , '62' )
fm[4] = FamilyMember.new('Thomas','Male', 'Child', 'Dog' , '10' )
fm[5] = FamilyMember.new('Samantha', 'Female', 'Child', 'Dog' , '4' )

I want to be able to output the contents of the array to the console formatted as a string. I need to be able to do this two ways - using each and seperately by using do.

What I have attempted (inspired by a previous SO question):

def eacharray(an_array)
  an_array.each do |inner|
      puts inner.join(" ")
  end
end

eacharray(fm)

However the output from the above is as follows:

1 #<FamilyMember:0x000000027e7d48>
2 #<FamilyMember:0x000000027e7c58>
3 #<FamilyMember:0x000000027e7b68>
4 #<FamilyMember:0x000000027e7a78>
5 #<FamilyMember:0x000000027e7988>

How do I output the 2D array elements nicely formatted using each and do?. Any help appreciated. Thanks.

Ideally, my output would be like this:

Family Member   Name     Sex     Type    Role    Age
1               Andrew   Male    Child   Son     27
2               Bill     Male    Parent  Father  63
3               Samantha Female  Parent  Mother  62
4               Thomas   Male    Child   Dog     10
5               Samantha Female  Child   Dog     4


问:
C: Separate HEX String into Char Aarray with RegEx
I want to convert hexadecimal strings like:

FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3

Into this format:

```<code>const char msg[] = {0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D, 0x4F,
0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3, 0x2F, 0x01, 0x88, 0x23, 0xFF,
0xFF, 0x60, 0xD3, 0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A, 0x0F,
0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB0, 0x04, 0x03,
0x07, 0x00, 0x03, 0x56, 0xA3};
</code>```

At the moment, I use regex in Notepad++, and works well.
This is the regex:

```<code>find: ([a-z0-9]{2})
replace with: \, 0x\1
(then I remove the first ',')
</code>```

I'm coding in C, I have tried using regex but I can't get it working. How should I use regex for this?

A solution without regex is also fine.

Body:
I want to convert hexadecimal strings like:

FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3

Into this format:

const char msg[] = {0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D, 0x4F,
0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3, 0x2F, 0x01, 0x88, 0x23, 0xFF,
0xFF, 0x60, 0xD3, 0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A, 0x0F,
0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB0, 0x04, 0x03,
0x07, 0x00, 0x03, 0x56, 0xA3};

At the moment, I use regex in Notepad++, and works well.
This is the regex:

find: ([a-z0-9]{2})
replace with: \, 0x\1
(then I remove the first ',')

I'm coding in C, I have tried using regex but I can't get it working. How should I use regex for this?

A solution without regex is also fine.

Body:
for example

const char * demo = "FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3";
int len = strlen(demo);
int i;
char ** msg = (char**) malloc(sizeof(char*) * len / 2);
for(i = 0; i < len / 2; i++) {
    msg[i] = (char*) malloc(sizeof(char) * 5);
    strncpy(msg[i], "0x", 2);
    strncpy(msg[i] + 2, demo + i * 2, 2);
    strncpy(msg[i] + 4, "\0", 1);
}


问:
JQuery => How to make the code a library
I am finally finished with what I've started. I created a responsive lightbox slideshow!

But, I am kinda facing a problem. I want to make it a library...In other words, I want the code to apply to the html classes that I can add infinitely (Like all libraries do).

Thank you!

var imageSliding = $('.box > .img');
        $('.lightbox').click(function() {
            $('.backdrop, .box').animate({
                'opacity': '.50'
            }, 300, 'linear');
            $('.box').animate({
                'opacity': '1.00'
            }, 300, 'linear');
            $('.backdrop, .box').css('display', 'block');
        });

        $('.close').click(function() {
            close_box();
        });

        $('.backdrop').click(function() {
            close_box();
        });

        function close_box() {
            $('.backdrop, .box').animate({
                'opacity': '0'
            }, 300, 'linear', function() {
                $('.backdrop, .box').css('display', 'none');
            });
        }

        /* Slider */
        var speed = 100;

        $(".prev").click(function() {
            var gallery = $(this).closest('.box').find("ul.gallery"),
                now = gallery.children(":visible"),
                last = gallery.children(":last"),
                prev = now.prev();
            prev = prev.index() == -1 ? last : prev;
            now.fadeOut(speed, function() {
                prev.fadeIn(speed);
            });
        });

        $(".next").click(function() {
            var gallery = $(this).closest('.box').find("ul.gallery"),
                now = gallery.children(":visible"),
                first = gallery.children(":first"),
                next = now.next();
            next = next.index() == -1 ? first : next;
            now.fadeOut(speed, function() {
                next.fadeIn(speed);
            });
        });

        $(".gallery li").click(function() {
            var first = $(this).parent().children(':first'),
                next = $(this).next();
            next = next.index() == -1 ? first : next;
            $(this).fadeOut(speed, function() {
                next.fadeIn(speed);
            });
        });```
<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></code>```

答:
See jQuery main Documentation for this: basic-plugin-creation

Also TeamTreehouse has a good tutorial About this: writing-your-own-jquery-plugins


问:
Scale tiny low-resolution app to larger screen size
I am creating a retro arcade game in Java. The screen resolution for the game is 304 x 256, which I want to keep to preserve the retro characteristics of the game (visuals, animations, font blockiness, etc.).

But when I render this on a large desktop display, it is too small, as one would expect.

I'd like to be able to scale the window up say by a constant factor, without having to code the various paint(Graphics) methods to be knowledgeable about the fact that there's a scale-up. That is, I'd like the rendering code believe that the screen is 304 x 256. I also don't want to have to change my desktop resolution or go into full screen exclusive mode. Just want a big window with scaled up pixels, essentially.

I'd be looking for something along the following lines:

```<code>scale(myJFrame, 4);
</code>```

and have all the contents automatically scale up.

UPDATE: Regarding input, my game happens to use keyboard input, so I don't myself need the inverse transform that trashgod describes. Still I can imagine that others would need that, so I think it's an appropriate suggestion.

答:
One approach, suggested here, is to rely on the graphics context's scale() method and construct to an inverse transform to convert between mouse coordinates and image coordinates. In the example below, note how the original image is 256 x 256, while the displayed image is scaled by SCALE = 2.0. The mouse is hovering over the center the image; the tooltip shows an arbitrary point in the display and the center point (127, 127) in the original.

```<code>import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see https://stackoverflow.com/a/2244285/230513 */
public class InverseTransform {

    private static final double SCALE = 2.0;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Inverse Test");
        BufferedImage image = getImage(256, 'F');
        AffineTransform at = new AffineTransform();
        at.scale(SCALE, SCALE);
        frame.add(new ImageView(image, at));
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    private static BufferedImage getImage(int size, char c) {
        final Font font = new Font("Serif", Font.BOLD, size);
        BufferedImage bi = new BufferedImage(
            size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setPaint(Color.white);
        g2d.fillRect(0, 0, size, size);
        g2d.setPaint(Color.blue);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int x = (size - fm.charWidth(c)) / 2;
        int y = fm.getAscent() + fm.getDescent() / 4;
        g2d.drawString(String.valueOf(c), x, y);
        g2d.setPaint(Color.black);
        g2d.drawLine(0, y, size, y);
        g2d.drawLine(x, 0, x, size);
        g2d.fillOval(x - 3, y - 3, 6, 6);
        g2d.drawRect(0, 0, size - 1, size - 1);
        g2d.dispose();
        return bi;
    }

    private static class ImageView extends JPanel {

        private BufferedImage image;
        private AffineTransform at;
        private AffineTransform inverse;
        private Graphics2D canvas;
        private Point oldPt = new Point();
        private Point newPt;

        @Override
        public Dimension getPreferredSize() {
            return new Dimension( // arbitrary multiple of SCALE
                (int)(image.getWidth()  * SCALE * 1.25),
                (int)(image.getHeight() * SCALE * 1.25));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            try {
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
                inverse = g2d.getTransform();
                inverse.invert();
                g2d.translate(this.getWidth() / 2, this.getHeight() / 2);
                g2d.transform(at);
                g2d.translate(-image.getWidth() / 2, -image.getHeight() / 2);
                inverse.concatenate(g2d.getTransform());
                g2d.drawImage(image, 0, 0, this);
            } catch (NoninvertibleTransformException ex) {
                ex.printStackTrace(System.err);
            }
        }

        ImageView(final BufferedImage image, final AffineTransform at) {
            this.setBackground(Color.lightGray);
            this.image = image;
            this.at = at;
            this.canvas = image.createGraphics();
            this.canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            this.canvas.setColor(Color.BLACK);
            this.addMouseMotionListener(new MouseMotionAdapter() {

                @Override
                public void mouseMoved(MouseEvent e) {
                    Point m = e.getPoint();
                    Point i = e.getPoint();
                    try {
                        inverse.inverseTransform(m, i);
                        setToolTipText("<html>Mouse: " + m.x + "," + m.y
                            + "<br>Inverse: " + i.x + "," + i.y + "</html>");
                    } catch (NoninvertibleTransformException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
    }
}
</code>```

Body:
I am creating a retro arcade game in Java. The screen resolution for the game is 304 x 256, which I want to keep to preserve the retro characteristics of the game (visuals, animations, font blockiness, etc.).

But when I render this on a large desktop display, it is too small, as one would expect.

I'd like to be able to scale the window up say by a constant factor, without having to code the various paint(Graphics) methods to be knowledgeable about the fact that there's a scale-up. That is, I'd like the rendering code believe that the screen is 304 x 256. I also don't want to have to change my desktop resolution or go into full screen exclusive mode. Just want a big window with scaled up pixels, essentially.

I'd be looking for something along the following lines:

scale(myJFrame, 4);

and have all the contents automatically scale up.

UPDATE: Regarding input, my game happens to use keyboard input, so I don't myself need the inverse transform that trashgod describes. Still I can imagine that others would need that, so I think it's an appropriate suggestion.

Body:
One approach, suggested here, is to rely on the graphics context's scale() method and construct to an inverse transform to convert between mouse coordinates and image coordinates. In the example below, note how the original image is 256 x 256, while the displayed image is scaled by SCALE = 2.0. The mouse is hovering over the center the image; the tooltip shows an arbitrary point in the display and the center point (127, 127) in the original.

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see https://stackoverflow.com/a/2244285/230513 */
public class InverseTransform {

    private static final double SCALE = 2.0;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Inverse Test");
        BufferedImage image = getImage(256, 'F');
        AffineTransform at = new AffineTransform();
        at.scale(SCALE, SCALE);
        frame.add(new ImageView(image, at));
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    private static BufferedImage getImage(int size, char c) {
        final Font font = new Font("Serif", Font.BOLD, size);
        BufferedImage bi = new BufferedImage(
            size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setPaint(Color.white);
        g2d.fillRect(0, 0, size, size);
        g2d.setPaint(Color.blue);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int x = (size - fm.charWidth(c)) / 2;
        int y = fm.getAscent() + fm.getDescent() / 4;
        g2d.drawString(String.valueOf(c), x, y);
        g2d.setPaint(Color.black);
        g2d.drawLine(0, y, size, y);
        g2d.drawLine(x, 0, x, size);
        g2d.fillOval(x - 3, y - 3, 6, 6);
        g2d.drawRect(0, 0, size - 1, size - 1);
        g2d.dispose();
        return bi;
    }

    private static class ImageView extends JPanel {

        private BufferedImage image;
        private AffineTransform at;
        private AffineTransform inverse;
        private Graphics2D canvas;
        private Point oldPt = new Point();
        private Point newPt;

        @Override
        public Dimension getPreferredSize() {
            return new Dimension( // arbitrary multiple of SCALE
                (int)(image.getWidth()  * SCALE * 1.25),
                (int)(image.getHeight() * SCALE * 1.25));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            try {
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
                inverse = g2d.getTransform();
                inverse.invert();
                g2d.translate(this.getWidth() / 2, this.getHeight() / 2);
                g2d.transform(at);
                g2d.translate(-image.getWidth() / 2, -image.getHeight() / 2);
                inverse.concatenate(g2d.getTransform());
                g2d.drawImage(image, 0, 0, this);
            } catch (NoninvertibleTransformException ex) {
                ex.printStackTrace(System.err);
            }
        }

        ImageView(final BufferedImage image, final AffineTransform at) {
            this.setBackground(Color.lightGray);
            this.image = image;
            this.at = at;
            this.canvas = image.createGraphics();
            this.canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            this.canvas.setColor(Color.BLACK);
            this.addMouseMotionListener(new MouseMotionAdapter() {

                @Override
                public void mouseMoved(MouseEvent e) {
                    Point m = e.getPoint();
                    Point i = e.getPoint();
                    try {
                        inverse.inverseTransform(m, i);
                        setToolTipText("<html>Mouse: " + m.x + "," + m.y
                            + "<br>Inverse: " + i.x + "," + i.y + "</html>");
                    } catch (NoninvertibleTransformException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
    }
}


问:
Connecting to remote SSH server (via Node.js/html5 console)
I have been scouring the face of the web looking to answer a question which I had thought would be simple. My goal is straight forward. I want to build out a simple web-based SSH client using Node.js module(s). I have found several options if I want to connect to the node server itself, but can't seem to find any examples of connecting to a REMOTE server.

Essentially the outcome I am looking for is a workflow like this : Connect to webserver -> Click on a server name in a list of servers -> Enter SSH session to the server I clicked on

The only thing I have found that's even remotely close to what I am looking for is guacamole. I do not want to use guacamole, however, as I want this application to be OS independent. Currently I am building it on a windows 10 platform, and will port it over to fedora when I am done.

I found this tutorial for creating an SSH terminal. However, all this does is creates (or attempts to create) an SSH connection to the local system.

Another options that looked absolutely fantastic was tty.js. Alas, the bottom-line is the same as the above tutorial. The module only allows you to connect to the node.js server, NOT to remote servers.

Anyone have information on a possible path to this goal?

答:
Try also noVnc.
However, a little dig within the page of xterm.js reveals other solutions, like

WebSSH2


问:
Best way to communicate between forms?
I almost never used (advanced, or at all) graphical interfaces, or one simple form with simple controls... but this time I've got something a little more complex, and I don't have much experience with GUI.
I have one main form (and possibly more in the future) from which other sub-forms open (and they might have sub-forms of themselves) and I wonder what is, in your opinion, the best way to communicate between them?

I thought of passing the main form as a parameter to the constructors of the sub-forms, but it doesn't seem like a good way, especially if I'm going to need to communicate between other, distinct, sub-forms, not to mention I have to double check the input, or make a few methods, but it seems more like functional programming than object oriented programming...

Perhaps I can:

Create a static class (or Properties.Settings) for global settings. Cons: every change of data is needed to be copied to the class, I'm looking for something a bit more comfortable and elegant.

Use the ugly way of accessing the controls from Application.OpenForms - fixes the problem of passing the main form as parameter. Cons: not very stable.

Do something else I haven't thought of. Suggestions? Cons: don't know what it is yet.

答:
A good way is to declare delegates in the form that want to start the communication. You need a delegate and a callback function:

```<code>public delegate void SetValueDelegate(string value);
public SetValueDelegate SetValueCallback;
</code>```

Another form can then attach to this delegate. At that moment both forms have to know each other, but not after that moment:

```<code>firstForm.SetValueCallback += new SetValueDelegate(secondForm.SetValueFunction);
</code>```

The second form has to declare a function that matches the delegate definition:

```<code>public void SetValueFunction(string value)
{
    // do something
}
</code>```

Now the first form can use the delegate to use the function of the second form (and all other forms or classes that were attached to the delegate:

```<code>SetValueCallback(txtParam.Text);
</code>```

Edit: made an complete example

```<code>using System;

namespace DelegateTest
{
    public delegate void SetValueDelegate(string value);

    public class Class1
    {
        public SetValueDelegate SetValueCallBack;

        public void Test()
        {
            if(SetValueCallBack != null)
            {
                SetValueCallBack("Hello World!");
            }
        }
    }

    public class Class2
    {
        public void SetValueFunction(string value)
        {
            Console.WriteLine(value);
        }
    }

    public class Launcher
    {
        public static void Main(string[] args)
        {
            Class1 c1 = new Class1();
            Class2 c2 = new Class2();
            c1.SetValueCallBack += new SetValueDelegate(c2.SetValueFunction);
            c1.Test();
        }
    }
}
</code>```

Title: Best way to communicate between forms?

Body:
A good way is to declare delegates in the form that want to start the communication. You need a delegate and a callback function:

public delegate void SetValueDelegate(string value);
public SetValueDelegate SetValueCallback;

Another form can then attach to this delegate. At that moment both forms have to know each other, but not after that moment:

firstForm.SetValueCallback += new SetValueDelegate(secondForm.SetValueFunction);

The second form has to declare a function that matches the delegate definition:

public void SetValueFunction(string value)
{
    // do something
}

Now the first form can use the delegate to use the function of the second form (and all other forms or classes that were attached to the delegate:

SetValueCallback(txtParam.Text);

Edit: made an complete example

using System;

namespace DelegateTest
{
    public delegate void SetValueDelegate(string value);

    public class Class1
    {
        public SetValueDelegate SetValueCallBack;

        public void Test()
        {
            if(SetValueCallBack != null)
            {
                SetValueCallBack("Hello World!");
            }
        }
    }

    public class Class2
    {
        public void SetValueFunction(string value)
        {
            Console.WriteLine(value);
        }
    }

    public class Launcher
    {
        public static void Main(string[] args)
        {
            Class1 c1 = new Class1();
            Class2 c2 = new Class2();
            c1.SetValueCallBack += new SetValueDelegate(c2.SetValueFunction);
            c1.Test();
        }
    }
}


问:
Rails increase duration of flash[:error] message
What would be the easiest/best way to increase the display duration of an individual flash[:error] message in a Rails 4 application?

the code that does the message is in a controller and the pertinent section looks like this:

```<code>  else
    flash[:notice] = t(:no_new_media, source: @channel.external_source.capitalize)
    flash[:error] = @error['message'] if @error.present?
    redirect_to admin_channel_path(@channel)
  end
</code>```

I'd like to increase the display duration of the error message but I don't care either way about the notice

答:
I am not sure but you can try like this:
reference

```<code>$('document').ready(function() {
  setTimeout(function() {
    $('#test').slideUp();
  }, 5000);
});
</code>```

I consider the id of the HTML element that has a flash message is #test, this will hide it after 5000 milliseconds (5 seconds).

OR

```<code>app/assets/javascripts/application.js.coffee

$ ->
  flashCallback = ->
    $(".flash-message").fadeOut()
  $(".flash-message").bind 'click', (ev) =>
    $(".flash-message").fadeOut()
  setTimeout flashCallback, 3000
</code>```

Hope this will help you.

Body:
What would be the easiest/best way to increase the display duration of an individual flash[:error] message in a Rails 4 application?

the code that does the message is in a controller and the pertinent section looks like this:

  else
    flash[:notice] = t(:no_new_media, source: @channel.external_source.capitalize)
    flash[:error] = @error['message'] if @error.present?
    redirect_to admin_channel_path(@channel)
  end

I'd like to increase the display duration of the error message but I don't care either way about the notice

Body:
I am not sure but you can try like this:
reference

$('document').ready(function() {
  setTimeout(function() {
    $('#test').slideUp();
  }, 5000);
});

I consider the id of the HTML element that has a flash message is #test, this will hide it after 5000 milliseconds (5 seconds).

OR

app/assets/javascripts/application.js.coffee

$ ->
  flashCallback = ->
    $(".flash-message").fadeOut()
  $(".flash-message").bind 'click', (ev) =>
    $(".flash-message").fadeOut()
  setTimeout flashCallback, 3000

Hope this will help you.


问:
npm ERR! when installing package
when I want to install a new package, i'm getting endless error-log..

I couldn't evaluate the exact problem of it
I tried npm cache clear since many people suggested it but it didn't work for me.

Maybe it's a problem with permissions, I really don't know.

I also already tried reinstalling nodejs, but nothing changed, still getting an Error when trying to install highcharts with:

```<code>npm install highcharts --save
</code>```

here's the npm-debug.log since it is suggested to provide it with problems

https://gist.github.com/xsoliah/20b4a8790888d5b4842769eeabe08248

thanks for your support

答:
Can you upload your package.json file?

In your npm-debug.log,
line 10489: 35 error Unexpected token < in JSON at position 0

It looks like your packasge.json might be at fault here.

Title: npm ERR! when installing package

Body:
when I want to install a new package, i'm getting endless error-log..

I couldn't evaluate the exact problem of it
I tried npm cache clear since many people suggested it but it didn't work for me.

Maybe it's a problem with permissions, I really don't know.

I also already tried reinstalling nodejs, but nothing changed, still getting an Error when trying to install highcharts with:

npm install highcharts --save

here's the npm-debug.log since it is suggested to provide it with problems

https://gist.github.com/xsoliah/20b4a8790888d5b4842769eeabe08248

thanks for your support


问:
SQL Query (Simple)
I would like to know how could a return the number of songs registred each year based on this table:

```<code>Musics={MusicID, SingerID, Recorder, YearOfRecord}
MusicID as PK
</code>```

Thanks for the attention

答:
Well, the correct query would be:</p>

```<code>SELECT YearOfRecord, Count(MusicID) as NumberOfSongs
FROM Musics
GROUP BY YearOfRecord
ORDER BY YearOfRecord
</code>```

Title: SQL Query (Simple)

Body:
I would like to know how could a return the number of songs registred each year based on this table:

Musics={MusicID, SingerID, Recorder, YearOfRecord}
MusicID as PK

Thanks for the attention

Body:
Well, the correct query would be:

SELECT YearOfRecord, Count(MusicID) as NumberOfSongs
FROM Musics
GROUP BY YearOfRecord
ORDER BY YearOfRecord


问:
tabBar.hidden = true not hiding complete tab bar it lefts white space in bottom of view
I have 2 tab item in my tab bar controller, my requirement is to hide tab bar when user move to child screens (Other than root of each tab).

I have tried hidesBottomBarWhenPushed but some how its not working due to view hierarchy.

Also tabBar.hidden = true hiding the tab bar icon instead the complete tab bar. randomly it works when i scroll up down again and again the table view used on root view

```<code>self.tabBarController.tabBar.hidden = true;
</code>```

I am calling this line before presenting the new view in (prepare for segue method)

On debug its seems tab bar is hidden but it left white space in bottom which remain there

Before - Normal

After tabBar.hidden = true

答:
user bellow code to hide the tabbar. for example "Tab1 and Tab2" is two tabbars, if u r moving Tab1 to inside viewcontrollerA. U can write the bellow code in "viewcontrollerA"</p>

```<code> -(BOOL)hidesBottomBarWhenPushed
   {
      return YES;
    }
</code>```

Body:
I have 2 tab item in my tab bar controller, my requirement is to hide tab bar when user move to child screens (Other than root of each tab).

I have tried hidesBottomBarWhenPushed but some how its not working due to view hierarchy.

Also tabBar.hidden = true hiding the tab bar icon instead the complete tab bar. randomly it works when i scroll up down again and again the table view used on root view

self.tabBarController.tabBar.hidden = true;

I am calling this line before presenting the new view in (prepare for segue method)

On debug its seems tab bar is hidden but it left white space in bottom which remain there

Before - Normal

After tabBar.hidden = true

Body:
user bellow code to hide the tabbar. for example "Tab1 and Tab2" is two tabbars, if u r moving Tab1 to inside viewcontrollerA. U can write the bellow code in "viewcontrollerA"

 -(BOOL)hidesBottomBarWhenPushed
   {
      return YES;
    }


问:
MySQL Subquery in Conditional Statement
I've got a small problem with sub-queries as conditions.

This is the code I'm trying to figure out:

```<code>  SELECT `page`
  FROM `mdl_tool_devcourse`
  WHERE `page` IN
            (SELECT `objectid`
            FROM `mdl_logstore_standard_log`
            WHERE `action` = 'viewed' AND `objecttable` = 'wiki_pages' AND `userid` = 2)

            AND `ref` IN

            (SELECT `objectid`
            FROM `mdl_logstore_standard_log`
            WHERE `action` = 'viewed' AND `objecttable` = 'wiki_pages' AND `userid` = 2)
</code>```

So in my WHERE statement I want both page and ref to be among the results from my subquery. To achieve this I couldn't find any other way than to run the subquery twice. Is there another option to have the subquery executed only once?

答:
Subqueries are ultra slow. Try to run that query:</p>

```<code>SELECT
    `mdl_tool_devcourse`.`page`
FROM `mdl_tool_devcourse`
INNER JOIN `mdl_logstore_standard_log` ON `mdl_logstore_standard_log`.`action` = 'viewed'
    AND `mdl_logstore_standard_log`.`objecttable` = 'wiki_pages'
    AND `mdl_logstore_standard_log`.`userid` = 2
    AND `mdl_tool_devcourse`.`page` = `mdl_logstore_standard_log`.`objectid`
    AND `mdl_tool_devcourse`.`page` = `mdl_logstore_standard_log`.`ref`
</code>```

Title: MySQL Subquery in Conditional Statement

Body:
I've got a small problem with sub-queries as conditions.

This is the code I'm trying to figure out:

  SELECT `page`
  FROM `mdl_tool_devcourse`
  WHERE `page` IN
            (SELECT `objectid`
            FROM `mdl_logstore_standard_log`
            WHERE `action` = 'viewed' AND `objecttable` = 'wiki_pages' AND `userid` = 2)

            AND `ref` IN

            (SELECT `objectid`
            FROM `mdl_logstore_standard_log`
            WHERE `action` = 'viewed' AND `objecttable` = 'wiki_pages' AND `userid` = 2)

So in my WHERE statement I want both page and ref to be among the results from my subquery. To achieve this I couldn't find any other way than to run the subquery twice. Is there another option to have the subquery executed only once?

Body:
Subqueries are ultra slow. Try to run that query:

SELECT
    `mdl_tool_devcourse`.`page`
FROM `mdl_tool_devcourse`
INNER JOIN `mdl_logstore_standard_log` ON `mdl_logstore_standard_log`.`action` = 'viewed'
    AND `mdl_logstore_standard_log`.`objecttable` = 'wiki_pages'
    AND `mdl_logstore_standard_log`.`userid` = 2
    AND `mdl_tool_devcourse`.`page` = `mdl_logstore_standard_log`.`objectid`
    AND `mdl_tool_devcourse`.`page` = `mdl_logstore_standard_log`.`ref`


问:
When is the init() function run?
I've tried to find a precise explanation of what the init() function does in Go. I read what Effective Go says but I was unsure if I understood fully what it said. The exact sentence I am unsure is the following:

And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.

What does all the variable declarations in the package have evaluated their initializers mean? Does it mean if you declare "global" variables in a package and its files, init() will not run until all of it is evaluated and then it will run all the init function and then main() when ./main_file_name is ran?

I also read Mark Summerfield's go book the following:

If a package has one or more init() functions they are automatically executed before the main package's main() function is called.

In my understanding, init() is only relevant when you intend to run main() right? Anyone understands more precisely init() feel free to correct me

答:
The init func runs first and then main. It's used for setting something first  before your program runs, for example:

Accessing a template,
 Running the program using all cores,
 Checking the Goos and arch etc...

ContentLicense: CC BY-SA 4.0

Title: When is the init() function run?


问:
Android open new activity when click link from textview(autolink)
I have a view display textview and enable autolink.

```<code><TextView
   android:id="@+id/txt_contents"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="30dp"
   android:textColor="@color/txt_code_itemlist"
   android:autoLink="web"
   android:textSize="22sp" />
</code>```

Now, when I click link from textview it's will open browser. But I want to find way to open new activity when I click same link.

答:
You can add this.

```<code>text_view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          Intent intent = new Intent(CurrentActivity.this,YourNewActivity.class);
          startActivity(intent);
        }
    });
</code>```

Hope this helps.

Body:
I have a view display textview and enable autolink.

<TextView
   android:id="@+id/txt_contents"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="30dp"
   android:textColor="@color/txt_code_itemlist"
   android:autoLink="web"
   android:textSize="22sp" />

Now, when I click link from textview it's will open browser. But I want to find way to open new activity when I click same link.

Body:
You can add this.

text_view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          Intent intent = new Intent(CurrentActivity.this,YourNewActivity.class);
          startActivity(intent);
        }
    });

Hope this helps.


问:
Examining a single changeset in Mercurial
In Mercurial, how do you examine a single changeset?  hg log -l 5 will give me a summary of the newest 5 changesets, but how do I get a list of the files changed in one changeset?  I don't want to do a diff.</p>

答:
If you want to see how did the contents of the files were changed for a given revision you can use:

```<code>hg diff --change <rev>
</code>```

If you want to see the diff between the current revision and the one you are interested in, you can use:

```<code>hg diff -r <rev>
</code>```

Body:
If you want to see how did the contents of the files were changed for a given revision you can use:

hg diff --change <rev>

If you want to see the diff between the current revision and the one you are interested in, you can use:

hg diff -r <rev>