问:
MPI_Send(99).: Invalid tag, value is -1
I meet the problem "MPI_Send(99).: Invalid tag, value is -1" while I was using  VS2013 and MPIEXEC.exe to run the following code.The  logic is very simple,just thread 0 send tokens to other worker thread, and then the worker thread will reset the token to 0 again.</p>

```<code>#include <mpi.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv) {
    int myid;
    int numprocs;
    int token;
    MPI_Status  status;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);

    if (numprocs == 1) {
        printf("The number of processes for this exercise must be greater than 1!\n");
    }
    else if (myid == 0) {
        /* Master process */
        int sdrID;
        int activeWorkers;

        /* set the number of activeWorkers */
        //...
        activeWorkers = 3;
            /* while there are any active workers */
            while (activeWorkers) {
                /*receive a token from any worker*/
                MPI_Recv(&token, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);

                /* obtain the sending process ID from status. */
                //...;
                //;

                /* print the message "The Master has received a token from Worker ...". */
                printf("%d",status.MPI_SOURCE);

                /* reset token to zero and send it back to the same worker */
                token = 0;
                //  //1.消息缓冲区的起始地址，这是一个指针
                //  //2.发送的指定类型的个数
                //  //3.发送数据的MPI数据类型（为了不同机器不同操作系统之间的互操作性）
                //  //4.整形，目的进程号
                //  //5.整型，消息标志（接受者可以根据这个标识来做出if不同的操作）
                MPI_Send(&token, 1, MPI_INT, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD);

                /* reduce the number of activeWorkers */
                activeWorkers = activeWorkers - 1;
            }
    }
    else {
        /* Worker processes */
        /* set token to 1 and send it to the Master.*/
        token = 1;
        MPI_Send(&token, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD);/////////////////

        /* receive token from the Master. */
        MPI_Recv(&token, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);

        /* print a message and return */
        printf("Worker %i has received the token from the Master.\n", myid);
    }

    MPI_Finalize();

    return 0;
}
</code>```

答:
MPI_ERR_TAG

Invalid tag argument. Tags must be non-negative;

tags in a receive (MPI_Recv, MPI_Irecv, MPI_Sendrecv, etc.) may also be MPI_ANY_TAG. The largest tag value is available through the the attribute MPI_TAG_UB.

Besides,

```<code>#define MPI_ANY_TAG            -1   /* match any message tag */
</code>```

Title: MPI_Send(99).: Invalid tag, value is -1

Body:
I meet the problem "MPI_Send(99).: Invalid tag, value is -1" while I was using  VS2013 and MPIEXEC.exe to run the following code.The  logic is very simple,just thread 0 send tokens to other worker thread, and then the worker thread will reset the token to 0 again.

#include <mpi.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv) {
    int myid;
    int numprocs;
    int token;
    MPI_Status  status;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);

    if (numprocs == 1) {
        printf("The number of processes for this exercise must be greater than 1!\n");
    }
    else if (myid == 0) {
        /* Master process */
        int sdrID;
        int activeWorkers;

        /* set the number of activeWorkers */
        //...
        activeWorkers = 3;
            /* while there are any active workers */
            while (activeWorkers) {
                /*receive a token from any worker*/
                MPI_Recv(&token, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);

                /* obtain the sending process ID from status. */
                //...;
                //;

                /* print the message "The Master has received a token from Worker ...". */
                printf("%d",status.MPI_SOURCE);

                /* reset token to zero and send it back to the same worker */
                token = 0;
                //  //1.消息缓冲区的起始地址，这是一个指针
                //  //2.发送的指定类型的个数
                //  //3.发送数据的MPI数据类型（为了不同机器不同操作系统之间的互操作性）
                //  //4.整形，目的进程号
                //  //5.整型，消息标志（接受者可以根据这个标识来做出if不同的操作）
                MPI_Send(&token, 1, MPI_INT, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD);

                /* reduce the number of activeWorkers */
                activeWorkers = activeWorkers - 1;
            }
    }
    else {
        /* Worker processes */
        /* set token to 1 and send it to the Master.*/
        token = 1;
        MPI_Send(&token, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD);/////////////////

        /* receive token from the Master. */
        MPI_Recv(&token, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);

        /* print a message and return */
        printf("Worker %i has received the token from the Master.\n", myid);
    }

    MPI_Finalize();

    return 0;
}

Body:
MPI_ERR_TAG

Invalid tag argument. Tags must be non-negative;

tags in a receive (MPI_Recv, MPI_Irecv, MPI_Sendrecv, etc.) may also be MPI_ANY_TAG. The largest tag value is available through the the attribute MPI_TAG_UB.

Besides,

#define MPI_ANY_TAG            -1   /* match any message tag */


来源: stackexchange

问:
Find a dot in a text file and add a newline to the file in Python?
I read from a file, if it finds a ".", it should add a newline "\n" to the text and write it back to the file. I tried this code but still have the problem.

```<code>inp = open('rawCorpus.txt', 'r')
out = open("testFile.text", "w")

for line in iter(inp):
    l = line.split()
    if l.endswith(".")
       out.write("\n")
    s = '\n'.join(l)
print(s)
out.write(str(s))
inp.close()
out.close()
</code>```

答:
Here is my own solution, but still I want one more newline after ".", that this solution not did this
    read_lines = [line.rstrip('\n') for line in open('rawCorpus.txt')]
    words = []</p>

```<code>my_save_data = open("my_saved_data.txt", "w")

   for lines in read_lines:

   words.append(lines)

for word in words:
   w = word.rstrip().replace('.', '\n.')
   w = w.split()
   my_save_data.write(str("\n".join(w)))
   print("\n".join(w))

my_save_data.close()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I read from a file, if it finds a ".", it should add a newline "\n" to the text and write it back to the file. I tried this code but still have the problem.

inp = open('rawCorpus.txt', 'r')
out = open("testFile.text", "w")

for line in iter(inp):
    l = line.split()
    if l.endswith(".")
       out.write("\n")
    s = '\n'.join(l)
print(s)
out.write(str(s))
inp.close()
out.close()

Body:
Here is my own solution, but still I want one more newline after ".", that this solution not did this
    read_lines = [line.rstrip('\n') for line in open('rawCorpus.txt')]
    words = []

my_save_data = open("my_saved_data.txt", "w")

   for lines in read_lines:

   words.append(lines)

for word in words:
   w = word.rstrip().replace('.', '\n.')
   w = w.split()
   my_save_data.write(str("\n".join(w)))
   print("\n".join(w))

my_save_data.close()

ContentLicense: CC BY-SA 3.0


问:
Missing ReactInputSelection in react-dom 16.1
I transferred the project to react 16.1 and there is no ReactInputSelection module anymore in the react-dom.
Where can I get it?</p>

答:
It's not (and never was) a public API. So importing it is not supposed. Private APIs are not exposed in React 16 anymore.

If you need this file, you can find it in React DOM 15 distribution, and copy and paste it (and any dependencies) directly into your project:

ReactInputSelection.js


问:
Python Set Comprehension Nested in Dict Comprehension
I have a list of tuples, where each tuple contains a string and a number in the form of:

```<code>[(string_1, num_a), (string_2, num_b), ...]
</code>```

The strings are nonunique, and so are the numbers, e.g. (string_1 , num_m) or (string_9 , num_b) are likely to exist in the list.

I'm attempting to create a dictionary with the string as the key and a set of all numbers occurring with that string as the value:

```<code>dict = {string_1: {num_a, num_m}, string_2: {num_b}, ...}
</code>```

I've done this somewhat successfully with the following dictionary comprehension with nested set comprehension:

```<code>#st_id_list = [(string_1, num_a), ...]
#st_dict = {string_1: {num_a, num_m}, ...}
st_dict = {
    st[0]: set(
        st_[1]
        for st_ in st_id_list
        if st_[0] == st[0]
    )
    for st in st_id_list
}
</code>```

There's only one issue: st_id_list is 18,000 items long. This snippet of code takes less than ten seconds to run for a list of 500 tuples, but over twelve minutes to run for the full 18,000 tuples. I have to think this is because I've nested a set comprehension inside a dict comprehension.

Is there a way to avoid this, or a smarter way to it?

答:
You have a double loop, so you take O(N**2) time to produce your dictionary. For 500 items, 250.000 steps are taken, and for your 18k items, 324 million steps need to be done.

Here is a O(N) loop instead, so 500 steps for your smaller dataset, 18.000 steps for the larger dataset:

```<code>st_dict = {}
for st, id in st_id_list:
    st_dict.setdefault(st, set()).add(id)
</code>```

This uses the dict.setdefault() method to ensure that for a given key (your string values), there is at least an empty set available if the key is missing, then adds the current id value to that set.

You can do the same with a collections.defaultdict() object:

```<code>from collections import defaultdict

st_dict = defaultdict(set)
for st, id in st_id_list:
    st_dict[st].add(id)
</code>```

The defaultdict() uses the factory passed in to set a default value for missing keys.

The disadvantage of the defaultdict approach is that the object continues to produce default values for missing keys after your loop, which can hide application bugs. Use st_dict.default_factory = None to disable the factory explicitly to prevent that.

Body:
I have a list of tuples, where each tuple contains a string and a number in the form of:

[(string_1, num_a), (string_2, num_b), ...]

The strings are nonunique, and so are the numbers, e.g. (string_1 , num_m) or (string_9 , num_b) are likely to exist in the list.

I'm attempting to create a dictionary with the string as the key and a set of all numbers occurring with that string as the value:

dict = {string_1: {num_a, num_m}, string_2: {num_b}, ...}

I've done this somewhat successfully with the following dictionary comprehension with nested set comprehension:

#st_id_list = [(string_1, num_a), ...]
#st_dict = {string_1: {num_a, num_m}, ...}
st_dict = {
    st[0]: set(
        st_[1]
        for st_ in st_id_list
        if st_[0] == st[0]
    )
    for st in st_id_list
}

There's only one issue: st_id_list is 18,000 items long. This snippet of code takes less than ten seconds to run for a list of 500 tuples, but over twelve minutes to run for the full 18,000 tuples. I have to think this is because I've nested a set comprehension inside a dict comprehension.

Is there a way to avoid this, or a smarter way to it?

Body:
You have a double loop, so you take O(N**2) time to produce your dictionary. For 500 items, 250.000 steps are taken, and for your 18k items, 324 million steps need to be done.

Here is a O(N) loop instead, so 500 steps for your smaller dataset, 18.000 steps for the larger dataset:

st_dict = {}
for st, id in st_id_list:
    st_dict.setdefault(st, set()).add(id)

This uses the dict.setdefault() method to ensure that for a given key (your string values), there is at least an empty set available if the key is missing, then adds the current id value to that set.

You can do the same with a collections.defaultdict() object:

from collections import defaultdict

st_dict = defaultdict(set)
for st, id in st_id_list:
    st_dict[st].add(id)

The defaultdict() uses the factory passed in to set a default value for missing keys.

The disadvantage of the defaultdict approach is that the object continues to produce default values for missing keys after your loop, which can hide application bugs. Use st_dict.default_factory = None to disable the factory explicitly to prevent that.


问:
How to convert an already open file to string?
Given an open file, return the contents as a string.( This assumes the autotester test the function with a random file so the variable should be open to multiple files of the same type)</p>

```<code>def read_file(myfile):
'''(file) -> str
Read the open file and return as a string.'''
</code>```

答: After opening the file (I recommend using the with statement, e.g with open(filename.txt, "r") as file, use fileString = file.read() and fileString will be the contents

Body:
Given an open file, return the contents as a string.( This assumes the autotester test the function with a random file so the variable should be open to multiple files of the same type)

def read_file(myfile):
'''(file) -> str
Read the open file and return as a string.'''


问:
How to change the same characters in a string to different values in python?
I'm trying to implement a basic converting program, changing stars to either  or  depending on if they are the first or second of a pair, but regardless of what I do my program changes all the stars to  or .

```<code>line = "*ju*bil*ee*"
star_counter = 0
new_line = line
    for character in line:
         if character is "*":
            star_counter += 1
            if star_counter%2 == 0:
                new_line = line.replace(character, "</em>")
            else:
                new_line = line.replace(character, "<em>")
