问:
Change Font Color for certain Words
I use ultraTextEditor via Infragistics.

I want to find 'Select' word and make it for color to blue. How can i do this ?

```<code>if (uteSQL.Text.Contains("Select"))
    {
         // Make All 'Select' words blue
    }
</code>```

答:
UltraTextEditor does not provide such functionality. As you are using Infragistics controls you can switch to UltraFormattedTextEditor. In UltraFormattedTextEditor you can change the color of each Select word to blue like this:</p>

```<code>var input = this.ultraFormattedTextEditor1.Value.ToString();
var result = input.Replace("Select", "<span style=\"color: Blue;\">Select</span>");
this.ultraFormattedTextEditor1.Value = result;
</code>```

Title: Change Font Color for certain Words

Body:
I use ultraTextEditor via Infragistics.

I want to find 'Select' word and make it for color to blue. How can i do this ?

if (uteSQL.Text.Contains("Select"))
    {
         // Make All 'Select' words blue
    }

Body:
UltraTextEditor does not provide such functionality. As you are using Infragistics controls you can switch to UltraFormattedTextEditor. In UltraFormattedTextEditor you can change the color of each Select word to blue like this:

var input = this.ultraFormattedTextEditor1.Value.ToString();
var result = input.Replace("Select", "<span style=\"color: Blue;\">Select</span>");
this.ultraFormattedTextEditor1.Value = result;


来源: stackexchange

问:
How to create copy of file using StreamReader and StreamWriter
I need to use StreamReader to read a .txt file on a console application, then create a new file or backup with a different name but same content. The problem is i cant figure out how to use the content from the first file to place into the new one. (This is for a school thing and im new to C#)</p>

```<code>using System;
using System.IO;
namespace UserListCopier
{
    class Program
    {
        static void Main()
        {
            string fineName = "zombieList.txt";

            StreamReader reader = new StreamReader(fineName);

            int lineNumber = 0;

            string line = reader.ReadLine();

            while (line != null) {
                lineNumber++;
                Console.WriteLine("Line {0}: {1}", lineNumber, line);
                line = reader.ReadLine();
            }

            StreamWriter writetext = new StreamWriter("zombieListBackup.txt");

            writetext.Close();
            System.Console.Read();
            reader.Close();
        }
    }
}
</code>```

答:
For files on the disk, you just need File.Copy(inputPath, outputPath). I'm not certain whether this streams the content efficiently, or whether it reads it all into memory and then writes it all out in one go.

So for large files, or if you have a stream that doesn't resolve to a path on the disk, you can efficiently copy from one to the other, using the following functions:

```<code>private void copyFile(string inputPath, string outputPath)
{
    using (var inputStream = StreamReader(inputPath))
    {
        using (var outputStream = StreamWriter(outputPath))
        {
            copyToOutputStream(inputStream, outputStream);
        }
    }
}

private void copyToOutputStream(StreamReader inputStream, StreamWriter outputStream)
{
    string line = null;
    while ((line = inputStream.ReadLine()) != null)
    {
        outputStream.WriteLine(line);
    }
    outputStream.Write(inputStream.ReadToEnd());
}
</code>```

This function copies from the input stream to the output stream one line at a time until the input stream ends. This means it only has one line in memory at a time (rather than the whole file) and that it can begin writing to the disk before the first stream has finished being read in / generated.

ContentLicense: CC BY-SA 3.0

Body:
I need to use StreamReader to read a .txt file on a console application, then create a new file or backup with a different name but same content. The problem is i cant figure out how to use the content from the first file to place into the new one. (This is for a school thing and im new to C#)

using System;
using System.IO;
namespace UserListCopier
{
    class Program
    {
        static void Main()
        {
            string fineName = "zombieList.txt";

            StreamReader reader = new StreamReader(fineName);

            int lineNumber = 0;

            string line = reader.ReadLine();

            while (line != null) {
                lineNumber++;
                Console.WriteLine("Line {0}: {1}", lineNumber, line);
                line = reader.ReadLine();
            }

            StreamWriter writetext = new StreamWriter("zombieListBackup.txt");

            writetext.Close();
            System.Console.Read();
            reader.Close();
        }
    }
}

Body:
For files on the disk, you just need File.Copy(inputPath, outputPath). I'm not certain whether this streams the content efficiently, or whether it reads it all into memory and then writes it all out in one go.

So for large files, or if you have a stream that doesn't resolve to a path on the disk, you can efficiently copy from one to the other, using the following functions:

private void copyFile(string inputPath, string outputPath)
{
    using (var inputStream = StreamReader(inputPath))
    {
        using (var outputStream = StreamWriter(outputPath))
        {
            copyToOutputStream(inputStream, outputStream);
        }
    }
}

private void copyToOutputStream(StreamReader inputStream, StreamWriter outputStream)
{
    string line = null;
    while ((line = inputStream.ReadLine()) != null)
    {
        outputStream.WriteLine(line);
    }
    outputStream.Write(inputStream.ReadToEnd());
}

This function copies from the input stream to the output stream one line at a time until the input stream ends. This means it only has one line in memory at a time (rather than the whole file) and that it can begin writing to the disk before the first stream has finished being read in / generated.


问:
Creating MongoDB image error from Docker official tutorial
Here is the official tutorial to create mongoDB img.

I followed exactly the tutorial and generated the following Dockerfile

```<code># https://docs.docker.com/engine/examples/mongodb/#creating-a-dockerfile-for-mongodb
# Dockerizing MongoDB: Dockerfile for building MongoDB images
# Based on ubuntu:latest, installs MongoDB following the instructions from:
# http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

# Format: FROM    repository[:version]
FROM       ubuntu:latest

# Installation:
# Import MongoDB public GPG key AND create a MongoDB list file
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
RUN apt-get install -y --no-install-recommends software-properties-common
RUN echo "deb http://repo.mongodb.org/apt/ubuntu $(cat /etc/lsb-release | grep DISTRIB_CODENAME | cut -d= -f2)/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list

# Update apt-get sources AND install MongoDB
RUN apt-get update && apt-get install -y mongodb-org

# MongoDB requires a data directory. Let’s create it as the final step of our installation instructions.
# Create the MongoDB data directory
RUN mkdir -p /data/db

# Expose port 27017 from the container to the host
EXPOSE 27017

# Set usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]
</code>```

But when I execute

```<code>$ docker build --tag my/repo .
</code>```

I got the following error:

What is going on? Why it fails? How to fix it?

EDIT:

After adjust the command order, my final script is this:

```<code># Format: FROM    repository[:version]
FROM       ubuntu:latest

# Update apt-get sources AND install MongoDB
RUN apt-get update

# Installation:
# Import MongoDB public GPG key AND create a MongoDB list file
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
RUN apt-get install -y --no-install-recommends software-properties-common
# RUN echo "deb http://repo.mongodb.org/apt/ubuntu $(cat /etc/lsb-release | grep DISTRIB_CODENAME | cut -d= -f2)/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

RUN apt-get install -y mongodb-org

# MongoDB requires a data directory. Let’s create it as the final step of our installation instructions.
# Create the MongoDB data directory
RUN mkdir -p /data/db

# Expose port 27017 from the container to the host
EXPOSE 27017

# Set usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]
</code>```

Then I got the following error:

Next, then I added "RUN apt-get install sudo", then I got the following error:

3 strikes down, I am not confident this whole thing will work. Here is my final Dockerfile.

```<code>    # https://docs.docker.com/engine/examples/mongodb/#creating-a-dockerfile-for-mongodb
    # Dockerizing MongoDB: Dockerfile for building MongoDB images
    # Based on ubuntu:latest, installs MongoDB following the instructions from:
    # http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

# Format: FROM    repository[:version]
FROM       ubuntu:latest

# Update apt-get sources AND install MongoDB
RUN apt-get update

# Installation:
# Import MongoDB public GPG key AND create a MongoDB list file
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
RUN apt-get install -y --no-install-recommends software-properties-common

RUN apt-get install sudo

# RUN echo "deb http://repo.mongodb.org/apt/ubuntu $(cat /etc/lsb-release | grep DISTRIB_CODENAME | cut -d= -f2)/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

RUN apt-get install -y mongodb-org

# MongoDB requires a data directory. Let’s create it as the final step of our installation instructions.
# Create the MongoDB data directory
RUN mkdir -p /data/db

# Expose port 27017 from the container to the host
EXPOSE 27017

# Set usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]
</code>```

If you can make it work, please paste your Dockerfile and I'd love to learn what is wrong in my script. I followed the tutorial and it doesn't work.

答:
A quick google search for your exact error message found this.

This is an error from apt saying it can't find the software-properties-common package in its repositories. When a package change be found, it usually means apt needs updating.

You are running apt-get update but you're running it after the update line.

```<code>RUN apt-get install -y --no-install-recommends software-properties-common
...
RUN apt-get update && apt-get install -y mongodb-org
</code>```

Instead, run it first

```<code>RUN apt-get update
RUN apt-get install -y --no-install-recommends software-properties-common
...
RUN apt-get install -y mongodb-org
</code>```

Update: Your update says you're now getting an error when installing the mongodb package. This is because you've loaded a deb package file and need to update apt yet again so that it knows about it. At this point, the easiest thing to do is just prefix any apt-get commands that complain about not finding packages with an update.

```<code>RUN apt-get update && apt-get install -y --no-install-recommends software-properties-common
...
RUN apt-get update && apt-get install -y mongodb-org
</code>```

Body:
Here is the official tutorial to create mongoDB img.

I followed exactly the tutorial and generated the following Dockerfile

# https://docs.docker.com/engine/examples/mongodb/#creating-a-dockerfile-for-mongodb
# Dockerizing MongoDB: Dockerfile for building MongoDB images
# Based on ubuntu:latest, installs MongoDB following the instructions from:
# http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

# Format: FROM    repository[:version]
FROM       ubuntu:latest

# Installation:
# Import MongoDB public GPG key AND create a MongoDB list file
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
RUN apt-get install -y --no-install-recommends software-properties-common
RUN echo "deb http://repo.mongodb.org/apt/ubuntu $(cat /etc/lsb-release | grep DISTRIB_CODENAME | cut -d= -f2)/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list

# Update apt-get sources AND install MongoDB
RUN apt-get update && apt-get install -y mongodb-org

# MongoDB requires a data directory. Let’s create it as the final step of our installation instructions.
# Create the MongoDB data directory
RUN mkdir -p /data/db

# Expose port 27017 from the container to the host
EXPOSE 27017

# Set usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]

But when I execute

$ docker build --tag my/repo .

I got the following error:

What is going on? Why it fails? How to fix it?

EDIT:

After adjust the command order, my final script is this:

# Format: FROM    repository[:version]
FROM       ubuntu:latest

# Update apt-get sources AND install MongoDB
RUN apt-get update

# Installation:
# Import MongoDB public GPG key AND create a MongoDB list file
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
RUN apt-get install -y --no-install-recommends software-properties-common
# RUN echo "deb http://repo.mongodb.org/apt/ubuntu $(cat /etc/lsb-release | grep DISTRIB_CODENAME | cut -d= -f2)/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

RUN apt-get install -y mongodb-org

# MongoDB requires a data directory. Let’s create it as the final step of our installation instructions.
# Create the MongoDB data directory
RUN mkdir -p /data/db

# Expose port 27017 from the container to the host
EXPOSE 27017

# Set usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]

Then I got the following error:

Next, then I added "RUN apt-get install sudo", then I got the following error:

3 strikes down, I am not confident this whole thing will work. Here is my final Dockerfile.

    # https://docs.docker.com/engine/examples/mongodb/#creating-a-dockerfile-for-mongodb
    # Dockerizing MongoDB: Dockerfile for building MongoDB images
    # Based on ubuntu:latest, installs MongoDB following the instructions from:
    # http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

# Format: FROM    repository[:version]
FROM       ubuntu:latest

# Update apt-get sources AND install MongoDB
RUN apt-get update

# Installation:
# Import MongoDB public GPG key AND create a MongoDB list file
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
RUN apt-get install -y --no-install-recommends software-properties-common

RUN apt-get install sudo

# RUN echo "deb http://repo.mongodb.org/apt/ubuntu $(cat /etc/lsb-release | grep DISTRIB_CODENAME | cut -d= -f2)/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

RUN apt-get install -y mongodb-org

# MongoDB requires a data directory. Let’s create it as the final step of our installation instructions.
# Create the MongoDB data directory
RUN mkdir -p /data/db

# Expose port 27017 from the container to the host
EXPOSE 27017

# Set usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]

If you can make it work, please paste your Dockerfile and I'd love to learn what is wrong in my script. I followed the tutorial and it doesn't work.

Body:
A quick google search for your exact error message found this.

This is an error from apt saying it can't find the software-properties-common package in its repositories. When a package change be found, it usually means apt needs updating.

You are running apt-get update but you're running it after the update line.

RUN apt-get install -y --no-install-recommends software-properties-common
...
RUN apt-get update && apt-get install -y mongodb-org

Instead, run it first

RUN apt-get update
RUN apt-get install -y --no-install-recommends software-properties-common
...
RUN apt-get install -y mongodb-org

Update: Your update says you're now getting an error when installing the mongodb package. This is because you've loaded a deb package file and need to update apt yet again so that it knows about it. At this point, the easiest thing to do is just prefix any apt-get commands that complain about not finding packages with an update.

RUN apt-get update && apt-get install -y --no-install-recommends software-properties-common
...
RUN apt-get update && apt-get install -y mongodb-org


问:
mod_rewrite forwarding always forwarding to index page
I have some basic URL forwarding set up in my .htaccess file to create seo friendly links. My problem is that after I added the first two rules any url that begins xxxxxx.com/cm/en forwards to the index page. xxxxxx.com/cm/en/about-condominium-calle-margarita-santa-ana gets forwarded to cm/en_index. I'm sure there is something basic I'm missing here, any help appreciated.</p>

```<code>RewriteRule ^cm/en cm/en_index.php [L]
RewriteRule ^cm/es cm/index.php [L]

RewriteRule ^cm/en/about-condominium-calle-margarita-santa-ana cm/en_about.php [L]
RewriteRule ^cm/es/nuestro-apartamentos-calle-margarita-santa-ana cm/es_about.php [L]
</code>```

答:
The answer for me was to add a $ to the end of ^cm/en.

So I used:

```<code>RewriteRule ^cm/en$ cm/en_index.php [L]
RewriteRule ^cm/es$ cm/index.php [L]
</code>```

I'm guessing the $ means that for that rule to match there can be no more text after the cm/en or cm/es. I'm sure someone else can give a proper explanation!

Body:
I have some basic URL forwarding set up in my .htaccess file to create seo friendly links. My problem is that after I added the first two rules any url that begins xxxxxx.com/cm/en forwards to the index page. xxxxxx.com/cm/en/about-condominium-calle-margarita-santa-ana gets forwarded to cm/en_index. I'm sure there is something basic I'm missing here, any help appreciated.

RewriteRule ^cm/en cm/en_index.php [L]
RewriteRule ^cm/es cm/index.php [L]

RewriteRule ^cm/en/about-condominium-calle-margarita-santa-ana cm/en_about.php [L]
RewriteRule ^cm/es/nuestro-apartamentos-calle-margarita-santa-ana cm/es_about.php [L]

Body:
The answer for me was to add a $ to the end of ^cm/en.

So I used:

RewriteRule ^cm/en$ cm/en_index.php [L]
RewriteRule ^cm/es$ cm/index.php [L]

I'm guessing the $ means that for that rule to match there can be no more text after the cm/en or cm/es. I'm sure someone else can give a proper explanation!


问:
Open an excel file and write values to
I want to open an excel sheet and write values to it.

Therefore I wrote this

```<code>Private Sub Test()

Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("C:\Users\Marc\Dropbox\PROJECTEN\Lopend\office_VA\macroStore.xlsx", True, False)
xlWorkBook.sheets(1).Range("A2").Select

Set xlApp = Nothing
Set xlWorkBook = Nothing

End Sub
</code>```

This all works. But the thing is that now everytime a new excel file is opened. And I just would like to open an existing one. Any thoughts on how to change this?

答:
Try this:

```<code>Sub Test()

Dim xlApp As Object
Dim xlWorkBook As Object
Dim path As String
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True

path = "C:\Users\Marc\Dropbox\PROJECTEN\Lopend\office_VA\macroStore.xlsx"
If IsFileOpen(path) Then
    Set xlWorkBook = GetObject(path)
Else
    Set xlWorkBook = xlApp.Workbooks.Open(path)
End If

Set xlApp = Nothing
Set xlWorkBook = Nothing

End Sub

Function IsFileOpen(filename As String)
    Dim filenum As Integer, errnum As Integer

    On Error Resume Next   ' Turn error checking off.
    filenum = FreeFile()   ' Get a free file number.
    ' Attempt to open the file and lock it.
    Open filename For Input Lock Read As #filenum
    Close filenum          ' Close the file.
    errnum = Err           ' Save the error number that occurred.
    On Error GoTo 0        ' Turn error checking back on.

    ' Check to see which error occurred.
    Select Case errnum

        ' No error occurred.
        ' File is NOT already open by another user.
        Case 0
         IsFileOpen = False

        ' Error number for "Permission Denied."
        ' File is already opened by another user.
        Case 70
            IsFileOpen = True

        ' Another error occurred.
        Case Else
            Error errnum
    End Select

End Function
</code>```

Note: Function is taken from Microsoft site

Title: Open an excel file and write values to

Body:
I want to open an excel sheet and write values to it.

Therefore I wrote this

Private Sub Test()

Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("C:\Users\Marc\Dropbox\PROJECTEN\Lopend\office_VA\macroStore.xlsx", True, False)
xlWorkBook.sheets(1).Range("A2").Select

Set xlApp = Nothing
Set xlWorkBook = Nothing

End Sub

This all works. But the thing is that now everytime a new excel file is opened. And I just would like to open an existing one. Any thoughts on how to change this?

Body:
Try this:

Sub Test()

Dim xlApp As Object
Dim xlWorkBook As Object
Dim path As String
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True

path = "C:\Users\Marc\Dropbox\PROJECTEN\Lopend\office_VA\macroStore.xlsx"
If IsFileOpen(path) Then
    Set xlWorkBook = GetObject(path)
Else
    Set xlWorkBook = xlApp.Workbooks.Open(path)
End If

Set xlApp = Nothing
Set xlWorkBook = Nothing

End Sub

Function IsFileOpen(filename As String)
    Dim filenum As Integer, errnum As Integer

    On Error Resume Next   ' Turn error checking off.
    filenum = FreeFile()   ' Get a free file number.
    ' Attempt to open the file and lock it.
    Open filename For Input Lock Read As #filenum
    Close filenum          ' Close the file.
    errnum = Err           ' Save the error number that occurred.
    On Error GoTo 0        ' Turn error checking back on.

    ' Check to see which error occurred.
    Select Case errnum

        ' No error occurred.
        ' File is NOT already open by another user.
        Case 0
         IsFileOpen = False

        ' Error number for "Permission Denied."
        ' File is already opened by another user.
        Case 70
            IsFileOpen = True

        ' Another error occurred.
        Case Else
            Error errnum
    End Select

End Function

Note: Function is taken from Microsoft site


问:
Second promise is not working properly
I have the following promise that works perfectly:

```<code>self.getAll = function (callback) {
    var users= [];
    var promises = [];
    $.ajax({
        url: "/API/Users",
        type: "GET",
        success: function (results) {
            var mappedContacts = $.map(results, function (item) {
                promises.push($.ajax({
                    url: "/API/Users/contacts/" + item.id,
                    type: "GET"
                }).then(function (contacts) {
                    users.push(new User(item, contacts));
                }));
            });
            $.when.apply($, promises).then(function () {
                callback(users);
            });
        }
    });
}
</code>```

I'm trying to add a second AJAX request but it's not working properly:

```<code>self.getAll = function (callback) {
    var users= [];
    var promises = [];
    $.ajax({
        url: "/API/Users",
        type: "GET",
        success: function (results) {
            var mappedContacts = $.map(results, function (item) {
                promises.push($.ajax({
                    url: "/API/Users/contacts/" + item.id,
                    type: "GET"
                }).then(function (contacts) {
                    users.push(new User(item, contacts));
                }));
            });
            var mappedContacts2 = $.map(results, function (item) {
                promises.push($.ajax({
                    url: "/API/Users/contacts2/" + item.id,
                    type: "GET"
                }).then(function (contacts2) {
                    users.push(new User(item, "",contacts2));
                }));
            });
            $.when.apply($, promises).then(function () {
                callback(users);
            });
        }
    });
}
</code>```

contacts2 is always empty, what am I doing wrong?

This is the User object:

```<code>var User= function (data, contacts, contacts2) {
    this.id = ko.observable(data.id);
    this.name = ko.observable(data.name);
    this.contacts = ko.observableArray(contacts);
    this.contacts2 = ko.observableArray(contacts2 );
}
</code>```

答:
Since you need both sets of contacts for each user to pass to new User() use one map() that returns a $.when() for both contacts requests. Create the user in then() of that $.when()

Something like:

```<code>self.getAll = function(callback) {
  var users = [];
  // return this promise ..... see notes below
  return $.getJSON("/API/Users").then(results) {

    // map array of promises to pass to final $.when
    var promises = $.map(results, function(item) {

      var req1 = $.getJSON("/API/Users/contacts/" + item.id);
      var req2 = $.getJSON("/API/Users/contacts2/" + item.id);

      // return this promise to mapped array
      return $.when(req1, req2).then(function(contacts1, contacts2) {
        // create user now that we have both sets of contacts
        users.push(new User(item, contacts1, contacts2));
      });
    })

    // should return this promise .... see notes below
    return $.when.apply($, promises).then(function() {
      callback(users);
      // return `users` ...see notes below
    });

  })
}
</code>```

Using a callback is an outdated approach when you could just return the promise chain shown in comments above and do :

```<code>self.getAll().then(function(users) {
  // do something with users
})
</code>```

Title: Second promise is not working properly

Body:
I have the following promise that works perfectly:

self.getAll = function (callback) {
    var users= [];
    var promises = [];
    $.ajax({
        url: "/API/Users",
        type: "GET",
        success: function (results) {
            var mappedContacts = $.map(results, function (item) {
                promises.push($.ajax({
                    url: "/API/Users/contacts/" + item.id,
                    type: "GET"
                }).then(function (contacts) {
                    users.push(new User(item, contacts));
                }));
            });
            $.when.apply($, promises).then(function () {
                callback(users);
            });
        }
    });
}

I'm trying to add a second AJAX request but it's not working properly:

self.getAll = function (callback) {
    var users= [];
    var promises = [];
    $.ajax({
        url: "/API/Users",
        type: "GET",
        success: function (results) {
            var mappedContacts = $.map(results, function (item) {
                promises.push($.ajax({
                    url: "/API/Users/contacts/" + item.id,
                    type: "GET"
                }).then(function (contacts) {
                    users.push(new User(item, contacts));
                }));
            });
            var mappedContacts2 = $.map(results, function (item) {
                promises.push($.ajax({
                    url: "/API/Users/contacts2/" + item.id,
                    type: "GET"
                }).then(function (contacts2) {
                    users.push(new User(item, "",contacts2));
                }));
            });
            $.when.apply($, promises).then(function () {
                callback(users);
            });
        }
    });
}

contacts2 is always empty, what am I doing wrong?

This is the User object:

var User= function (data, contacts, contacts2) {
    this.id = ko.observable(data.id);
    this.name = ko.observable(data.name);
    this.contacts = ko.observableArray(contacts);
    this.contacts2 = ko.observableArray(contacts2 );
}

Body:
Since you need both sets of contacts for each user to pass to new User() use one map() that returns a $.when() for both contacts requests. Create the user in then() of that $.when()

Something like:

self.getAll = function(callback) {
  var users = [];
  // return this promise ..... see notes below
  return $.getJSON("/API/Users").then(results) {

    // map array of promises to pass to final $.when
    var promises = $.map(results, function(item) {

      var req1 = $.getJSON("/API/Users/contacts/" + item.id);
      var req2 = $.getJSON("/API/Users/contacts2/" + item.id);

      // return this promise to mapped array
      return $.when(req1, req2).then(function(contacts1, contacts2) {
        // create user now that we have both sets of contacts
        users.push(new User(item, contacts1, contacts2));
      });
    })

    // should return this promise .... see notes below
    return $.when.apply($, promises).then(function() {
      callback(users);
      // return `users` ...see notes below
    });

  })
}

Using a callback is an outdated approach when you could just return the promise chain shown in comments above and do :

self.getAll().then(function(users) {
  // do something with users
})


问:
How to make a thumbnail created by a function clickable in html?
I am trying to make clickable thumbnails in my html code but I cannot figure out how to do it. I know href = ""> won't work. How can I make each thumbnail clickable so that it directs to another page?

Here are the functions I used to get data from the database and to create the thumbnail
`

```<code><script>
        $(function(){
                $.ajax({
                    url: '/getMovies',
                type: 'GET',
                    success:function(response) {
                    console.log(response);
                    var data = JSON.parse(response);
                    var itemsPerRow = 0;
                    var div = $('<div>').attr('class','row');
                    for(var i=0;i<data.length;i++){
                        console.log(data[i].Title);

                        if(itemsPerRow<3){
                            console.log(i);
                            if(i==data.length-1){
                                div.append(CreateThumb(data[i].Id,data[i].Name,data[i].Type,data[i].Copies));
                                $('.well').append(div);
                            }
                            else{
                            div.append(CreateThumb(data[i].Id,data[i].Name,data[i].Type,data[i].Copies));
                            itemsPerRow++;
                            }
                        }
                        else{
                            $('.well').append(div);
                            div = $('<div>').attr('class','row');
                            div.append(CreateThumb(data[i].Id,data[i].Name,data[i].Type,data[i].Copies));
                            if(i==data.length-1){
                                $('.well').append(div);
                            }
                            itemsPerRow = 1;
                        }
                    }

                    },
                    error:function(error){
                        console.log(error);
                    }
                });
            });
        })

        function CreateThumb(id,name,type,copies){
            var mainDiv = $('<div>').attr('class','col-sm-4 col-md-4');
            var thumbNail = $('<div>').attr('class','thumbnail');
            var caption = $('<div>').attr('class','caption');
            var title = $('<h3>').text(name);
            var title = $('<h5>').text(type);
            var title = $('<h4>').text(copies);
            var p = $('<p>');

            caption.append(name);
            caption.append(p);
            caption.append(type);
            thumbNail.append(caption);
            mainDiv.append(thumbNail);
            return mainDiv;

        }
    </script>