</code>```

答:
```<code>new_line = "*ju*bil*ee*"
star_counter = 0
for character in new_line:
    if character is "*":
        if star_counter == 0:
            new_line = new_line.replace(character, "<em>", 1)
            star_counter=1
        else:
            new_line = new_line.replace(character, "</em>", 1)
            star_counter = 0
print(new_line)
</code>```

Output

```<code><em>ju</em>bil<em>ee</em>
</code>```

Body:
I'm trying to implement a basic converting program, changing stars to either  or  depending on if they are the first or second of a pair, but regardless of what I do my program changes all the stars to  or .

line = "*ju*bil*ee*"
star_counter = 0
new_line = line
    for character in line:
         if character is "*":
            star_counter += 1
            if star_counter%2 == 0:
                new_line = line.replace(character, "")
            else:
                new_line = line.replace(character, "")

Body:
new_line = "*ju*bil*ee*"
star_counter = 0
for character in new_line:
    if character is "*":
        if star_counter == 0:
            new_line = new_line.replace(character, "<em>", 1)
            star_counter=1
        else:
            new_line = new_line.replace(character, "</em>", 1)
            star_counter = 0
print(new_line)

Output

<em>ju</em>bil<em>ee</em>


问:
Recursively get all the vertices emerging from a group of vertices
I have a vertex label "group" and a group can have multiple "categories".
For example, a group named "food" can have multiple categories like "Seafood, Chinese, Indian" which are connected by an edge labelled "label1".
Now, a category can have further categories, like "Seafood" can have "fish, prawns" and so on. the depth is arbitrary and these all further categories are connected by edge labelled "label2".

```<code>food --label1--> seafood --label2--> fish --label2--> jellyfish --label2--> so on
                                          --label2--> starfish
                         --label2--> prawns
                         --label2--> crab

     --label1--> Indian
     --label1--> Chinese
</code>```

I want to recursively traverse all the vertices and get the data.
I hope you understood the question. Please help me out.

答:
It's as easy as:</p>

```<code>g.V(food).out("label1").
  emit().
    repeat(out("label2"))