</code>```

`.

答:
After you've added the thumbnails use:</p>

```<code>$(".thumbnail").onclick(function(){
    document.location.href = newUrl;
}
</code>```

Body:
I am trying to make clickable thumbnails in my html code but I cannot figure out how to do it. I know  won't work. How can I make each thumbnail clickable so that it directs to another page?

Here are the functions I used to get data from the database and to create the thumbnail
`

`.

Body:
After you've added the thumbnails use:

$(".thumbnail").onclick(function(){
    document.location.href = newUrl;
}


问:
How to make a div hide when having same set of classes?
I have two set of div containers with input tags with same classes to both.
only difference is when input box of each clicked the resepctive parent div will add "frame-focus" class. what i want is if input is clicked and frame-focus class is exist, hide the div which has class "panel-set" of which the focus class exist. </p>

<p>Please check my div containers below. please advice how to proceed this
Ex: </p>

```<code><!--- here is 1st div container which input box is selected-->
    <div class="block">
    <div class="frame frame-focus">
    <input name="set1">
    <div class="panel-set"></div>
    </div>
    </div>

<!-- here is 2nd div -->
    <div class="block">
    <div class="frame">
    <input name="set1">
    <div class="panel-set"></div>
    </div>
    </div>
</code>```

答:
Use the child selector or the direct child selector to hide the .panel-set which is a child of .frame-focus:

.frame-focus > .panel-set {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--- here is 1st div container which input box is selected-->
<div class="block">
  <div class="frame frame-focus">
    <input name="set1">
    <div class="panel-set">1</div>
  </div>
</div>

<!-- here is 2nd div -->
<div class="block">
  <div class="frame">
    <input name="set1">
    <div class="panel-set">2</div>
  </div>
</div></code>```

Body:
I have two set of div containers with input tags with same classes to both.
only difference is when input box of each clicked the resepctive parent div will add "frame-focus" class. what i want is if input is clicked and frame-focus class is exist, hide the div which has class "panel-set" of which the focus class exist.

Please check my div containers below. please advice how to proceed this
Ex:

    <input name="set1">

    <input name="set1">

Body:
Use the child selector or the direct child selector to hide the .panel-set which is a child of .frame-focus:

.frame-focus > .panel-set {
  display: none;
}

<!--- here is 1st div container which input box is selected-->
<div class="block">
  <div class="frame frame-focus">
    <input name="set1">
    <div class="panel-set">1</div>
  </div>
</div>

<!-- here is 2nd div -->
<div class="block">
  <div class="frame">
    <input name="set1">
    <div class="panel-set">2</div>
  </div>
</div>


问:
Neo4J - How to create a new node based on splitting an existing relationship property and automatically creating a link?
I have a network of nodes which represent People which are connected by relationships (Emails).

The Receiver of the Email is m.slug

Based on:  ()-[r]-(m)

I wish to split the property (in this case "Sender" / m.slug ie Larry@google.com)and create a new node "Google.com" AS Company (i.e so I now have a set of Company nodes created from the existing information).

I want to then link Google (the company) to my Person Node (Larry@Google.com).

--

How would you approach this, without creating multiple duplicate Company nodes? (i.e for Sergey@Google.com & Larry@Google.com should be connected to the same Google.com Company Node).

Visual Representation of People and relationships

Example syntax of queries and relationship properties

答:
This is how you can ensure there is a unique Company node for each email address domain name, and associate it (via an AT relationship) with each Person with an email address in that domain. The domain name is lower-cased before storing, to ensure uniqueness, since email addresses frequently come with different casing.

```<code>MATCH (n:Person)
MERGE (c:Company {name: TOLOWER(SPLIT(n.slug, '@')[1])})
CREATE (n)-[:AT]->(c);
</code>```

NOTE: The above query should only be executed ONCE, since the CREATE clause would create the relationship every time, even if it already exists. You can replace CREATE with MERGE if you need to run the query multiple times.

Body:
This is how you can ensure there is a unique Company node for each email address domain name, and associate it (via an AT relationship) with each Person with an email address in that domain. The domain name is lower-cased before storing, to ensure uniqueness, since email addresses frequently come with different casing.

MATCH (n:Person)
MERGE (c:Company {name: TOLOWER(SPLIT(n.slug, '@')[1])})
CREATE (n)-[:AT]->(c);

NOTE: The above query should only be executed ONCE, since the CREATE clause would create the relationship every time, even if it already exists. You can replace CREATE with MERGE if you need to run the query multiple times.


问:
SQL Server: Group By based on one column and get columns based on other column
My data:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes
</code>```

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
</code>```

How do I select all values that satisfy above rule?

答:
I think the filtering would actually be better handled by the 'WHERE' clause instead of 'HAVING'.

True the original request stated "Select only those groups of A that contain Yes and Null both in the result of a" BUT no aggr is needed to limit the rows. I don't know if there is an additional cost to using the SUM function but why do the additional work.

I don't know if it is a far comparison but why would you go to the store, pick up a bunch of apples and when you get to the register, start pulling some of the out that are going bad?

Try this:

```<code>SELECT ColumnA, ColumnB, ColumnC
FROM myTable
WHERE ColumnC IS NULL || ColumnC = 'yes'
--GROUP BY ColumnA, ColumnB, ColumnC --commented per additional comment below.
</code>```

One more note. Please double check your sample data, if you are grouping I cant tell as all you did was exclude the row with 'c' as the value for columnA. Also, I would assume that the two rows:

```<code>ColumnA                 Column B            ColumnC
B                          Hola                Yes
</code>```

would have been only showing as one as they would have been grouped together, but in you sample output you have it there twice...

Body:
My data:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL

How do I select all values that satisfy above rule?

Body:
I think the filtering would actually be better handled by the 'WHERE' clause instead of 'HAVING'.

True the original request stated "Select only those groups of A that contain Yes and Null both in the result of a" BUT no aggr is needed to limit the rows. I don't know if there is an additional cost to using the SUM function but why do the additional work.

I don't know if it is a far comparison but why would you go to the store, pick up a bunch of apples and when you get to the register, start pulling some of the out that are going bad?

Try this:

SELECT ColumnA, ColumnB, ColumnC
FROM myTable
WHERE ColumnC IS NULL || ColumnC = 'yes'
--GROUP BY ColumnA, ColumnB, ColumnC --commented per additional comment below.

One more note. Please double check your sample data, if you are grouping I cant tell as all you did was exclude the row with 'c' as the value for columnA. Also, I would assume that the two rows:

ColumnA                 Column B            ColumnC
B                          Hola                Yes

would have been only showing as one as they would have been grouped together, but in you sample output you have it there twice...


问:
SELECT certain fields based on certain WHERE conditions
I am writing an advanced MySQL query that searches a database and retrieves user information. What I am wondering is can I select certain fields if WHERE condition 1 is met and select other fields if WHERE condition 2 is met?

Database: users

```<code>------------------------
| user_id | first_name |
------------------------
|    1    |    John    |
------------------------
|    2    |    Chris   |
------------------------
|    3    |     Sam    |
------------------------
|    4    |    Megan   |
------------------------
</code>```

Database: friendship

```<code>--------------------------------------
| user_id_one | user_id_two | status |
--------------------------------------
|      2      |      4      |    0   |
--------------------------------------
|      4      |      1      |    1   |
--------------------------------------

Status 0 = Unconfirmed
Status 1 = Confirmed
</code>```

OK, as you can see John & Megan are confirmed friends while Chris & Megan are friends but the relationship is unconfirmed.

The query I am trying to write is as follow: Megan(4) searches for new friends I want all of the users except for the ones she is a confirmed friend with to be returned. So, the results should return 2,3. But since a relationship with user_id 2 exists but is not confirmed, I want to also return the status since an entry in the friendship table does exist between the two. If a user exist but there is no connection in the relationship table it still returns that users information but returns status as a NULL or doesn't return status at all since it doesn't exist in that table.

I hope this makes since. Ask questions if you need to.

答:
You can create to separate queries and then UNION the result tables.  In each query, add a field that always has the same value.

So something like this should work:

```<code>(SELECT id, 'Not Friends' As Status FROM t1 WHERE condition1)
UNION
(SELECT id, 'Unconfirmed' As Status FROM t1 WHERE condition2)
</code>```

Just make sure the same number and name of fields exists in both queries.

ContentLicense: CC BY-SA 2.5

Body:
I am writing an advanced MySQL query that searches a database and retrieves user information. What I am wondering is can I select certain fields if WHERE condition 1 is met and select other fields if WHERE condition 2 is met?

Database: users

------------------------
| user_id | first_name |
------------------------
|    1    |    John    |
------------------------
|    2    |    Chris   |
------------------------
|    3    |     Sam    |
------------------------
|    4    |    Megan   |
------------------------

Database: friendship

--------------------------------------
| user_id_one | user_id_two | status |
--------------------------------------
|      2      |      4      |    0   |
--------------------------------------
|      4      |      1      |    1   |
--------------------------------------

Status 0 = Unconfirmed
Status 1 = Confirmed

OK, as you can see John & Megan are confirmed friends while Chris & Megan are friends but the relationship is unconfirmed.

The query I am trying to write is as follow: Megan(4) searches for new friends I want all of the users except for the ones she is a confirmed friend with to be returned. So, the results should return 2,3. But since a relationship with user_id 2 exists but is not confirmed, I want to also return the status since an entry in the friendship table does exist between the two. If a user exist but there is no connection in the relationship table it still returns that users information but returns status as a NULL or doesn't return status at all since it doesn't exist in that table.

I hope this makes since. Ask questions if you need to.

Body:
You can create to separate queries and then UNION the result tables.  In each query, add a field that always has the same value.

So something like this should work:

(SELECT id, 'Not Friends' As Status FROM t1 WHERE condition1)
UNION
(SELECT id, 'Unconfirmed' As Status FROM t1 WHERE condition2)

Just make sure the same number and name of fields exists in both queries.


问:
MySql join one to many relationship - for a specific userid within date range
I'm trying to draft a MySQL query to count the number of occurrences of a status code within a date range (2017-03-01 to 2017-04-01) for a specific user (userid = 41).

Here is the query I was trying to use, but not making much progress:

```<code>SELECT
  u.status,
  COUNT(*) AS countStatus
FROM (SELECT programid, userid FROM portal_program_evalsusers WHERE userid=41) c
LEFT JOIN (
   SELECT
    programid,
    status
    FROM portal_program_eval
    WHERE (portal_program_eval.date >= '2017-03-01' AND portal_program_eval.date <= '2017-04-01')
    GROUP BY status
) u ON u.programid = c.programid
  GROUP BY u.status
</code>```

Here is information about the tables:

```<code>Tbl portal_program_eval
--------------------------
programid (primary key)
status
date

Tbl portal_program_evalsusers [relational table]
--------------------------
programid
userid
</code>```

What am I doing wrong with the query?

The desired output is each status and the count:

```<code> --------------------------
 status  | countStatus
      1  |        6
      2  |       23
      3  |       14
</code>```

答:
After some additional trial and error, I believe I found the answer to my question:</p>

```<code>SELECT
  u.status,
  COUNT(*) AS countStatus
FROM (SELECT programid, userid FROM portal_program_evalsusers WHERE userid=41 GROUP BY programid) c
LEFT JOIN (
   SELECT
    programid,
    status,
    date
    FROM portal_program_eval
    GROUP BY programid
) u ON c.programid = u.programid
  WHERE (u.date >= 2017-03-01 AND u.date < 2017-04-01)
  GROUP BY u.status
</code>```

Body:
I'm trying to draft a MySQL query to count the number of occurrences of a status code within a date range (2017-03-01 to 2017-04-01) for a specific user (userid = 41).

Here is the query I was trying to use, but not making much progress:

SELECT
  u.status,
  COUNT(*) AS countStatus
FROM (SELECT programid, userid FROM portal_program_evalsusers WHERE userid=41) c
LEFT JOIN (
   SELECT
    programid,
    status
    FROM portal_program_eval
    WHERE (portal_program_eval.date >= '2017-03-01' AND portal_program_eval.date <= '2017-04-01')
    GROUP BY status
) u ON u.programid = c.programid
  GROUP BY u.status

Here is information about the tables:

Tbl portal_program_eval
--------------------------
programid (primary key)
status
date

Tbl portal_program_evalsusers [relational table]
--------------------------
programid
userid

What am I doing wrong with the query?

The desired output is each status and the count:

 --------------------------
 status  | countStatus
      1  |        6
      2  |       23
      3  |       14

Body:
After some additional trial and error, I believe I found the answer to my question:

SELECT
  u.status,
  COUNT(*) AS countStatus
FROM (SELECT programid, userid FROM portal_program_evalsusers WHERE userid=41 GROUP BY programid) c
LEFT JOIN (
   SELECT
    programid,
    status,
    date
    FROM portal_program_eval
    GROUP BY programid
) u ON c.programid = u.programid
  WHERE (u.date >= 2017-03-01 AND u.date < 2017-04-01)
  GROUP BY u.status


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答: There is no "hard" limit. OO design does however have a notion of coupling and cohesion. As long as your class is loosely coupled and highly cohesive I believe that you are ok with as many members/methods as you need.</p>

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

OwnerDisplayName: Matt Campbell


问:
How to access parent widget pointer in QT
I have a code something like this

```<code>Window::Window()
{
   QStackedWidget *centralApp = new QStackedWidget;
   QWidget1 *wgt1 = QWidget1;
   QWidget2 *wgt2 = QWidget2;
   QWidget3 *wgt3 = QWidget3;

   centralApp->addWidget(wgt1);
   centralApp->addWidget(wgt2);
   centralApp->addWidget(wgt3);
}
</code>```

The classes QWidget1,QWidget2 and QWidget3 are inherited from QWidget and each contains two buttons btn1 and btn2. These buttons I want to use the two buttons in each widget to navigate to other two widgets added to stacked widget. So to navigate to other page in stacked widget I have to use the setCurrentIndex() and for this I need the parent QStackedWidget pointer. Can anybody suggest me how I can access the QStackedWidget pointer inside on of its page widgets to navigate to another page?

Please let me know if I am not clear in explaining the problem.

答:
I would have your subclasses emit a signal - 'next' and 'prev' for example - and then connect this signal in your main window to switch the QStackWidget's current widget.

Otherwise, you're tightly coupling your stacked widgets in a way that is unnecessary.

Body:
I have a code something like this

Window::Window()
{
   QStackedWidget *centralApp = new QStackedWidget;
   QWidget1 *wgt1 = QWidget1;
   QWidget2 *wgt2 = QWidget2;
   QWidget3 *wgt3 = QWidget3;

   centralApp->addWidget(wgt1);
   centralApp->addWidget(wgt2);
   centralApp->addWidget(wgt3);
}

The classes QWidget1,QWidget2 and QWidget3 are inherited from QWidget and each contains two buttons btn1 and btn2. These buttons I want to use the two buttons in each widget to navigate to other two widgets added to stacked widget. So to navigate to other page in stacked widget I have to use the setCurrentIndex() and for this I need the parent QStackedWidget pointer. Can anybody suggest me how I can access the QStackedWidget pointer inside on of its page widgets to navigate to another page?

Please let me know if I am not clear in explaining the problem.


问:
MobX decorators not working
I'm having trouble getting decorators such as @observable and @computed to work in my project.

Here are my files.

package.json:

```<code>{
  "name": "heroku-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "babel-plugin-syntax-decorators": "^6.13.0",
    "mobx": "^3.1.11",
    "mobx-react": "^4.2.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-stage-1": "^6.24.1",
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

App.js:

```<code>import React, { Component } from 'react';
import './App.css';
import GameBoard from './components/game-board';
import { inject, observer } from 'mobx-react';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
        </div>
        <GameBoard />
      </div>
    );
  }
}

export default App;
</code>```

.babelrc:

```<code>{
  "presets": [
    "es2015",
    "react",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy"]
}
</code>```

When I add the @observer decorator like so (@observer class App extends Component {...}) before my class declaration I receive this error:

```<code>Failed to compile
./src/App.js
Syntax error: Unexpected token (7:0)

   5 | import { inject, observer } from 'mobx-react';
   6 |
>  7 | @observer class App extends Component {
     | ^
   8 |   render() {
   9 |     return (
  10 |       <div className="App">
</code>```

答:
Proper way of installing mobx when you are using create-react-app is as follows;

create-react-app ExampleApp

npm run eject

npm install --saveDev babel-plugin-transform-decorators-legacy

Update your .babelrc file as it is right now (with transform-decorators-legacy)

npm install --save mobx mobx-react

That should do the trick.

Title: MobX decorators not working

Body:
I'm having trouble getting decorators such as @observable and @computed to work in my project.

Here are my files.

package.json:

{
  "name": "heroku-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "babel-plugin-syntax-decorators": "^6.13.0",
    "mobx": "^3.1.11",
    "mobx-react": "^4.2.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-stage-1": "^6.24.1",
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

App.js:

import React, { Component } from 'react';
import './App.css';
import GameBoard from './components/game-board';
import { inject, observer } from 'mobx-react';

class App extends Component {
  render() {
    return (

        <GameBoard />

    );
  }
}

export default App;

.babelrc:

{
  "presets": [
    "es2015",
    "react",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy"]
}

When I add the @observer decorator like so (@observer class App extends Component {...}) before my class declaration I receive this error:

Failed to compile
./src/App.js
Syntax error: Unexpected token (7:0)

   5 | import { inject, observer } from 'mobx-react';
   6 |
>  7 | @observer class App extends Component {
     | ^
   8 |   render() {
   9 |     return (
  10 |


问:
Longest sequence of consecutive letters
Suppose I have a string of lower case letters, e.g.

```<code>'ablccmdnneofffpg'
</code>```

And my aim is to find the longest sequence of the consecutive numbers inside this string which in this case is:

```<code>'abcdefg'
</code>```

The intuitive attempt is to find loop around each letter and obtain the longest sequence starting from that letter. One possible solution is

```<code>longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
    current_length = 1
    last_in_sequence = ord(word[current_start])
    for i in range(current_start + 1, len(word)):
        if ord(word[i]) - last_in_sequence == 1:
            current_length += 1
            last_in_sequence = ord(word[i])
    if current_length > longest_length:
        longest_length = current_length
        start = current_start
    while (current_start < len(word) - 1 and
           ord(word[current_start + 1]) - ord(word[current_start]) == 1):
        current_start += 1
    current_start += 1
</code>```

Are there any other ways of solving the problem with fewer lines, or even using some pythonic methods?

答:
A solution that trades memory for (some) time:

It keeps track of all sequences seen and then at the end prints the longest found (although there could be more than one).

```<code>from contextlib import suppress

class Sequence:
    def __init__(self, letters=''):
        self.letters = letters
        self.last = self._next_letter(letters[-1:])

    def append(self, letter):
        self.letters += letter
        self.last = self._next_letter(letter)

    def _next_letter(self, letter):
        with suppress(TypeError):
            return chr(ord(letter) + 1)
        return 'a'

    def __repr__(self):
        return 'Sequence({}, {})'.format(repr(self.letters),
                                         repr(self.last))

word = 'ablccmdnneofffpg'
sequences = []
for letter in word:
    for s in sequences:
        if s.last == letter:
            s.append(letter)
            break
    else:
        sequences.append(Sequence(letters=letter))

sequences = list(sorted(sequences, key=lambda s: len(s.letters), reverse=True))
print(sequences[0].letters)
</code>```

Title: Longest sequence of consecutive letters

Body:
Suppose I have a string of lower case letters, e.g.

'ablccmdnneofffpg'

And my aim is to find the longest sequence of the consecutive numbers inside this string which in this case is:

'abcdefg'

The intuitive attempt is to find loop around each letter and obtain the longest sequence starting from that letter. One possible solution is

longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
    current_length = 1
    last_in_sequence = ord(word[current_start])
    for i in range(current_start + 1, len(word)):
        if ord(word[i]) - last_in_sequence == 1:
            current_length += 1
            last_in_sequence = ord(word[i])
    if current_length > longest_length:
        longest_length = current_length
        start = current_start
    while (current_start < len(word) - 1 and
           ord(word[current_start + 1]) - ord(word[current_start]) == 1):
        current_start += 1
    current_start += 1

Are there any other ways of solving the problem with fewer lines, or even using some pythonic methods?

Body:
A solution that trades memory for (some) time:

It keeps track of all sequences seen and then at the end prints the longest found (although there could be more than one).

from contextlib import suppress

class Sequence:
    def __init__(self, letters=''):
        self.letters = letters
        self.last = self._next_letter(letters[-1:])

    def append(self, letter):
        self.letters += letter
        self.last = self._next_letter(letter)

    def _next_letter(self, letter):
        with suppress(TypeError):
            return chr(ord(letter) + 1)
        return 'a'

    def __repr__(self):
        return 'Sequence({}, {})'.format(repr(self.letters),
                                         repr(self.last))

word = 'ablccmdnneofffpg'
sequences = []
for letter in word:
    for s in sequences:
        if s.last == letter:
            s.append(letter)
            break
    else:
        sequences.append(Sequence(letters=letter))

sequences = list(sorted(sequences, key=lambda s: len(s.letters), reverse=True))
print(sequences[0].letters)


问:
Polymer 2: custom validation with paper-input
I'm using a paper-input like this:

```<code><paper-input
    type="number"
    allowed-pattern="[0-9,]"
    validator="my-validator"
    auto-validate="true"
    error-message="Invalid input!">
</paper-input>
</code>```

I would like add my own logic to validate the input. I have searched info about that, but I only found Polymer 1.x examples. How do I add custom input validation in Polymer 2?

EDIT:

```<code><paper-input
    type="number"
    allowed-pattern="[0-9,]"
    validator="my-validator1"
    auto-validate="true"
    value="{{value1}}"
    error-message="Invalid input!">
</paper-input>

<paper-input
    type="number"
    allowed-pattern="[0-9,]"
    validator="my-validator2"
    auto-validate="true"
    value="{{value2}}"
    error-message="Invalid input!">
</paper-input>

<paper-input
    type="number"
    allowed-pattern="[0-9,]"
    validator="my-validator3"   <!-- value1 + value 2 == value3 -->
    auto-validate="true"
    value="{{value3}}"
    error-message="Invalid input!">
</paper-input>
</code>```

答:
Your usage of the validator looks correct, but the validator's definition is missing.

The key to adding the validator is to:

Define a template-less custom element that implements the Polymer.IronValidatorBehavior behavior.

Polymer 2.x:

```<code>class Foo extends Polymer.mixinBehaviors([Polymer.IronValidatorBehavior],
                                         Polymer.Element)
{...}
</code>```

Polymer 1.x:

```<code>Polymer({
  ...
  behaviors: [
    Polymer.IronValidatorBehavior
  ]
});
</code>```

In that element, define validate(value), which returns a Boolean, indicating whether the value is valid.

Polymer 2.x example:

```<code>class SsnValidator extends Polymer.mixinBehaviors([Polymer.IronValidatorBehavior], Polymer.Element) {
  static get is() { return 'ssn-validator'; }

  ready() {
    super.ready();

    // Workaround https://github.com/PolymerElements/iron-validator-behavior/issues/30#issuecomment-305643574
    new Polymer.IronMeta({type: 'validator', key: SsnValidator.is, value: this});
  }

  validate(value) {
    const re = /^\d{3}-?\d{2}-?\d{4}$/;
    return re.test(value);
  }
}

window.customElements.define(SsnValidator.is, SsnValidator);
</code>```

Note ready() uses a workaround for a known issue with IronValidatorBehavior in Polymer 2. Alternatively, you could define the validator with the Polymer 1.x syntax (still supported in Polymer 2):

```<code>Polymer({
  is: 'ssn-validator',

  behaviors: [
    Polymer.IronValidatorBehavior
  ],

  validate: function(value) {
    const re = /^\d{3}-?\d{2}-?\d{4}$/;
    return re.test(value);
  }
});
</code>```

demo

Body:
I'm using a paper-input like this:

<paper-input
    type="number"
    allowed-pattern="[0-9,]"
    validator="my-validator"
    auto-validate="true"
    error-message="Invalid input!">
</paper-input>

I would like add my own logic to validate the input. I have searched info about that, but I only found Polymer 1.x examples. How do I add custom input validation in Polymer 2?

EDIT:

<paper-input
    type="number"
    allowed-pattern="[0-9,]"
    validator="my-validator1"
    auto-validate="true"
    value="{{value1}}"
    error-message="Invalid input!">
</paper-input>

<paper-input
    type="number"
    allowed-pattern="[0-9,]"
    validator="my-validator2"
    auto-validate="true"
    value="{{value2}}"
    error-message="Invalid input!">
</paper-input>

<paper-input
    type="number"
    allowed-pattern="[0-9,]"
    validator="my-validator3"
    auto-validate="true"
    value="{{value3}}"
    error-message="Invalid input!">
</paper-input>

Body:
Your usage of the validator looks correct, but the validator's definition is missing.

The key to adding the validator is to:

Define a template-less custom element that implements the Polymer.IronValidatorBehavior behavior.

Polymer 2.x:

class Foo extends Polymer.mixinBehaviors([Polymer.IronValidatorBehavior],
                                         Polymer.Element)
{...}

Polymer 1.x:

Polymer({
  ...
  behaviors: [
    Polymer.IronValidatorBehavior
  ]
});

In that element, define validate(value), which returns a Boolean, indicating whether the value is valid.

Polymer 2.x example:

class SsnValidator extends Polymer.mixinBehaviors([Polymer.IronValidatorBehavior], Polymer.Element) {
  static get is() { return 'ssn-validator'; }

  ready() {
    super.ready();

    // Workaround https://github.com/PolymerElements/iron-validator-behavior/issues/30#issuecomment-305643574
    new Polymer.IronMeta({type: 'validator', key: SsnValidator.is, value: this});
  }

  validate(value) {
    const re = /^\d{3}-?\d{2}-?\d{4}$/;
    return re.test(value);
  }
}

window.customElements.define(SsnValidator.is, SsnValidator);

Note ready() uses a workaround for a known issue with IronValidatorBehavior in Polymer 2. Alternatively, you could define the validator with the Polymer 1.x syntax (still supported in Polymer 2):

Polymer({
  is: 'ssn-validator',

  behaviors: [
    Polymer.IronValidatorBehavior
  ],

  validate: function(value) {
    const re = /^\d{3}-?\d{2}-?\d{4}$/;
    return re.test(value);
  }
});

demo


问:
What is the best way to write a struct to file?
I have this two structs:

```<code>struct pcap_hdr_s {
    UInt32 magic_number;
    UInt16 version_major;
    UInt16 version_minor;
    int32_t thiszone;
    UInt32 sigfigs;
    UInt32 snaplen;
    UInt32 network;
};
//packet header
struct pcaprec_hdr_s {
    UInt32 ts_sec;
    UInt32 ts_usec;
    UInt32 incl_len;
    UInt32 orig_len;
};
</code>```

which are initialised as follows(for example):

```<code>    let pcapHeader : pcap_hdr_s = pcap_hdr_s(magic_number: 0xa1b2c3d4,
                                            version_major: 2,
                                            version_minor: 4,
                                            thiszone: 0,
                                            sigfigs: 0,
                                            snaplen:
                                            pcap_record_size,
                                            network: LINKTYPE_ETHERNET)

    let pcapRecHeader : pcaprec_hdr_s = pcaprec_hdr_s(ts_sec: UInt32(ts.tv_sec),
                                        ts_usec: UInt32(ts.tv_nsec),
                                        incl_len: plen,
                                        orig_len: length)
</code>```

I tried to create Data/NSData objects of the structs like this:

```<code>            //write pcap header
            let pcapHeaderData : NSData = NSData(bytes: pcapHeader, length: sizeofValue(pcapHeader))
            //write pcaprec header
            let pcapRecHeaderData : NSData = NSData(bytes: pcapRecHeader, length: sizeofValue(pcapRecHeader))
</code>```

but I always get this error for each line:

```<code>"Connot convert value if type 'pcap_hdr_s' to expected arguemnt type 'UsafeRawPointer?'"
</code>```

I had a look at the documentation of UnsafeRawPointers in Swift, but I don't get it enough as for now, to create the NSData object from the structs.
Am I on the right way or is there a better one to accomplish my intend?

If this Data initialisation would work, my next steps would be

Append pcapRecHeaderData to pcapHeaderData

write pcapHeaderData atomically to file/url with the provided function of Data/NSData

EDIT:

```<code>//packet ethernet header
struct ethernet_hdr_s {
    let dhost : [UInt8]
    let shost : [UInt8]
    let type : UInt16
};

let src_mac : [UInt8] = [0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB]
let dest_mac : [UInt8] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55]

let ethernetHeader : ethernet_hdr_s = ethernet_hdr_s(dhost: dest_mac, shost: src_mac, type: 0x0800)
</code>```

EDIT 2:

```<code>let payloadSize = packet.payload.count
            let plen = (payloadSize < Int(pcap_record_size) ? payloadSize : Int(pcap_record_size));

            bytesWritten = withUnsafePointer(to: &(packet.payload)) {
                $0.withMemoryRebound(to: UInt8.self, capacity: Int(plen)) {
                    ostream.write($0, maxLength: Int(plen))
                }
            }
            if bytesWritten != (Int(plen)) {
                // Could not write all bytes, report error ...
                NSLog("error in Writting packet payload, not all Bytes written: bytesWritten: %d|plen: %d", bytesWritten, Int(plen))
            }
</code>```

答:
You can write arbitrary data to an InputStream without creating a
(NS)Data object first. The "challenge" is how to convert the pointer to
the struct to an UInt8 pointer as expected by the write method:

```<code>let ostream = OutputStream(url: url, append: false)! // Add error checking here!
ostream.open()

var pcapHeader = pcap_hdr_s(...)
let headerSize = MemoryLayout.size(ofValue: pcapHeader)

let bytesWritten = withUnsafePointer(to: &pcapHeader) {
        $0.withMemoryRebound(to: UInt8.self, capacity: headerSize) {
        ostream.write($0, maxLength: headerSize)
    }
}
if bytesWritten != headerSize {
    // Could not write all bytes, report error ...
}
</code>```

In the same way you can read data from in InputStream:

```<code>let istream = InputStream(url: url)! // Add error checking here!
istream.open()

let bytesRead = withUnsafeMutablePointer(to: &pcapHeader) {
    $0.withMemoryRebound(to: UInt8.self, capacity: headerSize) {
        istream.read($0, maxLength: headerSize)
    }
}
if bytesRead != headerSize {
    // Could not read all bytes, report error ...
}
</code>```

If the file was possibly created on a different platform with a
different byte order then you can check the "magic" and swap bytes
if necessary (as described on https://wiki.wireshark.org/Development/LibpcapFileFormat):

```<code>switch pcapHeader.magic_number {
case 0xa1b2c3d4:
    break // Already in host byte order
case 0xd4c3b2a1:
    pcapHeader.version_major = pcapHeader.version_major.byteSwapped
    pcapHeader.version_minor = pcapHeader.version_minor.byteSwapped
    // ...
default:
    // Unknown magic, report error ...
}
</code>```

To simplify the task of writing and reading structs one can define
custom extension methods, e.g.

```<code>extension OutputStream {

    enum ValueWriteError: Error {
        case incompleteWrite
        case unknownError
    }

    func write<T>(value: T) throws {
        var value = value
        let size = MemoryLayout.size(ofValue: value)
        let bytesWritten = withUnsafePointer(to: &value) {
            $0.withMemoryRebound(to: UInt8.self, capacity: size) {
                write($0, maxLength: size)
            }
        }
        if bytesWritten == -1 {
            throw streamError ?? ValueWriteError.unknownError
        } else if bytesWritten != size {
            throw ValueWriteError.incompleteWrite
        }
    }
}

extension InputStream {

    enum ValueReadError: Error {
        case incompleteRead
        case unknownError
    }

    func read<T>(value: inout T) throws {
        let size = MemoryLayout.size(ofValue: value)
        let bytesRead = withUnsafeMutablePointer(to: &value) {
            $0.withMemoryRebound(to: UInt8.self, capacity: size) {
                read($0, maxLength: size)
            }
        }
        if bytesRead == -1 {
            throw streamError ?? ValueReadError.unknownError
        } else if bytesRead != size {
            throw ValueReadError.incompleteRead
        }
    }
}
</code>```

Now you can write and read simply with

```<code>try ostream.write(value: pcapHeader)
try istream.read(value: &pcapHeader)
</code>```

Of course this works only with "self-contained" structs like your
pcap_hdr_s and pcaprec_hdr_s.

Body:
I have this two structs:

struct pcap_hdr_s {
    UInt32 magic_number;
    UInt16 version_major;
    UInt16 version_minor;
    int32_t thiszone;
    UInt32 sigfigs;
    UInt32 snaplen;
    UInt32 network;
};
//packet header
struct pcaprec_hdr_s {
    UInt32 ts_sec;
    UInt32 ts_usec;
    UInt32 incl_len;
    UInt32 orig_len;
};

which are initialised as follows(for example):

    let pcapHeader : pcap_hdr_s = pcap_hdr_s(magic_number: 0xa1b2c3d4,
                                            version_major: 2,
                                            version_minor: 4,
                                            thiszone: 0,
                                            sigfigs: 0,
                                            snaplen:
                                            pcap_record_size,
                                            network: LINKTYPE_ETHERNET)

    let pcapRecHeader : pcaprec_hdr_s = pcaprec_hdr_s(ts_sec: UInt32(ts.tv_sec),
                                        ts_usec: UInt32(ts.tv_nsec),
                                        incl_len: plen,
                                        orig_len: length)

I tried to create Data/NSData objects of the structs like this:

            //write pcap header
            let pcapHeaderData : NSData = NSData(bytes: pcapHeader, length: sizeofValue(pcapHeader))
            //write pcaprec header
            let pcapRecHeaderData : NSData = NSData(bytes: pcapRecHeader, length: sizeofValue(pcapRecHeader))

but I always get this error for each line:

"Connot convert value if type 'pcap_hdr_s' to expected arguemnt type 'UsafeRawPointer?'"

I had a look at the documentation of UnsafeRawPointers in Swift, but I don't get it enough as for now, to create the NSData object from the structs.
Am I on the right way or is there a better one to accomplish my intend?

If this Data initialisation would work, my next steps would be

Append pcapRecHeaderData to pcapHeaderData

write pcapHeaderData atomically to file/url with the provided function of Data/NSData

EDIT:

//packet ethernet header
struct ethernet_hdr_s {
    let dhost : [UInt8]
    let shost : [UInt8]
    let type : UInt16
};

let src_mac : [UInt8] = [0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB]
let dest_mac : [UInt8] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55]

let ethernetHeader : ethernet_hdr_s = ethernet_hdr_s(dhost: dest_mac, shost: src_mac, type: 0x0800)

EDIT 2:

let payloadSize = packet.payload.count
            let plen = (payloadSize < Int(pcap_record_size) ? payloadSize : Int(pcap_record_size));

            bytesWritten = withUnsafePointer(to: &(packet.payload)) {
                $0.withMemoryRebound(to: UInt8.self, capacity: Int(plen)) {
                    ostream.write($0, maxLength: Int(plen))
                }
            }
            if bytesWritten != (Int(plen)) {
                // Could not write all bytes, report error ...
                NSLog("error in Writting packet payload, not all Bytes written: bytesWritten: %d|plen: %d", bytesWritten, Int(plen))
            }

Body:
You can write arbitrary data to an InputStream without creating a
(NS)Data object first. The "challenge" is how to convert the pointer to
the struct to an UInt8 pointer as expected by the write method:

let ostream = OutputStream(url: url, append: false)! // Add error checking here!
ostream.open()

var pcapHeader = pcap_hdr_s(...)
let headerSize = MemoryLayout.size(ofValue: pcapHeader)

let bytesWritten = withUnsafePointer(to: &pcapHeader) {
        $0.withMemoryRebound(to: UInt8.self, capacity: headerSize) {
        ostream.write($0, maxLength: headerSize)
    }
}
if bytesWritten != headerSize {
    // Could not write all bytes, report error ...
}

In the same way you can read data from in InputStream:

let istream = InputStream(url: url)! // Add error checking here!
istream.open()

let bytesRead = withUnsafeMutablePointer(to: &pcapHeader) {
    $0.withMemoryRebound(to: UInt8.self, capacity: headerSize) {
        istream.read($0, maxLength: headerSize)
    }
}
if bytesRead != headerSize {
    // Could not read all bytes, report error ...
}

If the file was possibly created on a different platform with a
different byte order then you can check the "magic" and swap bytes
if necessary (as described on https://wiki.wireshark.org/Development/LibpcapFileFormat):

switch pcapHeader.magic_number {
case 0xa1b2c3d4:
    break // Already in host byte order
case 0xd4c3b2a1:
    pcapHeader.version_major = pcapHeader.version_major.byteSwapped
    pcapHeader.version_minor = pcapHeader.version_minor.byteSwapped
    // ...
default:
    // Unknown magic, report error ...
}

To simplify the task of writing and reading structs one can define
custom extension methods, e.g.

extension OutputStream {

    enum ValueWriteError: Error {
        case incompleteWrite
        case unknownError
    }

    func write<T>(value: T) throws {
        var value = value
        let size = MemoryLayout.size(ofValue: value)
        let bytesWritten = withUnsafePointer(to: &value) {
            $0.withMemoryRebound(to: UInt8.self, capacity: size) {
                write($0, maxLength: size)
            }
        }
        if bytesWritten == -1 {
            throw streamError ?? ValueWriteError.unknownError
        } else if bytesWritten != size {
            throw ValueWriteError.incompleteWrite
        }
    }
}

extension InputStream {

    enum ValueReadError: Error {
        case incompleteRead
        case unknownError
    }

    func read<T>(value: inout T) throws {
        let size = MemoryLayout.size(ofValue: value)
        let bytesRead = withUnsafeMutablePointer(to: &value) {
            $0.withMemoryRebound(to: UInt8.self, capacity: size) {
                read($0, maxLength: size)
            }
        }
        if bytesRead == -1 {
            throw streamError ?? ValueReadError.unknownError
        } else if bytesRead != size {
            throw ValueReadError.incompleteRead
        }
    }
}

Now you can write and read simply with

try ostream.write(value: pcapHeader)
try istream.read(value: &pcapHeader)

Of course this works only with "self-contained" structs like your
pcap_hdr_s and pcaprec_hdr_s.


答:
You can listen to clicks with jQuery by using:

```<code>// Change the selector used below
$('#some-id-here').click(function(){
    // Your code here
});
</code>```

There's also another way, using "on". This might be more useful to you, because it also triggers on items added dynamically to the page, which looks to be your case.

```<code>// Change the selector used below
$('#some-id-here').on('click', 'img', function(){
  // Your code here.
});
</code>```

Also, you can select the document with $(document) (instead of #some-id-here) to apply it globally on your page, so every img tag would trigger this function.

Title: How to make a thumbnail created by a function clickable in html?

Body:
I am trying to make clickable thumbnails in my html code but I cannot figure out how to do it. I know  won't work. How can I make each thumbnail clickable so that it directs to another page?

Here are the functions I used to get data from the database and to create the thumbnail
`

`.

Body:
You can listen to clicks with jQuery by using:

// Change the selector used below
$('#some-id-here').click(function(){
    // Your code here
});

There's also another way, using "on". This might be more useful to you, because it also triggers on items added dynamically to the page, which looks to be your case.

// Change the selector used below
$('#some-id-here').on('click', 'img', function(){
  // Your code here.
});

Also, you can select the document with $(document) (instead of #some-id-here) to apply it globally on your page, so every img tag would trigger this function.


问:
Convert Non-List Type to List Directly
I have a list of items that I need to actually be a list of lists. All the conversion methods I have seen convert the non-list items to lists of individual characters ["12", "cat", 87] to [['1', '2'], ['c', 'a', 't'], ['8', '7']] instead of [['12'], ['cat'], [87]]. The following works,

```<code>v_Data = ["12", "cat", 87]
for index, i in enumerate(v_Data):
    if type(i) != list:
        v_Data[index] = [i]
print(v_Data) ## [['12'], ['cat'], [87]]
</code>```

Is there a better way to do this?

Using Python 2.7

Title: Convert Non-List Type to List Directly

Body:
I have a list of items that I need to actually be a list of lists. All the conversion methods I have seen convert the non-list items to lists of individual characters ["12", "cat", 87] to [['1', '2'], ['c', 'a', 't'], ['8', '7']] instead of [['12'], ['cat'], [87]]. The following works,

v_Data = ["12", "cat", 87]
for index, i in enumerate(v_Data):
    if type(i) != list:
        v_Data[index] = [i]
print(v_Data) ## [['12'], ['cat'], [87]]

Is there a better way to do this?

Using Python 2.7

Body:
you can do :

>>> a=["12", "cat", 87]
>>> b=[[i] for i in a]
>>> b
[['12'], ['cat'], [87]]

EDIT :
if there is already list in your list :

>>> a=["12", "cat", 87, [23]]
>>> b=[[i] if type(i) is not list else i for i in a]
>>> b
[['12'], ['cat'], [87], [23]]


问:
OpenMP - Initializing 1D Array
I am trying to initialize a dynamic array using OpenMP in C but it seems to be slower than the serial method. The function I am using is

```<code>int* createArray(int size, int num) {
    int i;
    int* M = (int*)malloc(size*sizeof(int));

    srand(time(NULL));
    double start = omp_get_wtime();

    #pragma omp parallel for num_threads(num)
    for (i = 0; i < size; i++) {
        M[i] = rand() % (MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
    }

    double end = omp_get_wtime();
    printf("Create Array %f\n",end-start);
    return M;
}
</code>```

I get an array of the given size containing random numbers but the fewer threads I use the faster the function is. Am I doing something wrong?

答:
In general, a parallel application running slower than the corresponding sequential implementation usually comes from either the overhead of starting the threads or the bottleneck of having threads that are not perfectly independent (e.g. through shared data).

Here, the former is true because you are calling rand(). This function uses somehow global variables which have to be shared between threads. A way to overcome this would be to use a private seed for each thread. Furthermore, did you notice that your array is not really random when you have multiple threads? You could make the seed provided to srand() a function of omp_get_thread_num() to solve this.

Title: OpenMP - Initializing 1D Array

Body:
I am trying to initialize a dynamic array using OpenMP in C but it seems to be slower than the serial method. The function I am using is

int* createArray(int size, int num) {
    int i;
    int* M = (int*)malloc(size*sizeof(int));

    srand(time(NULL));
    double start = omp_get_wtime();

    #pragma omp parallel for num_threads(num)
    for (i = 0; i < size; i++) {
        M[i] = rand() % (MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
    }

    double end = omp_get_wtime();
    printf("Create Array %f\n",end-start);
    return M;
}

I get an array of the given size containing random numbers but the fewer threads I use the faster the function is. Am I doing something wrong?


问:
collaborative filtering in rails
I'm looking for a solution for collaborative filtering in rails or even possible examples.  So far I have only found acts_as_recommendable which looks useful but I noticed it hasn't had any updates in the last 2 years.

Does anyone know of any other solutions and/or examples?

答:
This pertains to the examples part of your question, as both the libraries mentioned below are in Java.

The article referenced in above answer, written by Apache Mahout-Taste library author, has neat examples, source code of the examples( using 2.5GB wikipedia data) , and an excellent packaging to run and see those examples in action, in a few minutes.

Apache Mahout-Taste

The specific section is Building a recommendation engine

Here is another open source recommendation engine.
 easyrec

Title: collaborative filtering in rails


问:
How do I create a method for filling a matrix without knowing the type of the input
I want to create a method that reads input from the console and fills it, example:

3 4

A B B D

E B B B

I J B B

The first line reads the dimensions and the rest are the input in the matrix (there is no empty line in between i just cant paste it otherwise).
I wrote this :

```<code>  static void Main(string[] args)
    {
        var input = Console.ReadLine();
        char[,] matrix = ReadAndFillMatrix(input);
    }

  private static char[,] ReadAndFillMatrix(string input)
        {
            var size=input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
            var rows = size[0];
            var cols = size[1];
            var matrix = new char[rows, cols];
            for (int i = 0; i < rows; i++)
            {
                var line = Console.ReadLine()
               .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
               .Select(char.Parse)
               .ToArray();
                for (int j = 0; j < cols; j++)
                {
                    matrix[i, j] = line[j];
                }
            }

            return matrix;
        }
</code>```

So far so good, but what do I do when the matrix is not made of chars, but of integers for example?

The question: Do I have to create a different method for each type of matrix or is there some something I'm missing?

PS: I want to be able to use it in multiple places for different matrices not just the one

答:
You're very close! Just use Char.IsDigit (or int.TryParse) to test each of the sections you've read out, and that way you'll know; of course, you'll need to create a different matrix array for each type char and int for example, but that shouldn't be too onerous.

Edit

As per the comment made by @kokosaish on this answer, I've updated to the following:

```<code>void Main()
{
    var stringMatrix = ReadAndFillMatrix<string>(s => s);
    var intMatrix = ReadAndFillMatrix<int>(int.Parse);
    var doubleMatrix = ReadAndFillMatrix<double>(double.Parse);
}

private static T[,] ReadAndFillMatrix<T>(Func<string,T> sectionParser)
{
    var readAndSplit =
        new Func<string[]>(
            () =>
            {
                return
                Console.ReadLine()
                .Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries)
                .ToArray();
            });

    var size = readAndSplit();
    var rows = int.Parse(size[0]);
    var cols = int.Parse(size[1]);

    var matrix = new T[rows, cols];
    for (var i = 0; i < rows; i++)
    {
        var line = readAndSplit();
        for (var j = 0; j < cols; j++)
        {
            matrix[i,j] = sectionParser(line[j]);
        }
    }
    return matrix;
}
</code>```

This is far from production ready code, as you need to add error handling for when parsing fails etc, but this should show you how to specify which type you want.

Body:
I want to create a method that reads input from the console and fills it, example:

3 4

A B B D

E B B B

I J B B

The first line reads the dimensions and the rest are the input in the matrix (there is no empty line in between i just cant paste it otherwise).
I wrote this :

  static void Main(string[] args)
    {
        var input = Console.ReadLine();
        char[,] matrix = ReadAndFillMatrix(input);
    }

  private static char[,] ReadAndFillMatrix(string input)
        {
            var size=input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
            var rows = size[0];
            var cols = size[1];
            var matrix = new char[rows, cols];
            for (int i = 0; i < rows; i++)
            {
                var line = Console.ReadLine()
               .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
               .Select(char.Parse)
               .ToArray();
                for (int j = 0; j < cols; j++)
                {
                    matrix[i, j] = line[j];
                }
            }

            return matrix;
        }

So far so good, but what do I do when the matrix is not made of chars, but of integers for example?

The question: Do I have to create a different method for each type of matrix or is there some something I'm missing?

PS: I want to be able to use it in multiple places for different matrices not just the one

Body:
You're very close! Just use Char.IsDigit (or int.TryParse) to test each of the sections you've read out, and that way you'll know; of course, you'll need to create a different matrix array for each type char and int for example, but that shouldn't be too onerous.

Edit

As per the comment made by @kokosaish on this answer, I've updated to the following:

void Main()
{
    var stringMatrix = ReadAndFillMatrix<string>(s => s);
    var intMatrix = ReadAndFillMatrix<int>(int.Parse);
    var doubleMatrix = ReadAndFillMatrix<double>(double.Parse);
}

private static T[,] ReadAndFillMatrix<T>(Func<string,T> sectionParser)
{
    var readAndSplit =
        new Func<string[]>(
            () =>
            {
                return
                Console.ReadLine()
                .Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries)
                .ToArray();
            });

    var size = readAndSplit();
    var rows = int.Parse(size[0]);
    var cols = int.Parse(size[1]);

    var matrix = new T[rows, cols];
    for (var i = 0; i < rows; i++)
    {
        var line = readAndSplit();
        for (var j = 0; j < cols; j++)
        {
            matrix[i,j] = sectionParser(line[j]);
        }
    }
    return matrix;
}

This is far from production ready code, as you need to add error handling for when parsing fails etc, but this should show you how to specify which type you want.


问:
BigQuery: can I lower querying costs by storing data in multiple tables?
I have single table, currently with over 43 million rows in BigQuery that stores data samples. One of the fields is "owner_id". All my queries are done with respect to a single owner.

Example:

```<code>SELECT COUNT(*)
FROM `mydataset.mytable`
WHERE owner_id = "owner23" AND color = "red"
</code>```

Would creating a table for each owner lower my BigQuery query costs? I suspect querying the entire table with WHERE owner_id = "owner23" AND color = "red" requires more GBs to be processed than querying a table with only owner23's data and using WHERE color = "red" . While I suspect this is true, I wanted to confirm.

Also, would splitting my data across multiple tables cause storage costs to increase?

Thanks!

答:
Would creating a table for each owner lower my BigQuery query costs?

Theoretically - Yes. You are charged for only data in the columns you query – no matter how many rows are qualified per your WHERE clause. For example if you have 10 clients with relatively even data – cost of your queries can be up to 10 times lower – or in case of just COUNT(1) and no other WHERE clauses - it will be $0(Zero!)

There is a small catch, if query cost is non-zero – the minimum charge is as for 10MB – so if your split tables small and size of involved columns less than 10MB – you still will be charged as for 10MB

Practically – potentially "cost" of managing multiple tables can be high, so you need to compare and decide for yourself

Would splitting my data across multiple tables cause storage costs to increase?

Storage pricing is prorated per MB, per second – so No – storage cost will not increase

Body:
I have single table, currently with over 43 million rows in BigQuery that stores data samples. One of the fields is "owner_id". All my queries are done with respect to a single owner.

Example:

SELECT COUNT(*)
FROM `mydataset.mytable`
WHERE owner_id = "owner23" AND color = "red"

Would creating a table for each owner lower my BigQuery query costs? I suspect querying the entire table with WHERE owner_id = "owner23" AND color = "red" requires more GBs to be processed than querying a table with only owner23's data and using WHERE color = "red" . While I suspect this is true, I wanted to confirm.

Also, would splitting my data across multiple tables cause storage costs to increase?

Thanks!


问:
Putting methods into an ArrayList Java
I would like to put these Methods into an ArrayList, but I can't figure out how to do that. I'm using NetBeans, and the program is going to be a GUI.

Here is my code:

```<code>public class canada150Tour extends javax.swing.JFrame {

    ArrayList <String> mcQuestions = new ArrayList(); //This is the array I want to put the below methods into.

    private void questionFredricton(){
        outputTextQuestion.append("Where is Fredricton located?");

        displayQuestions.append("New Brunswick");
    }
    private void questionRegina(){
        outputTextQuestion.setText("Where is Regina located?");

        displayQuestions.append("Saskatchewan");

    }
    private void questionOttawa(){
        outputTextQuestion.setText("Where is Ottawa located?");

        displayQuestions.append("Ontario");
    }
    private void questionHalifax(){
        outputTextQuestion.setText("Where is Halifax located?");

        displayQuestions.append("Nova Scotia");
    }
    private void questionQuebecCity(){
        outputTextQuestion.setText("Where is Quebec City located?");

        displayQuestions.append("Quebec");
    }
    private void questionEdmonton(){
        outputTextQuestion.setText("Where is Edmonton located?");

        displayQuestions.append("Alberta");
    }
    private void questionCharlottetown(){
        outputTextQuestion.setText("Where is Charlottetown located?");

        displayQuestions.append("Prince Edward Island");
    }
    private void questionVictoria(){
        outputTextQuestion.setText("Where is Victoria located?");

        displayQuestions.append("British Columbia");
    }
    private void questionIqaluit(){
        outputTextQuestion.setText("Where is Iqaluit located?");

        displayQuestions.append("Nunavut");
    }
    private void questionWhitehorse(){
        //outputTextQuestion.setText("Where is Whitehorse located?");

        displayQuestions.append("Yukon");
    }
    private void questionWinnipeg(){
        outputTextQuestion.setText("Where is Winnipeg located?");

        displayQuestions.append("Manitoba");
    }
</code>```

I've tried:

```<code>Collections.addAll(mcQuestions, questionFredricton(), questionRegina());
</code>```

And so on for all the methods, but obviously that isn't working.

I get a compiling error when I'm trying to add to the ArrayList (above):

'void' type not allowed here

I'm fairly new to Java, so still learning.

EDIT:
This will eventually be a multiple choice quiz.  I essentially want to the put the methods into an array so I can chose methods randomly.

Thanks in advance!

答:
You need to pass the ArrayList as an argument to methods in order to add elements inside it, e.g.:

```<code>private void questionFredricton(ArrayList <String> mcQuestions){
    mcQuestions.add("Where is Fredricton located?");
}
</code>```

And call the method like this:

```<code>ArrayList <String> mcQuestions = new ArrayList();
questionFredricton(mcQuestions);
</code>```

Also, it seems you need to store the pair of questions and answers here, in which case, it's better to use HashMap, e.g.:

```<code>private void questionFredricton(Map<String, String> questions){
    questions.put("Where is Fredricton located?", "New Brunswick");
}
</code>```

And call it like this:

```<code>Map<String, String> questions = new HashMap<>();
questionFredricton(questions);
</code>```

This way, you will be able to store both questions and answers. questions.keySet() will give you list of all the questions and questions.get("<questions>") will give you the answer.

Title: Putting methods into an ArrayList Java

Body:
I would like to put these Methods into an ArrayList, but I can't figure out how to do that. I'm using NetBeans, and the program is going to be a GUI.

Here is my code:

public class canada150Tour extends javax.swing.JFrame {

    ArrayList <String> mcQuestions = new ArrayList(); //This is the array I want to put the below methods into.

    private void questionFredricton(){
        outputTextQuestion.append("Where is Fredricton located?");

        displayQuestions.append("New Brunswick");
    }
    private void questionRegina(){
        outputTextQuestion.setText("Where is Regina located?");

        displayQuestions.append("Saskatchewan");

    }
    private void questionOttawa(){
        outputTextQuestion.setText("Where is Ottawa located?");

        displayQuestions.append("Ontario");
    }
    private void questionHalifax(){
        outputTextQuestion.setText("Where is Halifax located?");

        displayQuestions.append("Nova Scotia");
    }
    private void questionQuebecCity(){
        outputTextQuestion.setText("Where is Quebec City located?");

        displayQuestions.append("Quebec");
    }
    private void questionEdmonton(){
        outputTextQuestion.setText("Where is Edmonton located?");

        displayQuestions.append("Alberta");
    }
    private void questionCharlottetown(){
        outputTextQuestion.setText("Where is Charlottetown located?");

        displayQuestions.append("Prince Edward Island");
    }
    private void questionVictoria(){
        outputTextQuestion.setText("Where is Victoria located?");

        displayQuestions.append("British Columbia");
    }
    private void questionIqaluit(){
        outputTextQuestion.setText("Where is Iqaluit located?");

        displayQuestions.append("Nunavut");
    }
    private void questionWhitehorse(){
        //outputTextQuestion.setText("Where is Whitehorse located?");

        displayQuestions.append("Yukon");
    }
    private void questionWinnipeg(){
        outputTextQuestion.setText("Where is Winnipeg located?");

        displayQuestions.append("Manitoba");
    }

I've tried:

Collections.addAll(mcQuestions, questionFredricton(), questionRegina());

And so on for all the methods, but obviously that isn't working.

I get a compiling error when I'm trying to add to the ArrayList (above):

'void' type not allowed here

I'm fairly new to Java, so still learning.

EDIT:
This will eventually be a multiple choice quiz.  I essentially want to the put the methods into an array so I can chose methods randomly.

Thanks in advance!

Body:
You need to pass the ArrayList as an argument to methods in order to add elements inside it, e.g.:

private void questionFredricton(ArrayList <String> mcQuestions){
    mcQuestions.add("Where is Fredricton located?");
}

And call the method like this:

ArrayList <String> mcQuestions = new ArrayList();
questionFredricton(mcQuestions);

Also, it seems you need to store the pair of questions and answers here, in which case, it's better to use HashMap, e.g.:

private void questionFredricton(Map<String, String> questions){
    questions.put("Where is Fredricton located?", "New Brunswick");
}

And call it like this:

Map<String, String> questions = new HashMap<>();
questionFredricton(questions);

This way, you will be able to store both questions and answers. questions.keySet() will give you list of all the questions and questions.get("<questions>") will give you the answer.