</code>```

Body:
I have a vertex label "group" and a group can have multiple "categories".
For example, a group named "food" can have multiple categories like "Seafood, Chinese, Indian" which are connected by an edge labelled "label1".
Now, a category can have further categories, like "Seafood" can have "fish, prawns" and so on. the depth is arbitrary and these all further categories are connected by edge labelled "label2".

food --label1--> seafood --label2--> fish --label2--> jellyfish --label2--> so on
                                          --label2--> starfish
                         --label2--> prawns
                         --label2--> crab

     --label1--> Indian
     --label1--> Chinese

I want to recursively traverse all the vertices and get the data.
I hope you understood the question. Please help me out.

Body:
It's as easy as:

g.V(food).out("label1").
  emit().
    repeat(out("label2"))


问:
How to write an average equation in c# for any amount of numbers
My goal is to produce the average of the numbers a person types into the box (which I have already set up).  The equation needs to be after the f.Close(); and the data type needs to be float.

```<code>public partial class frmMain : Form
{
    public frmMain()
    {
        InitializeComponent();
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        int total = 0, count = 0;
        DialogResult result;
        result = ofd.ShowDialog();
        if (result == System.Windows.Forms.DialogResult.OK)
        {
            string fileName = ofd.FileName;
            StreamReader f = new StreamReader(fileName);

            while (!f.EndOfStream)
            {
                string textScore = f.ReadLine();
                firstScores.Items.Add(textScore);
                int score = int.Parse(textScore);
                total = total + score;
                count = count + 1;
            }

            f.Close();

            //This is what I have currently
            float sum, length, average;
            string textLine;

            sum = float.Parse(textLine);
            length = float.Parse(textLine);
            average = sum / length;
</code>```

I thought this might work, but it states that the textLine in the sum = float.Parse is unassigned.

答:
he textLine in the sum = float.Parse is unassigned.

You have these two lines together:

```<code>string textLine;
sum = float.Parse(textLine);
</code>```

You just declared textLine, but haven't stored anything in it yet.

What you really want to do is use the data you already read in from the file. When you were reading the file, you put that data in the firstScores.Items collection, and you already have the total and count calculated. You just need to use those same values, and make sure to cast (not Parse()) them to float to avoid integer division, which would truncate the decimal portion (the link is written for old-school C, but the contents are true for C# as well).

BTW, you're still learning, and the professor likely has specific objectives for you in going through the process of using a StreamReader, etc. But I think it's also worthwhile to show you how I'd do this in a real program for work:

```<code>//First, separate out the this code into a function that accepts a file name and returns the values via the IEnumerable interface, rather than an array or list
IEnumerable<int> ReadScores(string filename)
{
    //Use the `System.IO.File` class to make reading simpler
    // and use the linq functions to get this down to a single line of code:
    return File.ReadLines(filename).Select(l => int.Parse(l));
}

private void btnOpen_Click(object sender, EventArgs e)
{
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        //ToList() is optional, but it will force the data into memory, so we only need to go disk once
        var data = ReadScores(ofd.FileName).ToList();

        int total = data.Sum();
        int count = data.Count;
        float average = (float)total / (float)count;
    }
}
</code>```

Body:
My goal is to produce the average of the numbers a person types into the box (which I have already set up).  The equation needs to be after the f.Close(); and the data type needs to be float.

public partial class frmMain : Form
{
    public frmMain()
    {
        InitializeComponent();
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        int total = 0, count = 0;
        DialogResult result;
        result = ofd.ShowDialog();
        if (result == System.Windows.Forms.DialogResult.OK)
        {
            string fileName = ofd.FileName;
            StreamReader f = new StreamReader(fileName);

            while (!f.EndOfStream)
            {
                string textScore = f.ReadLine();
                firstScores.Items.Add(textScore);
                int score = int.Parse(textScore);
                total = total + score;
                count = count + 1;
            }

            f.Close();

            //This is what I have currently
            float sum, length, average;
            string textLine;

            sum = float.Parse(textLine);
            length = float.Parse(textLine);
            average = sum / length;

I thought this might work, but it states that the textLine in the sum = float.Parse is unassigned.

Body:
he textLine in the sum = float.Parse is unassigned.

You have these two lines together:

string textLine;
sum = float.Parse(textLine);

You just declared textLine, but haven't stored anything in it yet.

What you really want to do is use the data you already read in from the file. When you were reading the file, you put that data in the firstScores.Items collection, and you already have the total and count calculated. You just need to use those same values, and make sure to cast (not Parse()) them to float to avoid integer division, which would truncate the decimal portion (the link is written for old-school C, but the contents are true for C# as well).

BTW, you're still learning, and the professor likely has specific objectives for you in going through the process of using a StreamReader, etc. But I think it's also worthwhile to show you how I'd do this in a real program for work:

//First, separate out the this code into a function that accepts a file name and returns the values via the IEnumerable interface, rather than an array or list
IEnumerable<int> ReadScores(string filename)
{
    //Use the `System.IO.File` class to make reading simpler
    // and use the linq functions to get this down to a single line of code:
    return File.ReadLines(filename).Select(l => int.Parse(l));
}

private void btnOpen_Click(object sender, EventArgs e)
{
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        //ToList() is optional, but it will force the data into memory, so we only need to go disk once
        var data = ReadScores(ofd.FileName).ToList();

        int total = data.Sum();
        int count = data.Count;
        float average = (float)total / (float)count;
    }
}


问:
Implement an asynchronous tcp connection with a timeout
I am getting an exception:

```<code>"An unhandled exception of type 'System.NotSupportedException' occurred in
 System.dll

 Additional information: This protocol version is not supported."
</code>```

when I run the following code. I am trying to implement an asynchronous tcp connection with a timeout.

I've seen and read several stack overflow examples, some using TcpClient and some using Socket. I assume the former wraps up the latter and is newer. I am trying with TcpClient.BeginConnect

The documentation does not list NotSupported as one of the exception types this method can throw. How do I track down what the problem is?

```<code>public class Client
{
    private string m_host;
    private uint m_port;
    private uint m_timeoutMilliseconds;
    private TcpClient m_client;

    public Client(string host, uint port, uint timeoutMilliseconds)
    {
        m_host = host;
        m_port = port;
        m_timeoutMilliseconds = timeoutMilliseconds;
        m_client = new TcpClient();
    }

    public bool Connect()
    {
        IPHostEntry hostInfo = Dns.GetHostEntry(m_host);
        IPAddress ipAddress = hostInfo.AddressList[0];
        IPEndPoint endpoint = new IPEndPoint(ipAddress, (int)m_port);

        IAsyncResult result = m_client.BeginConnect(ipAddress, (int)m_port, new AsyncCallback(OnConnect), m_client);
        result.AsyncWaitHandle.WaitOne((int)m_timeoutMilliseconds, true);

        // SNIP

        return true;
    }

    public void Disconnect()
    {
        throw new NotImplementedException();
    }

    public void MakeRequest(string symbol)
    {
        throw new NotImplementedException();
    }

    private static void OnConnect(IAsyncResult asyncResult)
    {
        Socket socket = (Socket)asyncResult.AsyncState;
        socket.EndConnect(asyncResult);

        Console.WriteLine("Socket connected to {0}"
                        , socket.RemoteEndPoint.ToString());

    }
}

class Program
{
    static void Main(string[] args)
    {
        Client client = new Integration.Client("127.0.0.1", 24001, 360000);
        client.Connect();
    }
}
</code>```

答:
If you are only after an IP4 local address try this

```<code>using System.Linq;

IPAddress ipAddress = Dns.GetHostEntry(m_host).AddressList.FirstOrDefault(x => x.IsIPv6LinkLocal == false);
</code>```

I just tried your example and had the same error, with the above it seemed to work.

Body:
I am getting an exception:

"An unhandled exception of type 'System.NotSupportedException' occurred in
 System.dll

 Additional information: This protocol version is not supported."

when I run the following code. I am trying to implement an asynchronous tcp connection with a timeout.

I've seen and read several stack overflow examples, some using TcpClient and some using Socket. I assume the former wraps up the latter and is newer. I am trying with TcpClient.BeginConnect

The documentation does not list NotSupported as one of the exception types this method can throw. How do I track down what the problem is?

public class Client
{
    private string m_host;
    private uint m_port;
    private uint m_timeoutMilliseconds;
    private TcpClient m_client;

    public Client(string host, uint port, uint timeoutMilliseconds)
    {
        m_host = host;
        m_port = port;
        m_timeoutMilliseconds = timeoutMilliseconds;
        m_client = new TcpClient();
    }

    public bool Connect()
    {
        IPHostEntry hostInfo = Dns.GetHostEntry(m_host);
        IPAddress ipAddress = hostInfo.AddressList[0];
        IPEndPoint endpoint = new IPEndPoint(ipAddress, (int)m_port);

        IAsyncResult result = m_client.BeginConnect(ipAddress, (int)m_port, new AsyncCallback(OnConnect), m_client);
        result.AsyncWaitHandle.WaitOne((int)m_timeoutMilliseconds, true);

        // SNIP

        return true;
    }

    public void Disconnect()
    {
        throw new NotImplementedException();
    }

    public void MakeRequest(string symbol)
    {
        throw new NotImplementedException();
    }

    private static void OnConnect(IAsyncResult asyncResult)
    {
        Socket socket = (Socket)asyncResult.AsyncState;
        socket.EndConnect(asyncResult);

        Console.WriteLine("Socket connected to {0}"
                        , socket.RemoteEndPoint.ToString());

    }
}

class Program
{
    static void Main(string[] args)
    {
        Client client = new Integration.Client("127.0.0.1", 24001, 360000);
        client.Connect();
    }
}

Body:
If you are only after an IP4 local address try this

using System.Linq;

IPAddress ipAddress = Dns.GetHostEntry(m_host).AddressList.FirstOrDefault(x => x.IsIPv6LinkLocal == false);

I just tried your example and had the same error, with the above it seemed to work.


问:
Convert a string containing a number in scientific notation to a double in PHP
I need help converting a string that contains a number in scientific notation to a double.

Example strings:
"1.8281e-009"
"2.3562e-007"
"0.911348"

I was thinking about just breaking the number into the number on the left and the exponent and than just do the math to generate the number; but is there a better/standard way to do this?

答:
Use number_format() and rtrim() functions together.  Eg

```<code>//eg $sciNotation = 2.3649E-8
$number = number_format($sciNotation, 10); //Use $dec_point large enough
echo rtrim($number, '0'); //Remove trailing zeros
</code>```

I created a function, with more functions (pun not intended)

```<code>function decimalNotation($num){
    $parts = explode('E', $num);
    if(count($parts) != 2){
        return $num;
    }
    $exp = abs(end($parts)) + 3;
    $decimal = number_format($num, $exp);
    $decimal = rtrim($decimal, '0');
    return rtrim($decimal, '.');
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Use number_format() and rtrim() functions together.  Eg

//eg $sciNotation = 2.3649E-8
$number = number_format($sciNotation, 10); //Use $dec_point large enough
echo rtrim($number, '0'); //Remove trailing zeros

I created a function, with more functions (pun not intended)

function decimalNotation($num){
    $parts = explode('E', $num);
    if(count($parts) != 2){
        return $num;
    }
    $exp = abs(end($parts)) + 3;
    $decimal = number_format($num, $exp);
    $decimal = rtrim($decimal, '0');
    return rtrim($decimal, '.');
}


问:
Remove trailing whitespace recursively only at end of file using grep/sed?
Basically, I've got about 1,500 files and the last character of any of these files should not be any type of white space.

How do I check a bunch of files to make sure that they don't end in some form of whitespace?(newline, space, carriage return, tab, etc.)?

答:
This will strip all trailing whitespace:

```<code>perl -e '$s = ""; while (defined($_ = getc)) { if (/\s/) { $s .= $_; } else { print $s, $_; $s = ""; } }' < infile > outfile
</code>```

There's probably an equivalent in sed but I'm much more familiar with Perl, hope that works for you.  Basic idea: if the next character is whitespace, save it; otherwise, print any saved characters followed by the character just read.  If we hit EOF after reading one or more whitespace characters, they won't be printed.

This will simply detect trailing whitespace, giving an exit code of 1 if so:

```<code>perl -e 'while (defined($_ = getc)) { $last = $_; } exit($last =~ /\s/);' < infile > outfile
</code>```

[EDIT]
The above describes how to detect or change a single file.  If you have a large directory tree containing files that you want to apply the changes to, you can put the command in a separate script:

fix.pl

```<code>#!/usr/bin/perl
$s = "";
while (defined($_ = getc)) {
    if (/\s/) { $s .= $_; } else { print $s, $_; $s = ""; }
}
</code>```

and use it in conjunction with the find command:

```<code>find /top/dir -type f -exec sh -c 'mv "{}" "{}.bak" && fix.pl < "{}.bak" > "{}"' ';'
</code>```

This will move each original file to a backup file ending in ".bak".  (It would be a good idea to test this on a small test fileset first.)

Body:
This will strip all trailing whitespace:

perl -e '$s = ""; while (defined($_ = getc)) { if (/\s/) { $s .= $_; } else { print $s, $_; $s = ""; } }' < infile > outfile

There's probably an equivalent in sed but I'm much more familiar with Perl, hope that works for you.  Basic idea: if the next character is whitespace, save it; otherwise, print any saved characters followed by the character just read.  If we hit EOF after reading one or more whitespace characters, they won't be printed.

This will simply detect trailing whitespace, giving an exit code of 1 if so:

perl -e 'while (defined($_ = getc)) { $last = $_; } exit($last =~ /\s/);' < infile > outfile

[EDIT]
The above describes how to detect or change a single file.  If you have a large directory tree containing files that you want to apply the changes to, you can put the command in a separate script:

fix.pl

#!/usr/bin/perl
$s = "";
while (defined($_ = getc)) {
    if (/\s/) { $s .= $_; } else { print $s, $_; $s = ""; }
}

and use it in conjunction with the find command:

find /top/dir -type f -exec sh -c 'mv "{}" "{}.bak" && fix.pl < "{}.bak" > "{}"' ';'

This will move each original file to a backup file ending in ".bak".  (It would be a good idea to test this on a small test fileset first.)


问:
Opening only some functions from a module in Reason
I'm trying to do something like this in Reason:

```<code>let {map, fold_left} = List;
let {log} = Js;

let list = [1,2,3];
list |> map(i => i + 1) |> fold_left((p,c) => p+c, 0) |> log;
</code>```

Basically, I want to import only a couple of functions from a module. Is that possible in Reason.

Currently I do it like this:

```<code>let map = List.map;
let fold_left = List.fold_left;
let log = Js.log;
</code>```

答:
From Discord, courtesy of @octachron</p>

```<code>let (map,fold_left) = List.(map, fold_left)
</code>```

Body:
I'm trying to do something like this in Reason:

let {map, fold_left} = List;
let {log} = Js;

let list = [1,2,3];
list |> map(i => i + 1) |> fold_left((p,c) => p+c, 0) |> log;

Basically, I want to import only a couple of functions from a module. Is that possible in Reason.

Currently I do it like this:

let map = List.map;
let fold_left = List.fold_left;
let log = Js.log;

Body:
From Discord, courtesy of @octachron

let (map,fold_left) = List.(map, fold_left)


问:
How to add a QVideoWidget in Qt Designer?
I want to insert video in blue box(ui image) but I don't know how to insert video file.

My code is here.
I don't know how to add video... Just know example that make video player ...

```<code>import sys

from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import uic
from PyQt5 import QtCore
from PyQt5.QtCore import QDir, Qt, QUrl, pyqtSlot

from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget

from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel,
        QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget)

dir_audience=''
dir_movie = ''
dir_export = ''
select_emotion = 'happy'

class Form(QtWidgets.QDialog):
    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = uic.loadUi("highlight_export_form.ui", self)
        self.ui.show()

        self.ui.load_audience.clicked.connect(self.load_audience_clicked)
        self.ui.load_movie.clicked.connect(self.load_movie_clicked)

        self.ui.start_recog.clicked.connect(self.start_recog_clicked)

        self.ui.radio_happy.toggled.connect(self.on_radio_button_toggled)
        self.ui.radio_surprised.toggled.connect(self.on_radio_button_toggled)

    def load_audience_clicked(self, event):
        dir_audience, _ = QFileDialog.getOpenFileName(self, "Open Audience", QDir.homePath())
        self.path_audience.setText(dir_audience)

    def load_movie_clicked(self, event):
        dir_movie, _ = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath())
        self.path_movie.setText(dir_movie)

    def start_recog_clicked(self, event):
        self.check_1.setText("start_recognition")

    def on_radio_button_toggled(self):
        if self.radio_happy.isChecked():
            select_emotion='happy'
            self.check_3.setText(select_emotion)

        elif self.radio_surprised.isChecked():
            select_emotion='surprised'
            self.check_3.setText(select_emotion)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Form()
    sys.exit(app.exec())
</code>```

Thank you for reading my question.

答:
Qt Designer does not show all the Qt widget, and often we want to add our own widget through Qt, for that there are at least 2 solutions, the first is to create a plugin and load it to Qt Designer, and the other is simpler. promote the widget, the latter is what I will show in this answer.

For this you must make certain minimum changes, I do not know what type of widget is the one you use in the blue box but you must change it to the Widget type that is in the sub-menu of the containers as shown in the following image:

after them you must right click on the widget and select Promote to ..., then a dialogue will appear, in the part of Promoted class name you must place QVideoWidget, and in the part of Header File you must place PyQt5.QtMultimediaWidgets, then press the add button and then Promote:

After that you will be able to use QVideoWidget within your application.

In the following link there is an example

Body:
I want to insert video in blue box(ui image) but I don't know how to insert video file.

My code is here.
I don't know how to add video... Just know example that make video player ...

import sys

from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import uic
from PyQt5 import QtCore
from PyQt5.QtCore import QDir, Qt, QUrl, pyqtSlot

from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget

from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel,
        QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget)

dir_audience=''
dir_movie = ''
dir_export = ''
select_emotion = 'happy'

class Form(QtWidgets.QDialog):
    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = uic.loadUi("highlight_export_form.ui", self)
        self.ui.show()

        self.ui.load_audience.clicked.connect(self.load_audience_clicked)
        self.ui.load_movie.clicked.connect(self.load_movie_clicked)

        self.ui.start_recog.clicked.connect(self.start_recog_clicked)

        self.ui.radio_happy.toggled.connect(self.on_radio_button_toggled)
        self.ui.radio_surprised.toggled.connect(self.on_radio_button_toggled)

    def load_audience_clicked(self, event):
        dir_audience, _ = QFileDialog.getOpenFileName(self, "Open Audience", QDir.homePath())
        self.path_audience.setText(dir_audience)

    def load_movie_clicked(self, event):
        dir_movie, _ = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath())
        self.path_movie.setText(dir_movie)

    def start_recog_clicked(self, event):
        self.check_1.setText("start_recognition")

    def on_radio_button_toggled(self):
        if self.radio_happy.isChecked():
            select_emotion='happy'
            self.check_3.setText(select_emotion)

        elif self.radio_surprised.isChecked():
            select_emotion='surprised'
            self.check_3.setText(select_emotion)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Form()
    sys.exit(app.exec())

Thank you for reading my question.


问:
Transforming a string to list of integer then sum them up in haskell?
I have a function checkIfTrue where I want to computes a string and check if the sum of the string is true. Like for example, I have a String "ABC" where A= 1, B=2, C=3.Let say

input:

checkIfTrue "ABC" 2

output:

False

as the sum of A+B+C = 6.

```<code>checkIfTrue :: String -> Int -> Bool
checkIfTrue = sum x + xs .words
    | x <- A = 1
    |x <- B = 2
    |x <- C = 3
</code>```

This is what I had in mind but I don't know how to compare if the sum of the input is the same. Sorry if what I had in mind is ridiculous.

答:
String in Haskell is a type synonym for [Char]. You can utilize this to your advantage here!

Write a function that translates Char -> Int, then map that over your list:

```<code>stringValue :: String -> Int
stringValue s = sum $ map charToInt s
</code>```

Now you can use this function to write your checkIfTrue in a simpler manner:

```<code>checkIfTrue :: String -> Int -> Bool
checkIfTrue s i = stringValue s == i
</code>```

As @karakfa notes in the comments, you can write a simple charToInt function making use of the Enum typeclass that will map 'A' -> 1 ... 'Z' -> 26:

```<code>charToInt :: Char -> Int
charToInt = (+1) . (subtract (fromEnum 'A') . fromEnum)
</code>```

And the whole thing can be condensed to a one-liner using function composition and eta-reduction:

```<code>checkIfTrue = (==) . sum . map (subtract (fromEnum 'A') . fromEnum)
</code>```

Body:
I have a function checkIfTrue where I want to computes a string and check if the sum of the string is true. Like for example, I have a String "ABC" where A= 1, B=2, C=3.Let say

input:

checkIfTrue "ABC" 2

output:

False

as the sum of A+B+C = 6.

checkIfTrue :: String -> Int -> Bool
checkIfTrue = sum x + xs .words
    | x <- A = 1
    |x <- B = 2
    |x <- C = 3

This is what I had in mind but I don't know how to compare if the sum of the input is the same. Sorry if what I had in mind is ridiculous.

Body:
String in Haskell is a type synonym for [Char]. You can utilize this to your advantage here!

Write a function that translates Char -> Int, then map that over your list:

stringValue :: String -> Int
stringValue s = sum $ map charToInt s

Now you can use this function to write your checkIfTrue in a simpler manner:

checkIfTrue :: String -> Int -> Bool
checkIfTrue s i = stringValue s == i

As @karakfa notes in the comments, you can write a simple charToInt function making use of the Enum typeclass that will map 'A' -> 1 ... 'Z' -> 26:

charToInt :: Char -> Int
charToInt = (+1) . (subtract (fromEnum 'A') . fromEnum)

And the whole thing can be condensed to a one-liner using function composition and eta-reduction:

checkIfTrue = (==) . sum . map (subtract (fromEnum 'A') . fromEnum)


答:
You can do this with a regular expression substitution.

```<code>import re
new_line = re.sub(r'\*([^*]+)\*', r'<em>\1</em>', line)
</code>```

The regular expression matches two * with some non-* characters between them, uses a capture group to capture the in-between text, and then substitutes that capture group between  and  in the result.

Title: How to change the same characters in a string to different values in python?

Body:
You can do this with a regular expression substitution.

import re
new_line = re.sub(r'\*([^*]+)\*', r'<em>\1</em>', line)

The regular expression matches two * with some non-* characters between them, uses a capture group to capture the in-between text, and then substitutes that capture group between <em> and </em> in the result.


问:
SQL Sub-query Error
I think there is issue with the A2 set where I am only including Restart_case = Y, but I am not sure please help. I am getting this error: An unexpected token "WHERE" was found following "_ID) AS Max_DateBegin".  Expected tokens may include...
Thank you</p>

```<code>SELECT A2.* FROM
(SELECT A1.*, min(BeginDate) OVER (PARTITION BY Per_ID) AS Min_BeginDate,
MAX(BeginDate) OVER (PARTITION BY Per_ID) AS Max_BeginDate
WHERE RestartCase = 'Y'
From) A2
(SELECT distinct C.Per_ID, P.DOB, C.BeginDate, C.EndDate, C.RestartCase, P.per_type
FROM CaseSum C LEFT JOIN PERSON p on C.ID_PRSN = P.ID_PRSN)  A1
WHERE per_Type = 1 AND BeginDate <= '9/30/2017' AND (EndDate >= '10/01/2017' OR EndDate IS NULL)
ORDER BY A1.Per_ID
</code>```

答:
I believe this is what you want (or something like it):

SELECT
    A2.*
FROM
    (SELECT
        A1.*,
        MIN(BeginDate) OVER (PARTITION BY Per_ID) AS Min_BeginDate,
        MAX(BeginDate) OVER (PARTITION BY Per_ID) AS Max_BeginDate
    FROM
        (SELECT DISTINCT
            C.Per_ID,
            P.DOB,
            C.BeginDate,
            C.EndDate,
            C.RestartCase,
            P.per_type
        FROM CaseSum C
        LEFT JOIN PERSON P
            on C.ID_PRSN = P.ID_PRSN
        WHERE P.per_Type = 1
            AND C.BeginDate <= '9/30/2017'
            AND (C.EndDate >= '10/01/2017' OR C.EndDate IS NULL)
        )  A1
    WHERE A1.RestartCase = 'Y'
ORDER BY A1.Per_ID
    ) A2

Title: SQL Sub-query Error

Body:
I think there is issue with the A2 set where I am only including Restart_case = Y, but I am not sure please help. I am getting this error: An unexpected token "WHERE" was found following "_ID) AS Max_DateBegin".  Expected tokens may include...
Thank you

SELECT A2.* FROM
(SELECT A1.*, min(BeginDate) OVER (PARTITION BY Per_ID) AS Min_BeginDate,
MAX(BeginDate) OVER (PARTITION BY Per_ID) AS Max_BeginDate
WHERE RestartCase = 'Y'
From) A2
(SELECT distinct C.Per_ID, P.DOB, C.BeginDate, C.EndDate, C.RestartCase, P.per_type
FROM CaseSum C LEFT JOIN PERSON p on C.ID_PRSN = P.ID_PRSN)  A1
WHERE per_Type = 1 AND BeginDate <= '9/30/2017' AND (EndDate >= '10/01/2017' OR EndDate IS NULL)
ORDER BY A1.Per_ID


问:
Error on launching AVD in Android Studio, ERROR says eglMakeCurrent failed
```<code>emulator: device fd:668
HAX is working and emulator runs in fast virt mode
creating window 0 0 240 400
emulator: emulator window was out of view and was recentered
eglMakeCurrent failed
</code>```

What is "eglMakeCurrent failed"?

TRIED

to set the window.x = 0 window.y = 0 ...

but window.x=322 keeps coming back... I tried changing the resolution....plus
can't even move the emulator..tried ALT+SPACE and 'move'...but can't move
it.. Although the emulator can be started –

答:
In AVD Manager, change Emulated Performance - Graphics to Software - GLES 2.0

I ran into this after setting up multiple monitors using different graphics cards.

Body:
emulator: device fd:668
HAX is working and emulator runs in fast virt mode
creating window 0 0 240 400
emulator: emulator window was out of view and was recentered
eglMakeCurrent failed

What is "eglMakeCurrent failed"?

TRIED

to set the window.x = 0 window.y = 0 ...

but window.x=322 keeps coming back... I tried changing the resolution....plus
can't even move the emulator..tried ALT+SPACE and 'move'...but can't move
it.. Although the emulator can be started –


问:
regex for email validation Not Working with Subdomains?
I'm using the following for email validation:

```<code>var filter = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/; // For Email Validation

if (filter.test(emailInputVal))) {console.log('good')}
</code>```

For some reason the above does not work with emails that have a subdomain Any ideas why?

```<code>xxxx@xxx.xxx.com
</code>```

Thanks

答:
You can't reliably validate email addresses with regular expressions. What I'd do:

use a simple expression like /^[^@]+@([A-Za-z0-9-]+\.)*[A-Za-z0-9-]+$/ for client-side validation to catch typos

check the DNS record on the server-side

send a confirmation mail

Body:
I'm using the following for email validation:

var filter = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/; // For Email Validation

if (filter.test(emailInputVal))) {console.log('good')}

For some reason the above does not work with emails that have a subdomain Any ideas why?

xxxx@xxx.xxx.com

Thanks


问:
Vertx: resource allocation when verticles are idle?
I am pretty new to Vertx and have been experimenting with Vertx 3 in my app. So far it seem really useful in some scenarios. But I do have a question that I would like a comprehensive answer on, since the documentation and Google do not provide any information on this.

It seems (through my observation) that in a simple application not using clustered vertx, each verticle deployed is maintained by a separate thread. But currently my app (i.e. a web application using some other framework) is not using vertx all the way, (meaning that a lot of business logic does not involve vertx andthe verticles deployed are not always busy and only perform operations in a relatively infrequent manner). I wonder in this scenario, would the threads be freed up by vertx when the verticles are deployed but idle, and only utilized when they receive events? Or will they occupy the threads and not allow the non-vertx parts of the application utilize them?

Thanks in advance

答:
Actually, this part is covered quite well: http://vertx.io/docs/vertx-core/java/#_reactor_and_multi_reactor

Vert.x works differently here. Instead of a single event loop, each
  Vertx instance maintains several event loops. By default we choose the
  number based on the number of available cores on the machine, but this
  can be overridden.

Where you're wrong is that verticle bound to a thread is a verticle occupying a thread. Let's say you have 4 CPUs and 1 verticle. VertX will allocate 4 threads to it's EventLoop. You start 100 vertices? VertX will still use 4 threads.

But, if Verticle34, let's say, starts on Thread2, then gets suspended, it will always resume on the same thread.

Let's see some code now:

```<code>public class EventLoopExample {

static Map<String, AtomicInteger> threadCounts = new ConcurrentHashMap<>();

public static void main(String[] args) {
    printActive("Before starting VertX");

    Vertx vertx = Vertx.vertx();

    printActive("After starting VertX");
    for (int i = 0; i < 1000; i++) {
        vertx.deployVerticle(new MyVerticle());
        printActive("Regular verticle deployed");
    }

    printActive("Before deploying worker verticles");
    for (int i = 0; i < 1000; i++) {
        vertx.deployVerticle(new MyVerticle(), new DeploymentOptions().setWorker(true));
        printActive("Worker verticle deployed");
    }

    printActive("After everything deployed");

    System.out.println(new TreeMap(threadCounts));

    AtomicInteger count = new AtomicInteger(0);
    threadCounts.forEach((key, value) -> {
        count.addAndGet(value.get());
    });

    System.out.println(count.get());
}

private static void printActive(String message) {
    System.out.println(message);
    System.out.println(Thread.activeCount());
}

static class MyVerticle extends AbstractVerticle {

    @Override
    public void start() {
        threadCounts.putIfAbsent(Thread.currentThread().getName(), new AtomicInteger(0));
        threadCounts.get(Thread.currentThread().getName()).incrementAndGet();
    }

    @Override
    public void stop() throws Exception {
        System.out.println("Stopped");
    }
}
}
</code>```

Note:
Before VertX starts you have 2 threads active

Startup of VertX adds 2 more threads, even if you don't have verticles deployed

Number of EventLoop threads is defined by number of cores. Since I have 8 cores, VertX creates maximum of 8 threads.

Worker pool is 20 threads by default.

So, unless you create more WorkerPools or play with configuration any other way, VertX won't use more than ~32 threads.

Body:
Actually, this part is covered quite well: http://vertx.io/docs/vertx-core/java/#_reactor_and_multi_reactor

Vert.x works differently here. Instead of a single event loop, each
  Vertx instance maintains several event loops. By default we choose the
  number based on the number of available cores on the machine, but this
  can be overridden.

Where you're wrong is that verticle bound to a thread is a verticle occupying a thread. Let's say you have 4 CPUs and 1 verticle. VertX will allocate 4 threads to it's EventLoop. You start 100 vertices? VertX will still use 4 threads.

But, if Verticle34, let's say, starts on Thread2, then gets suspended, it will always resume on the same thread.

Let's see some code now:

public class EventLoopExample {

static Map<String, AtomicInteger> threadCounts = new ConcurrentHashMap<>();

public static void main(String[] args) {
    printActive("Before starting VertX");

    Vertx vertx = Vertx.vertx();

    printActive("After starting VertX");
    for (int i = 0; i < 1000; i++) {
        vertx.deployVerticle(new MyVerticle());
        printActive("Regular verticle deployed");
    }

    printActive("Before deploying worker verticles");
    for (int i = 0; i < 1000; i++) {
        vertx.deployVerticle(new MyVerticle(), new DeploymentOptions().setWorker(true));
        printActive("Worker verticle deployed");
    }

    printActive("After everything deployed");

    System.out.println(new TreeMap(threadCounts));

    AtomicInteger count = new AtomicInteger(0);
    threadCounts.forEach((key, value) -> {
        count.addAndGet(value.get());
    });

    System.out.println(count.get());
}

private static void printActive(String message) {
    System.out.println(message);
    System.out.println(Thread.activeCount());
}

static class MyVerticle extends AbstractVerticle {

    @Override
    public void start() {
        threadCounts.putIfAbsent(Thread.currentThread().getName(), new AtomicInteger(0));
        threadCounts.get(Thread.currentThread().getName()).incrementAndGet();
    }

    @Override
    public void stop() throws Exception {
        System.out.println("Stopped");
    }
}
}

Note:
Before VertX starts you have 2 threads active

Startup of VertX adds 2 more threads, even if you don't have verticles deployed

Number of EventLoop threads is defined by number of cores. Since I have 8 cores, VertX creates maximum of 8 threads.

Worker pool is 20 threads by default.

So, unless you create more WorkerPools or play with configuration any other way, VertX won't use more than ~32 threads.


问:
Ada pass array of records to c function
I know that a similar question has already been posted, but its solution doesn't work for me. In my spec file I have the code:

```<code>type Colour_Component is mod 256;

type Colour is
    record
        A, R, G, B : Colour_Component;
    end record;

type Raw_Image_Data is array (Interfaces.C.int range <>) of Colour;

type Raw_Image is access all Raw_Image_Data;
pragma Convention (C, Raw_Image);
</code>```

Then I try to interface with a C function:

```<code>function C_SDL_CreateRGBSurfaceFrom (
    Pixels : Raw_Image;
    Width : int;
    Height : int;
    Depth : int;
    Pitch : int;
    Rmask : Unsigned_32;
    Gmask : Unsigned_32;
    Bmask : Unsigned_32;
    Amask : Unsigned_32)
    return System.Address;
pragma Import (C, C_SDL_CreateRGBSurfaceFrom, "SDL_CreateRGBSurfaceFrom");
</code>```

But when I try to compile it I get a warning:

```<code>warning: type of "C_SDL_CreateRGBSurfaceFrom.Pixels" does not correspond to C pointer
warning: this access type does not correspond to C pointer
</code>```

Since I have my compiler flags set to treat warnings as errors this doesn't compile. Any advice on how to fix this?

答:
Ada arrays come in two flavours, constrained and unconstrained arrays. C arrays are constrained (newer C standards also have dynamically sized arrays), but if you pass C arrays around function calls you either terminate them with a zero element or with a separate length parameter.

Anyway, you declared your parameter Raw_Image as an unconstrained array. There is no counterpart in C. You can only pass constrained arrays from or to C.

I think you have two options: (1) use address to access conversion or (2) use the binding generator -fdump-ada-spec

(1) declare your first parameter as of type System.Address and use the package System.Address_To_Access_Conversions

(2) The easiest way is to use the gcc switch -fdump-ada-spec on a C header. See Generating Ada Bindings for C and C++ headers

Title: Ada pass array of records to c function

Body:
I know that a similar question has already been posted, but its solution doesn't work for me. In my spec file I have the code:

type Colour_Component is mod 256;

type Colour is
    record
        A, R, G, B : Colour_Component;
    end record;

type Raw_Image_Data is array (Interfaces.C.int range <>) of Colour;

type Raw_Image is access all Raw_Image_Data;
pragma Convention (C, Raw_Image);

Then I try to interface with a C function:

function C_SDL_CreateRGBSurfaceFrom (
    Pixels : Raw_Image;
    Width : int;
    Height : int;
    Depth : int;
    Pitch : int;
    Rmask : Unsigned_32;
    Gmask : Unsigned_32;
    Bmask : Unsigned_32;
    Amask : Unsigned_32)
    return System.Address;
pragma Import (C, C_SDL_CreateRGBSurfaceFrom, "SDL_CreateRGBSurfaceFrom");

But when I try to compile it I get a warning:

warning: type of "C_SDL_CreateRGBSurfaceFrom.Pixels" does not correspond to C pointer
warning: this access type does not correspond to C pointer

Since I have my compiler flags set to treat warnings as errors this doesn't compile. Any advice on how to fix this?


问:
Using Python and Mechanize to submit form data and authenticate
I want to submit login to the website Reddit.com, navigate to a particular area of the page, and submit a comment.  I don't see what's wrong with this code, but it is not working in that no change is reflected on the Reddit site.

```<code>import mechanize
import cookielib

def main():

#Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

#Opens the site to be navigated
r= br.open('http://www.reddit.com')
html = r.read()

# Select the second (index one) form
br.select_form(nr=1)

# User credentials
br.form['user'] = 'DUMMYUSERNAME'
br.form['passwd'] = 'DUMMYPASSWORD'

# Login
br.submit()

#Open up comment page
r= br.open('http://www.reddit.com/r/PoopSandwiches/comments/f47f8/testing/')
html = r.read()

#Text box is the 8th form on the page (which, I believe, is the text area)
br.select_form(nr=7)

#Change 'text' value to a testing string
br.form['text']= "this is an automated test"

#Submit the information
br.submit()
</code>```

What's wrong with this?

答:
I would definitely suggest trying to use the API if possible, but this works for me (not for your example post, which has been deleted, but for any active one):

```<code>#!/usr/bin/env python

import mechanize
import cookielib
import urllib
import logging
import sys

def main():

    br = mechanize.Browser()
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)

    br.set_handle_equiv(True)
    br.set_handle_gzip(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

    r= br.open('http://www.reddit.com')

    # Select the second (index one) form
    br.select_form(nr=1)

    # User credentials
    br.form['user'] = 'user'
    br.form['passwd'] = 'passwd'

    # Login
    br.submit()

    # Open up comment page
    posting = 'http://www.reddit.com/r/PoopSandwiches/comments/f47f8/testing/'
    rval = 'PoopSandwiches'
    # you can get the rval in other ways, but this will work for testing

    r = br.open(posting)

    # You need the 'uh' value from the first form
    br.select_form(nr=0)
    uh = br.form['uh']

    br.select_form(nr=7)
    thing_id = br.form['thing_id']
    id = '#' + br.form.attrs['id']
    # The id that gets posted is the form id with a '#' prepended.

    data = {'uh':uh, 'thing_id':thing_id, 'id':id, 'renderstyle':'html', 'r':rval, 'text':"Your text here!"}
    new_data_dict = dict((k, urllib.quote(v).replace('%20', '+')) for k, v in data.iteritems())

    # not sure if the replace needs to happen, I did it anyway
    new_data = 'thing_id=%(thing_id)s&text=%(text)s&id=%(id)s&r=%(r)s&uh=%(uh)s&renderstyle=%(renderstyle)s' %(new_data_dict)

    # not sure which of these headers are really needed, but it works with all
    # of them, so why not just include them.
    req = mechanize.Request('http://www.reddit.com/api/comment', new_data)
    req.add_header('Referer', posting)
    req.add_header('Accept', ' application/json, text/javascript, */*')
    req.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    req.add_header('X-Requested-With', 'XMLHttpRequest')
    cj.add_cookie_header(req)
    res = mechanize.urlopen(req)

main()
</code>```

It would be interesting to turn javascript off and see how the reddit comments are handled then.  Right now there is a bunch of magic that happens in an onsubmit function called when making your post.  This is where the uh and id value get added.

Body:
I want to submit login to the website Reddit.com, navigate to a particular area of the page, and submit a comment.  I don't see what's wrong with this code, but it is not working in that no change is reflected on the Reddit site.

import mechanize
import cookielib

def main():

#Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

#Opens the site to be navigated
r= br.open('http://www.reddit.com')
html = r.read()

# Select the second (index one) form
br.select_form(nr=1)

# User credentials
br.form['user'] = 'DUMMYUSERNAME'
br.form['passwd'] = 'DUMMYPASSWORD'

# Login
br.submit()

#Open up comment page
r= br.open('http://www.reddit.com/r/PoopSandwiches/comments/f47f8/testing/')
html = r.read()

#Text box is the 8th form on the page (which, I believe, is the text area)
br.select_form(nr=7)

#Change 'text' value to a testing string
br.form['text']= "this is an automated test"

#Submit the information
br.submit()

What's wrong with this?

Body:
I would definitely suggest trying to use the API if possible, but this works for me (not for your example post, which has been deleted, but for any active one):

#!/usr/bin/env python

import mechanize
import cookielib
import urllib
import logging
import sys

def main():

    br = mechanize.Browser()
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)

    br.set_handle_equiv(True)
    br.set_handle_gzip(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

    r= br.open('http://www.reddit.com')

    # Select the second (index one) form
    br.select_form(nr=1)

    # User credentials
    br.form['user'] = 'user'
    br.form['passwd'] = 'passwd'

    # Login
    br.submit()

    # Open up comment page
    posting = 'http://www.reddit.com/r/PoopSandwiches/comments/f47f8/testing/'
    rval = 'PoopSandwiches'
    # you can get the rval in other ways, but this will work for testing

    r = br.open(posting)

    # You need the 'uh' value from the first form
    br.select_form(nr=0)
    uh = br.form['uh']

    br.select_form(nr=7)
    thing_id = br.form['thing_id']
    id = '#' + br.form.attrs['id']
    # The id that gets posted is the form id with a '#' prepended.

    data = {'uh':uh, 'thing_id':thing_id, 'id':id, 'renderstyle':'html', 'r':rval, 'text':"Your text here!"}
    new_data_dict = dict((k, urllib.quote(v).replace('%20', '+')) for k, v in data.iteritems())

    # not sure if the replace needs to happen, I did it anyway
    new_data = 'thing_id=%(thing_id)s&text=%(text)s&id=%(id)s&r=%(r)s&uh=%(uh)s&renderstyle=%(renderstyle)s' %(new_data_dict)

    # not sure which of these headers are really needed, but it works with all
    # of them, so why not just include them.
    req = mechanize.Request('http://www.reddit.com/api/comment', new_data)
    req.add_header('Referer', posting)
    req.add_header('Accept', ' application/json, text/javascript, */*')
    req.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    req.add_header('X-Requested-With', 'XMLHttpRequest')
    cj.add_cookie_header(req)
    res = mechanize.urlopen(req)

main()

It would be interesting to turn javascript off and see how the reddit comments are handled then.  Right now there is a bunch of magic that happens in an onsubmit function called when making your post.  This is where the uh and id value get added.


答:
To deal with larger files, it's a good idea to read in chunks of fixed size. If you try to open an image, for example, and don't use buffered reading, you'll get a MemoryError.

```<code>def read_file(filename):
    BUFFER_SIZE = 65536
    contents = []
    with open(filename, "r") as f:
        while True:
            chunk = filename.read(BUFFER_SIZE)
            if not chunk:
                break
            contents.append(chunk)
    return "".join(contents)
</code>```

Title: How to convert an already open file to string?

Body:
Given an open file, return the contents as a string.( This assumes the autotester test the function with a random file so the variable should be open to multiple files of the same type)

def read_file(myfile):
'''(file) -> str
Read the open file and return as a string.'''

Body:
To deal with larger files, it's a good idea to read in chunks of fixed size. If you try to open an image, for example, and don't use buffered reading, you'll get a MemoryError.

def read_file(filename):
    BUFFER_SIZE = 65536
    contents = []
    with open(filename, "r") as f:
        while True:
            chunk = filename.read(BUFFER_SIZE)
            if not chunk:
                break
            contents.append(chunk)
    return "".join(contents)


问:
JavaScript Reset Input with a Condition
I am trying to reset some input fields for a login if the loginDiv display is none, however it is not working at all.

Desired Outcome: click the login button, so long as the loginDiv display is none, the two input fields will be reset.

Here is my code:

// LOGIN
const logDiv = document.getElementById('loginDiv');
const wrong = document.getElementById('wrong');
const user = document.getElementById('user');
const pass = document.getElementById('pass');
const log = document.getElementById('logBtn');

log.addEventListener('click', () => {
  if (user.value == 'f' && pass.value == 'f') {
    logDiv.style.display = 'none';
    wrong.style.display = 'none';
  } else {
    wrong.style.display = 'block';
  }
});

// LOGOUT

const logout = document.getElementById('logout');

logout.addEventListener('click', () => {
  if (logDiv.style.display == 'none') {
    logDiv.style.display = 'block';
  }
});

function resetForm() {
  if (logDiv.style.display == 'none') {
    user.reset();
    pass.reset();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="loginDiv">
  <input id="user" type="text" placeholder="username"></input>
  <input id="pass" type="password" placeholder="password"></input>
  <button id="logBtn" onclick="resetForm()">login</button>
</div>
<div id="wrong" style="display: none;">
  <p id="wrongText">incorrect login info.</p>
</div>

<div id="logoutDiv">
  <button id="logout" type="button">logout</button>
</div></code>```

答:
Yoy can'n click to button login , if this button is not visible , and you
can reset data in input trougth next code:

```<code>function resetForm() {
    user.value='';
    pass.value='';
}
</code>```

I think that best way is using resetForm in

```<code> logDiv.style.display = 'none';
    wrong.style.display = 'none';
    resetForm();
</code>```

Using onclick is not good way, because your code has many location.

Full code for example :
HTML:

```<code>  <div id="loginDiv">
      <input id="user" type="text" placeholder="username">
      <input id="pass" type="password" placeholder="password">
      <button id="logBtn">login</button>
    </div>
    <div id="wrong" style="display: none;">
      <p id="wrongText">incorrect login info.</p>
    </div>

    <div id="logoutDiv">
      <button id="logout" type="button">logout</button>
    </div>
</code>```

JS:

```<code>//LOGIN
      const logDiv = document.getElementById('loginDiv');
      const wrong = document.getElementById('wrong');
      const user = document.getElementById('user');
      const pass = document.getElementById('pass');
      const log = document.getElementById('logBtn');

      log.addEventListener('click', () => {
        if (user.value == 'f' && pass.value == 'f') {
          logDiv.style.display = 'none';
          wrong.style.display = 'none';
          resetForm();
        } else {
          wrong.style.display = 'block';
        }
      });

      // LOGOUT

      const logout = document.getElementById('logout');

      logout.addEventListener('click', () => {
        if (logDiv.style.display == 'none') {
          logDiv.style.display = 'block';
        }
      });

      function resetForm() {

        user.value = '';
        pass.value = '';
      }
</code>```

Title: JavaScript Reset Input with a Condition

Body:
I am trying to reset some input fields for a login if the loginDiv display is none, however it is not working at all.

Desired Outcome: click the login button, so long as the loginDiv display is none, the two input fields will be reset.

Here is my code:

// LOGIN
const logDiv = document.getElementById('loginDiv');
const wrong = document.getElementById('wrong');
const user = document.getElementById('user');
const pass = document.getElementById('pass');
const log = document.getElementById('logBtn');

log.addEventListener('click', () => {
  if (user.value == 'f' && pass.value == 'f') {
    logDiv.style.display = 'none';
    wrong.style.display = 'none';
  } else {
    wrong.style.display = 'block';
  }
});

// LOGOUT

const logout = document.getElementById('logout');

logout.addEventListener('click', () => {
  if (logDiv.style.display == 'none') {
    logDiv.style.display = 'block';
  }
});

function resetForm() {
  if (logDiv.style.display == 'none') {
    user.reset();
    pass.reset();
  }
}

  <input id="user" type="text" placeholder="username"></input>
  <input id="pass" type="password" placeholder="password"></input>
  <button id="logBtn" onclick="resetForm()">login</button>

incorrect login info.

  <button id="logout" type="button">logout</button>

Body:
Yoy can'n click to button login , if this button is not visible , and you
can reset data in input trougth next code:

function resetForm() {
    user.value='';
    pass.value='';
}

I think that best way is using resetForm in

 logDiv.style.display = 'none';
    wrong.style.display = 'none';
    resetForm();

Using onclick is not good way, because your code has many location.

Full code for example :
HTML:

  <div id="loginDiv">
      <input id="user" type="text" placeholder="username">
      <input id="pass" type="password" placeholder="password">
      <button id="logBtn">login</button>
    </div>
    <div id="wrong" style="display: none;">
      <p id="wrongText">incorrect login info.</p>
    </div>

    <div id="logoutDiv">
      <button id="logout" type="button">logout</button>
    </div>

JS:

//LOGIN
      const logDiv = document.getElementById('loginDiv');
      const wrong = document.getElementById('wrong');
      const user = document.getElementById('user');
      const pass = document.getElementById('pass');
      const log = document.getElementById('logBtn');

      log.addEventListener('click', () => {
        if (user.value == 'f' && pass.value == 'f') {
          logDiv.style.display = 'none';
          wrong.style.display = 'none';
          resetForm();
        } else {
          wrong.style.display = 'block';
        }
      });

      // LOGOUT

      const logout = document.getElementById('logout');

      logout.addEventListener('click', () => {
        if (logDiv.style.display == 'none') {
          logDiv.style.display = 'block';
        }
      });

      function resetForm() {

        user.value = '';
        pass.value = '';
      }


问:
Android license "LICENSED RESPONSE" error
I have problem in testing the "LICENSED" response of LVL. I already changed the test license response in dashboard in edit profile in market web site.

When I set to "NOT LICENSED", it will prompt to buy or exit, but if I set to LICENSE, after waiting for "CHECKING LICENSE" progress bar, it will not load my main activity page, the check license loops infinitely, and I need to force close the process. I already added licensecheck Java file name in the manifest and included the intent section.

The following is what I have captured in logcat. Anyone have an idea what's going on? How do I fix my code?

```<code>I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Binding to licensing service.
I/ActivityManager(   59): Start proc com.android.vending for service com.android.vending/.licensing.LicensingService: pid=320 uid=10019 gids
={3003}
I/LicenseChecker(  312): Calling checkLicense on service for com.test.apps1
I/ActivityManager(   59): Displayed activity com.test.apps1/.MActivity: 3586 ms (total 3586 ms)
I/LicenseChecker(  312): Start monitoring timeout.
I/ARMAssembler(   59): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x305798:0x305854] in 914005 ns
D/GoogleLoginService(  170): onBind: Intent { act=android.accounts.AccountAuthenticator cmp=com.google.android.gsf/.loginservice.GoogleLogin
Service }
I/LicenseChecker(  312): Received response.
I/LicenseChecker(  312): Clearing timeout.
E/LicenseValidator(  312): CORI APP LICENSED!
W/ServerManagedPolicy(  312): License validity timestamp (VT) missing, caching for a minute
W/ServerManagedPolicy(  312): License retry timestamp (GT) missing, grace period disabled
W/ServerManagedPolicy(  312): Licence retry count (GR) missing, grace period disabled
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
D/dalvikvm(  312): GC_FOR_MALLOC freed 3870 objects / 267592 bytes in 92ms
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
W/ActivityManager(   59): Launch timeout has expired, giving up wake lock!
W/ActivityManager(   59): Activity idle timeout for HistoryRecord{44003148 com.test.apps1/.MActivity}
</code>```

```<code>public void allow()
{
    Log.d("LicenseChecker","Allow");
    //Log.i("LICENSE", "allow");
    if (isFinishing())
    {
        // Don't update UI if Activity is finishing.
        return;
    }
    // Should allow user access.
    displayResult(getString(R.string.allow));

    // Should allow user access.
    startMainActivity();
}
</code>```

Is this related to the cache response timestamp? If yes, how can I change and modify it?

```<code>W/ServerManagedPolicy(  312): License validity timestamp (VT) missing, caching for a minute
W/ServerManagedPolicy(  312): License retry timestamp (GT) missing, grace period disabled
W/ServerManagedPolicy(  312): Licence retry count (GR) missing, grace period disabled
</code>```

Do I need to modify ServerManagedPolicy?

```<code>public boolean allowAccess() {
    long ts = System.currentTimeMillis();
    if (mLastResponse == LicenseResponse.LICENSED) {
        // Check if the LICENSED response occurred within the validity timeout.
        if (ts <= mValidityTimestamp) {
            // Cached LICENSED response is still valid.
            return true;
        }
    } else if (mLastResponse == LicenseResponse.RETRY &&
               ts < mLastResponseTime + MILLIS_PER_MINUTE) {
        // Only allow access if we are within the retry period or we haven't used up our
        // max retries.
        return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
    }
    return false;
}
</code>```

Also, how can I do the following?

When there is no license (either no license in Google server or no cached license), then prompt disallow and go to market.

When there is a cached license, allow user to run apps (no matter if there is no network or no network connection).

When there is a license in Google server (network mode), but no cached license, allow user to run apps.

答: The messages about missing VT, GT, and GR are normal when you set the test response to anything other than "Respond normally." There may be a logic problem in your code. It might help if you could post the code for startMainActivity() and also your onCreate() method (and any relevant methods they call).</p>

Body:
I have problem in testing the "LICENSED" response of LVL. I already changed the test license response in dashboard in edit profile in market web site.

When I set to "NOT LICENSED", it will prompt to buy or exit, but if I set to LICENSE, after waiting for "CHECKING LICENSE" progress bar, it will not load my main activity page, the check license loops infinitely, and I need to force close the process. I already added licensecheck Java file name in the manifest and included the intent section.

The following is what I have captured in logcat. Anyone have an idea what's going on? How do I fix my code?

I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Binding to licensing service.
I/ActivityManager(   59): Start proc com.android.vending for service com.android.vending/.licensing.LicensingService: pid=320 uid=10019 gids
={3003}
I/LicenseChecker(  312): Calling checkLicense on service for com.test.apps1
I/ActivityManager(   59): Displayed activity com.test.apps1/.MActivity: 3586 ms (total 3586 ms)
I/LicenseChecker(  312): Start monitoring timeout.
I/ARMAssembler(   59): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x305798:0x305854] in 914005 ns
D/GoogleLoginService(  170): onBind: Intent { act=android.accounts.AccountAuthenticator cmp=com.google.android.gsf/.loginservice.GoogleLogin
Service }
I/LicenseChecker(  312): Received response.
I/LicenseChecker(  312): Clearing timeout.
E/LicenseValidator(  312): CORI APP LICENSED!
W/ServerManagedPolicy(  312): License validity timestamp (VT) missing, caching for a minute
W/ServerManagedPolicy(  312): License retry timestamp (GT) missing, grace period disabled
W/ServerManagedPolicy(  312): Licence retry count (GR) missing, grace period disabled
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
D/dalvikvm(  312): GC_FOR_MALLOC freed 3870 objects / 267592 bytes in 92ms
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
I/LicenseChecker(  312): Using cached license response
D/LicenseChecker(  312): Allow
I/ActivityManager(   59): Starting activity: Intent { cmp=com.test.apps1/.MActivity }
I/LICENSE (  312): checkLicense
W/ActivityManager(   59): Launch timeout has expired, giving up wake lock!
W/ActivityManager(   59): Activity idle timeout for HistoryRecord{44003148 com.test.apps1/.MActivity}

public void allow()
{
    Log.d("LicenseChecker","Allow");
    //Log.i("LICENSE", "allow");
    if (isFinishing())
    {
        // Don't update UI if Activity is finishing.
        return;
    }
    // Should allow user access.
    displayResult(getString(R.string.allow));

    // Should allow user access.
    startMainActivity();
}

Is this related to the cache response timestamp? If yes, how can I change and modify it?

W/ServerManagedPolicy(  312): License validity timestamp (VT) missing, caching for a minute
W/ServerManagedPolicy(  312): License retry timestamp (GT) missing, grace period disabled
W/ServerManagedPolicy(  312): Licence retry count (GR) missing, grace period disabled

Do I need to modify ServerManagedPolicy?

public boolean allowAccess() {
    long ts = System.currentTimeMillis();
    if (mLastResponse == LicenseResponse.LICENSED) {
        // Check if the LICENSED response occurred within the validity timeout.
        if (ts <= mValidityTimestamp) {
            // Cached LICENSED response is still valid.
            return true;
        }
    } else if (mLastResponse == LicenseResponse.RETRY &&
               ts < mLastResponseTime + MILLIS_PER_MINUTE) {
        // Only allow access if we are within the retry period or we haven't used up our
        // max retries.
        return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
    }
    return false;
}

Also, how can I do the following?

When there is no license (either no license in Google server or no cached license), then prompt disallow and go to market.

When there is a cached license, allow user to run apps (no matter if there is no network or no network connection).

When there is a license in Google server (network mode), but no cached license, allow user to run apps.


问:
How to avoid bad Code with StackNavigator in React Native Navigation
I am just starting to learn React Native and in my Navigation I noticed something that i would consider a Code smell and I would like to know, how I could make this better.

So I am using react-navigation and a StackNavigator. I do have some Views, that you have to navigate in a row, like View1 -> View2 -> View 3, etc. But to navigate from the View2 to View3, I usually hand the navigation item in the params, so I am able to acces it again in the other views. So i usually end up with code like this:

```<code>navigateToDetailPage() {
    const {navigation} = this.props.navigation.state.params;

    navigation.navigate('GameSessionDetailPage', {
        navigation: navigation
    });
}
</code>```

I am not using Redux right now, so far, as i wanted to understand the fundamentals first. But would this be a case where i should put the navigation into the redux store? From what I understood, redux should reflect your application state and not be a big data/object dump. But I feel like I am getting into a long chain of "navigation object passing" that seems fragile and very coupled to me. Is there some best practice you guys would reccomend?

答:
You don't need to pass through the navigation object. It will get added to the next components props automatically

```<code>navigateToDetailPage() {
    const {navigation} = this.props;

    navigation.navigate('GameSessionDetailPage');
}
</code>```

Then in GameSessionDetailPage you will have this.props.navigation available.

No need to use Redux here.

Body:
I am just starting to learn React Native and in my Navigation I noticed something that i would consider a Code smell and I would like to know, how I could make this better.

So I am using react-navigation and a StackNavigator. I do have some Views, that you have to navigate in a row, like View1 -> View2 -> View 3, etc. But to navigate from the View2 to View3, I usually hand the navigation item in the params, so I am able to acces it again in the other views. So i usually end up with code like this:

navigateToDetailPage() {
    const {navigation} = this.props.navigation.state.params;

    navigation.navigate('GameSessionDetailPage', {
        navigation: navigation
    });
}

I am not using Redux right now, so far, as i wanted to understand the fundamentals first. But would this be a case where i should put the navigation into the redux store? From what I understood, redux should reflect your application state and not be a big data/object dump. But I feel like I am getting into a long chain of "navigation object passing" that seems fragile and very coupled to me. Is there some best practice you guys would reccomend?

Body:
You don't need to pass through the navigation object. It will get added to the next components props automatically

navigateToDetailPage() {
    const {navigation} = this.props;

    navigation.navigate('GameSessionDetailPage');
}

Then in GameSessionDetailPage you will have this.props.navigation available.

No need to use Redux here.


问:
Is it possible to build a portable webapp when using oracle with django
I started developing a django webapp which will need to connect to oracle databases. But using oracle with django requires an Oracle client if I'm not mistaken which is platform dependant. If it's not possible to create a portable webapp with django and oracle, could the app use an oracle client install on the machine where the app is running?

Thanks

答:
What do you mean by "portable" exactly ? You can definitely move your Django folder around, especially if you use SQLite for database storage, since a SQLite database is just a file.

All you'll need is Python on the target machine, access to the command line and the ability to install your dependencies with pip.

Then you can just run your webapp with python manage.py runserver.

If this doesn't answer your question, please give more info.


问:
Reordering LabelNodes causes their offset to mess up in Java ASM
I have the following sample code:

```<code>    Label L1654589030
    Line 3, L1654589030
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init>()V
    RETURN
    Label L466002798
</code>```

I perform a basic transformation, reordering instructions and labels and inserting two GOTO instructions:

```<code>    GOTO L1654589030
    Label L466002798
    RETURN
    Label L1654589030
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init>()V
    GOTO L466002798
</code>```

However, when frames are being calculated by ASM, it throws an ArrayIndexOutOfBoundsException at org.objectweb.asm.ClassReader.createDebugLabel. In createDebugLabel, ASM tries to access a label at offset 65539, thus crashing. I can work this issue around by replacing the LabelNode I moved up with a new LabelNode, but that means I'll also have to update all instructions referencing it. Why is issue occurring?

EDIT1 | CheckClassAdapter returns the following dump:

```<code><init>()V
00000 Main  :  :     GOTO L0
00001 Main  :  :    L1
00002 Main  :  :    FRAME FULL [com/company/Main] []
00003 Main  :  :     RETURN
00004 Main  :  :    L0
00005 Main  :  :    FRAME FULL [U] []
00006 Main  :  :     ALOAD 0
00007 Main  : Main  :     INVOKESPECIAL java/lang/Object.<init> ()V
00008 Main  :  :     GOTO L1
</code>```

FRAME FULL should not be there, but how can I fix that?

答: SOLVED: The MethodNode.localVariables -> start / end labels didn't form a region after I reordered their instruction nodes. I had to manually update each variable.

Body:
I have the following sample code:

    Label L1654589030
    Line 3, L1654589030
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init>()V
    RETURN
    Label L466002798

I perform a basic transformation, reordering instructions and labels and inserting two GOTO instructions:

    GOTO L1654589030
    Label L466002798
    RETURN
    Label L1654589030
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init>()V
    GOTO L466002798

However, when frames are being calculated by ASM, it throws an ArrayIndexOutOfBoundsException at org.objectweb.asm.ClassReader.createDebugLabel. In createDebugLabel, ASM tries to access a label at offset 65539, thus crashing. I can work this issue around by replacing the LabelNode I moved up with a new LabelNode, but that means I'll also have to update all instructions referencing it. Why is issue occurring?

EDIT1 | CheckClassAdapter returns the following dump:

<init>()V
00000 Main  :  :     GOTO L0
00001 Main  :  :    L1
00002 Main  :  :    FRAME FULL [com/company/Main] []
00003 Main  :  :     RETURN
00004 Main  :  :    L0
00005 Main  :  :    FRAME FULL [U] []
00006 Main  :  :     ALOAD 0
00007 Main  : Main  :     INVOKESPECIAL java/lang/Object.<init> ()V
00008 Main  :  :     GOTO L1

FRAME FULL should not be there, but how can I fix that?


问:
What does the error "Compile with /main to specify the type that contains the entry point." mean
I was troubleshooting steps I could find in relation to an IIS 502.5 error with no success.

In desperation I tried starting over using dotnet publish from the command line and got a build error telling me there were 2 entry points in the application and that I needed to "Compile with /main to specify the type that contains the entry point."  First I checked my solution to verify that there is only 1 Main() method in the project. Even though the target namespace is specified in the csproj file, I leave no stone unturned and attempt to run dotnet build with a /main switch only to be told that /main is an unknown switch.

So...what is that error message is telling me and where might I look next to discover what I am certain will be an embarrassing developer error.

答:
As you have already found out, the test SDK automatically generates an additional code file to make sure that there is a main method in test ""libraries"" (which are then made an application) - this is purely to make use of build logic that is only triggered for applications to create a "runnable" output even though the main method is never called and only side effects of creating an applications are used by the test runner.

The error about the /main parameter is generated by the compiler. When invoking the csc.exe compiler directly, this is the parameter to use when specifying which main method to use if there are multiple options.

However, the build tooling that is used to build project files (.csproj) uses msbuild logic which then invokes the compiler. This msbuild tooling will only understand msbuild-specific parameters and not parameters of csc. Unfortunately, the error message was authored under the assumption that the csc command line host was used to perform the compilation.

MSBuild uses the StartupObject property to pass this configuration option to the compiler. So one could either specify it inside the csproj file (assuming a static MyLib.AlternativeProgram.Main() method):

```<code><PropertyGroup>
  <StartupObject>MyLib.AlternativeProgram</StartupObject>
</PropertyGroup>
</code>```

or specify it as arguments to commands that understand the msbuild syntax for setting properties:

```<code>$ dotnet build /p:StartupObject=MyLib.AlternativeProgram

> msbuild.exe /p:StartupObject=MyLib.AlternativeProgram
</code>```

Body:
As you have already found out, the test SDK automatically generates an additional code file to make sure that there is a main method in test ""libraries"" (which are then made an application) - this is purely to make use of build logic that is only triggered for applications to create a "runnable" output even though the main method is never called and only side effects of creating an applications are used by the test runner.

The error about the /main parameter is generated by the compiler. When invoking the csc.exe compiler directly, this is the parameter to use when specifying which main method to use if there are multiple options.

However, the build tooling that is used to build project files (.csproj) uses msbuild logic which then invokes the compiler. This msbuild tooling will only understand msbuild-specific parameters and not parameters of csc. Unfortunately, the error message was authored under the assumption that the csc command line host was used to perform the compilation.

MSBuild uses the StartupObject property to pass this configuration option to the compiler. So one could either specify it inside the csproj file (assuming a static MyLib.AlternativeProgram.Main() method):

<PropertyGroup>
  <StartupObject>MyLib.AlternativeProgram</StartupObject>
</PropertyGroup>

or specify it as arguments to commands that understand the msbuild syntax for setting properties:

$ dotnet build /p:StartupObject=MyLib.AlternativeProgram

> msbuild.exe /p:StartupObject=MyLib.AlternativeProgram


问:
how to use JQuery "toggle" with parameters?
I have a table like this:

```<code><table>
  <tr>
    <td><input type="button" title="Toggle" value="Show" id="btn534534" class="toggle" />    </td>
    <td>some data about ID 534534</td>
  </tr>
  <tr id="row534534" class="hiddenRow">
    <td colspan="2">some hidden data about ID 534534 that must show/hide with toggle</td>
  </tr>
  <tr>
    <td><input type="button" title="Toggle" value="Show" id="btn2423434" class="toggle" /></td>
    <td>some data about ID 2423434</td>
  </tr>
  <tr id="row2423434" class="hiddenRow">
    <td colspan="2">some hidden data about ID 2423434that must show/hide with toggle</td>
  </tr>
  <!-- many more rows here -->
</table>
</code>```

There are MANY "sets" of rows like the above.  One row of the table is visible for each "set" of rows.  The second row with class "hiddenRow" is hidden on page load by JQuery like this:

```<code>$("tr.hiddenRow").hide();
</code>```

Now I want each button to toggle visibility of the row immediately after it.  Note that the INPUT in the visible row, and the TR of the hidden row share a unique ID.  I want to have the button onclick call a JQuery function and pass the ID so that JQuery knows which row to toggle.

Any ideas?  I can't find any examples of this online.

答:
use a custom method like this one:

```<code>    <script type="text/javascript">
        function viewToggle(id){
            $('#'+id).slideToggle(500);
        }
    </script>
</code>```

And then have each button call the function above passing in the value of the id you would like to toggle the view of:

```<code><table>
  <tr>
    <td><input type="button" onclick="viewToggle('row534534');" title="Toggle" value="Show" id="btn534534" class="toggle" />    </td>
    <td>some data about ID 534534</td>
  </tr>
  <tr id="row534534" class="hiddenRow">
    <td colspan="2">some hidden data about ID 534534 that must show/hide with toggle</td>
  </tr>
  <tr>
    <td><input type="button" onclick="viewToggle('row2423434');" title="Toggle" value="Show" id="btn2423434" class="toggle" /></td>
    <td>some data about ID 2423434</td>
  </tr>
  <tr id="row2423434" class="hiddenRow">
    <td colspan="2">some hidden data about ID 2423434that must show/hide with toggle</td>
  </tr>
  <!-- many more rows here -->
</table>
</code>```

Body:
I have a table like this:

    <input type="button" title="Toggle" value="Show" id="btn534534" class="toggle" />
    some data about ID 534534

    some hidden data about ID 534534 that must show/hide with toggle

    <input type="button" title="Toggle" value="Show" id="btn2423434" class="toggle" />
    some data about ID 2423434

    some hidden data about ID 2423434that must show/hide with toggle

There are MANY "sets" of rows like the above.  One row of the table is visible for each "set" of rows.  The second row with class "hiddenRow" is hidden on page load by JQuery like this:

$("tr.hiddenRow").hide();

Now I want each button to toggle visibility of the row immediately after it.  Note that the INPUT in the visible row, and the TR of the hidden row share a unique ID.  I want to have the button onclick call a JQuery function and pass the ID so that JQuery knows which row to toggle.

Any ideas?  I can't find any examples of this online.

Body:
use a custom method like this one:

    <script type="text/javascript">
        function viewToggle(id){
            $('#'+id).slideToggle(500);
        }
    </script>

And then have each button call the function above passing in the value of the id you would like to toggle the view of:

<table>
  <tr>
    <td><input type="button" onclick="viewToggle('row534534');" title="Toggle" value="Show" id="btn534534" class="toggle" />    </td>
    <td>some data about ID 534534</td>
  </tr>
  <tr id="row534534" class="hiddenRow">
    <td colspan="2">some hidden data about ID 534534 that must show/hide with toggle</td>
  </tr>
  <tr>
    <td><input type="button" onclick="viewToggle('row2423434');" title="Toggle" value="Show" id="btn2423434" class="toggle" /></td>
    <td>some data about ID 2423434</td>
  </tr>
  <tr id="row2423434" class="hiddenRow">
    <td colspan="2">some hidden data about ID 2423434that must show/hide with toggle</td>
  </tr>
  <!-- many more rows here -->
</table>


问:
Setting Master/Detail's first appearance to the Master view, not the Detail view
This question has been asked a couple of times but I seem to have serious issues understanding the concept. This is how the part looks like right now

A TabBarController leads to the master on the left. Now, where am I supposed to put the splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController . . . in this setup? I tried it at numerous places, tried setting delegates, ... but it doesn't even get called. I can't even provide real code as there is nothing to show.

I got a class for the TableViewCell, one for the DetailViewController, and one for the TableViewController.

If anyone could point me at what point I should add abovementioned method so it gets called and prevents the app from jumping straight into the Detail view, I'd really appreciate that.

Thanks so much

答:
Ok, the missing part was not setting the delegate to what I've set the other controllers' delegates to.

I now have 2 masters (still no idea where the "template-created" master got the delegate-association from) and my new master's split view's delegate is the same file the other one uses. There, the splitViewController . . . gets called and I can manipulate with return YES.