问:
C# Generating new id from database on windows forms application
I have to make automatic generate new AccountID  on my load windows form app.

So for example when users start windows form "Add new Account" in textbox for "Account id" I have to show latest value from database. If i have two accounts in database on windows form in textbox value will be three.

My code perfectly work if i have at least one account in database, but when my database is empty i got exception.

This is my code:

```<code>public int GetLatestAccountID()
{
    try
    {
        command.CommandText = "select Max(AccountID)as maxID from Account";
        command.CommandType = CommandType.Text;

        connection.Open();

        OleDbDataReader reader= command.ExecuteReader();

        if (reader.Read())
        {
            int valueID = Convert.ToInt32(reader["maxID"]);
            return valueID + 1;
        }

        return 1;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (connection!= null)
        {
            connection.Close();
        }
    }
}
</code>```

Also I find answer on stackoverflow:

```<code>object aa = DBNull.Value;
int valueID = (aa as int?).GetValueOrDefault();
</code>```

But this line of code works if my database is empty, but when I have one account in the database, it will always show on my windows form in account id textbox value one. I use Microsoft Access 2007 database.

I appreciate any help.

答:
```<code>public int GetLatestAccountID()
{
    try
    {
        int accounts = 0;

        command.CommandText = "select Max(AccountID)as maxID from Account";
        command.CommandType = CommandType.Text;

        connection.Open();

        OleDbDataReader reader= command.ExecuteReader();

        if (reader.Read())
        {
            accounts = Convert.ToInt32(reader["maxID"]) + 1;
        }

        return accounts;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (connection!= null)
        {
            connection.Close();
        }
    }
}
</code>```

Body:
I have to make automatic generate new AccountID  on my load windows form app.

So for example when users start windows form "Add new Account" in textbox for "Account id" I have to show latest value from database. If i have two accounts in database on windows form in textbox value will be three.

My code perfectly work if i have at least one account in database, but when my database is empty i got exception.

This is my code:

public int GetLatestAccountID()
{
    try
    {
        command.CommandText = "select Max(AccountID)as maxID from Account";
        command.CommandType = CommandType.Text;

        connection.Open();

        OleDbDataReader reader= command.ExecuteReader();

        if (reader.Read())
        {
            int valueID = Convert.ToInt32(reader["maxID"]);
            return valueID + 1;
        }

        return 1;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (connection!= null)
        {
            connection.Close();
        }
    }
}

Also I find answer on stackoverflow:

object aa = DBNull.Value;
int valueID = (aa as int?).GetValueOrDefault();

But this line of code works if my database is empty, but when I have one account in the database, it will always show on my windows form in account id textbox value one. I use Microsoft Access 2007 database.

I appreciate any help.


来源: stackexchange

问:
A feature that has different meanings in different ranges
In machine learning, how to deal with a feature like salary.  For example,  if I'm applying k-nearest neighbors by measuring the distance between data points based on features.  Let's say we have two points with salaries 2000 and 6000.  The difference between them is 4000. Let's view another two points with salaries 102000 and 106000. The difference here is still 4000$ but we humans consider the last two points closer or more similar than the first two points.  </p>

<p>How do I incorporate such an intuition in machine learning? </p>

答:
You can do one of the following things (and many more):

transform the feature using log function (thus 2000 and 6000 would be much further than 102000 and 106000)

binarize feature into multiple buckets (you would create a feature for each range of salary and you are the one creating the buckets)

change similarity function in k-nn to look at relative instead of absolute difference

ContentLicense: CC BY-SA 3.0

Body:
In machine learning, how to deal with a feature like salary.  For example,  if I'm applying k-nearest neighbors by measuring the distance between data points based on features.  Let's say we have two points with salaries 2000 and 6000.  The difference between them is 4000. Let's view another two points with salaries 102000 and 106000. The difference here is still 4000$ but we humans consider the last two points closer or more similar than the first two points.

How do I incorporate such an intuition in machine learning?


问:
Natively access JSON POST payload from Node.js server
Consider the following HTTP POST call to a Node.js server:

```<code>curl -H "Content-Type: application/json" \
     -X POST \
     -d '{"jsonKey":"jsonValue"}' \
     'http://localhost:8080?abcd=efgh'
</code>```

I would like to access both the URL parameters and the JSON payload of the POST request.

Accessing the URL params is pretty straightforward by importing url.parse:

```<code>var server = http.createServer(function(req, res) {
        // Parse the params - prints "{ abcd: 'efgh' }"
        var URLParams = url.parse(req.url, true).query;
        console.log(URLParams);

        // How do I access the JSON payload as an object?
}
</code>```

But how do I access the JSON payload, using native Node.js library (without any npm import)?

What have I tried

Printed req to console.log, but did not find the POST object

Read the documentation of req, which is of type http.IncomingMessage

答:
From documentation:

When receiving a POST or PUT request, the request body might be
  important to your application. Getting at the body data is a little
  more involved than accessing request headers. The request object
  that's passed in to a handler implements the ReadableStream interface.
  This stream can be listened to or piped elsewhere just like any other
  stream. We can grab the data right out of the stream by listening to
  the stream's 'data' and 'end' events.

https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body

```<code>var server = http.createServer(function(req, res) {
        // Parse the params - prints "{ abcd: 'efgh' }"
        var URLParams = url.parse(req.url, true).query;
        console.log(URLParams);

        // How do I access the JSON payload as an object?
        var body = [];
        req.on('data', function(chunk) {
            body.push(chunk);
        }).on('end', function() {
            body = Buffer.concat(body).toString();
            if (body) console.log(JSON.parse(body));
            res.end('It Works!!');
        });
});
</code>```

Body:
Consider the following HTTP POST call to a Node.js server:

curl -H "Content-Type: application/json" \
     -X POST \
     -d '{"jsonKey":"jsonValue"}' \
     'http://localhost:8080?abcd=efgh'

I would like to access both the URL parameters and the JSON payload of the POST request.

Accessing the URL params is pretty straightforward by importing url.parse:

var server = http.createServer(function(req, res) {
        // Parse the params - prints "{ abcd: 'efgh' }"
        var URLParams = url.parse(req.url, true).query;
        console.log(URLParams);

        // How do I access the JSON payload as an object?
}

But how do I access the JSON payload, using native Node.js library (without any npm import)?

What have I tried

Printed req to console.log, but did not find the POST object

Read the documentation of req, which is of type http.IncomingMessage

Body:
From documentation:

When receiving a POST or PUT request, the request body might be
  important to your application. Getting at the body data is a little
  more involved than accessing request headers. The request object
  that's passed in to a handler implements the ReadableStream interface.
  This stream can be listened to or piped elsewhere just like any other
  stream. We can grab the data right out of the stream by listening to
  the stream's 'data' and 'end' events.

https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body

var server = http.createServer(function(req, res) {
        // Parse the params - prints "{ abcd: 'efgh' }"
        var URLParams = url.parse(req.url, true).query;
        console.log(URLParams);

        // How do I access the JSON payload as an object?
        var body = [];
        req.on('data', function(chunk) {
            body.push(chunk);
        }).on('end', function() {
            body = Buffer.concat(body).toString();
            if (body) console.log(JSON.parse(body));
            res.end('It Works!!');
        });
});


问:
Is there way to use PreferenceActivity without storing values in shared preferences
I have an android application that has uses few serializable classes
(I can store and load them in JSON format using Google Gson library and it works like a charm).

Now I want to provide way for user to edit those objects in fashion similar to PreferenceActivity - they contain few strings, ints and doubles and PreferenceScreen just seems ideal for editing them.

Is there a way to 'abuse' PreferenceActivity to provide UI for editing my objects without actually storing data in shared preferences?

For example - if there was some callback to override that is called just before saving data, I could extract data, assemble my object and somehow prevent Android from messing with preferences?

答:
First I would think if I really want to present objects editing with preferences UI since it might confuse a user.

If you still decide to go this way you can achieve it with:

Serialise every object in separate shared preference file and use preference activity how it is designed

Write own PreferenceManager and use reflection to replace private field in PreferenceActivity

The first one is straight forward and rather simple to implement, might have some performance implications. The second one might get tricky and probably requires more code to write.

I would still advice to revise decision to "re-use" PreferenceActivity for such case.


问:
How do I split a single pandas.DataFrame row into multiple columns delimited by space? Python
I am working with NCEI marine data which are .dat files without headers, using python (https://www.ncei.noaa.gov/data/marine/icoads3.0/ for the files)
They look like:

```<code>166210151200 4962 35378 1306    101134     NL 1585 26                                                        165 17796730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000003002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0493800N 102600E493700N         2 1TENERIFE                                                                                0 21662101512         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015WZW                    7.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                ZZO                                                                                MOU (?) KOELTE                                                                                00000000CLIWOC VERSION 1.0
166210161300 4907 35215 1306    101134     NL 1585 26                                                        165 17797730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000013002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0490400N  84800E                1 1TENERIFE                                                                                0 21662101612         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015ZW 1/2 N              18.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                ZZO                                                                                MOU KOELTE                                                                                00000000CLIWOC VERSION 1.0
166210171300 4812 35000 1306    101134     NL 1695 26                                                        165 17680730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000023002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0483000N  63900E480700N         2 1TENERIFE                                                                                0 21662101712         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015ZWTW                  15.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                ZTO                                                                                MOU KOELTE                                                                                MOOI WEER                                                                                00000000CLIWOC VERSION 1.0
166210181300 4758 34925 1306    101134     NL 1695 26                                                        165 17670730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000033002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0474100N  55400E473500N         2 1TENERIFE                                                                                0 21662101812         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015ZWTW                  11.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                ZTO                                                                                MOU KOELTE                                                                                'ENN MOUT'?                                                                                REGEN                                                                                01000000CLIWOC VERSION 1.0
166210191300 4757 34795 1306    101134     NL 1805 67                                                        165 17672730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000043002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0473400N  43600E                1 1TENERIFE                                                                                0 21662101912         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015W/Z                   14.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                Z                                                                                MARSZEILSKOELTE, TOUPKOULTE                                                                                REGEN                                                                                01000000CLIWOC VERSION 1.0
</code>```

These are tab delimited files which I have been importing using

```<code>data = pd.read_table('file.dat', header=None)
</code>```

Which imports the data as x rows with a single column containing all the data. In the single column each datum is separated by white space.

Is there a way in which I can import this data into columns or read the data variable and split each row into columns based on the white space. I thought that is what I was doing with the read.table function. The full dataset is large so I would prefer a method to import them over having to process them after.

答:
I think what you need is Fixed Width Formatted:

Code:

```<code>df = pd.read_fwf('IMMA.dat', header=None)
print(df.dtypes)
</code>```

Results:

```<code>[17 rows x 66 columns]
0       int64
1       int64
2       int64
3       int64
       ...
61     object
62     object
63     object
64     object
65    float64
dtype: object
</code>```

Body:
I am working with NCEI marine data which are .dat files without headers, using python (https://www.ncei.noaa.gov/data/marine/icoads3.0/ for the files)
They look like:

166210151200 4962 35378 1306    101134     NL 1585 26                                                        165 17796730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000003002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0493800N 102600E493700N         2 1TENERIFE                                                                                0 21662101512         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015WZW                    7.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                ZZO                                                                                MOU (?) KOELTE                                                                                00000000CLIWOC VERSION 1.0
166210161300 4907 35215 1306    101134     NL 1585 26                                                        165 17797730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000013002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0490400N  84800E                1 1TENERIFE                                                                                0 21662101612         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015ZW 1/2 N              18.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                ZZO                                                                                MOU KOELTE                                                                                00000000CLIWOC VERSION 1.0
166210171300 4812 35000 1306    101134     NL 1695 26                                                        165 17680730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000023002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0483000N  63900E480700N         2 1TENERIFE                                                                                0 21662101712         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015ZWTW                  15.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                ZTO                                                                                MOU KOELTE                                                                                MOOI WEER                                                                                00000000CLIWOC VERSION 1.0
166210181300 4758 34925 1306    101134     NL 1695 26                                                        165 17670730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000033002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0474100N  55400E473500N         2 1TENERIFE                                                                                0 21662101812         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015ZWTW                  11.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                ZTO                                                                                MOU KOELTE                                                                                'ENN MOUT'?                                                                                REGEN                                                                                01000000CLIWOC VERSION 1.0
166210191300 4757 34795 1306    101134     NL 1805 67                                                        165 17672730133 5 0                   2FF11FF11AAAAAAAAAAAA     98150000043002199 0 NAN     NATIONAAL ARCHIEF OF THE NETHERLANDS              DEN HAAG  NEDERLAND     1.11.01.01     1229             AANW                                   112                            AAN_1229_112                  DUTCH                         0473400N  43600E                1 1TENERIFE                                                                                0 21662101912         3         VM    8UNKNOWN        MAARSEVEEN                    DUTCH                  VOC                               M. GERRITSZ. BOOS             OPPERSTUURMAN                                                                                ROTTERDAM                                    BATAVIA                                           0                                                  0977.216621015W/Z                   14.00                                                                                UNKNOWN        UNKNOWN                                       UNKNOWN360 DEGREES                                                                                Z                                                                                MARSZEILSKOELTE, TOUPKOULTE                                                                                REGEN                                                                                01000000CLIWOC VERSION 1.0

These are tab delimited files which I have been importing using

data = pd.read_table('file.dat', header=None)

Which imports the data as x rows with a single column containing all the data. In the single column each datum is separated by white space.

Is there a way in which I can import this data into columns or read the data variable and split each row into columns based on the white space. I thought that is what I was doing with the read.table function. The full dataset is large so I would prefer a method to import them over having to process them after.

Body:
I think what you need is Fixed Width Formatted:

Code:

df = pd.read_fwf('IMMA.dat', header=None)
print(df.dtypes)

Results:

[17 rows x 66 columns]
0       int64
1       int64
2       int64
3       int64
       ...
61     object
62     object
63     object
64     object
65    float64
dtype: object


问:
how to make role menu in laravel
I need to make role menu in laravel , i have make in User model this funcion

```<code>public function isTeacher() {
    return $this->where('role', '3')->exists();
}
</code>```

and at the app.blade making this :

```<code>@if(Auth::user()->isTeacher())

    <li class=" btn">
        <a class="menu"  href="/">الرئيسية</a>
    </li>
    <li class=" btn">
        <a class="menu"  href="/">تقييم الأطفال</a>
    </li>
    <li class=" btn">
        <a class="menu" href="/">تسجيل طفل جديد</a>
    </li>
    <li class=" btn">
        <a class="menu" href="/indexTable">إدخال جدول الانشطة</a>
    </li>
    <li class=" btn">
        <a class="menu" href="/">مراجعة جدول الانشطة</a>
    </li>
@endif
@if (Auth::guest())

    <li class=" btn">
        <a href="/register" class="log"> تسجيل ولي أمر جديد </a>
    </li>
@endif
</code>```

But it's giving me that error :

Call to a member function isTeacher() on a non-object

答:
In your blade change:

```<code>@if(Auth::user()->isTeacher())
</code>```

to

```<code>@if(Auth::user() && Auth::user()->isTeacher())
</code>```

Your check is not correct, if user is not logged Auth::user() returns null, so before calling isTeacher() you have to check that Auth::user() is an object

Title: how to make role menu in laravel

Body:
I need to make role menu in laravel , i have make in User model this funcion

public function isTeacher() {
    return $this->where('role', '3')->exists();
}

and at the app.blade making this :

@if(Auth::user()->isTeacher())

        الرئيسية

        تقييم الأطفال

        تسجيل طفل جديد

        إدخال جدول الانشطة

        مراجعة جدول الانشطة

@endif
@if (Auth::guest())

         تسجيل ولي أمر جديد

@endif

But it's giving me that error :

Call to a member function isTeacher() on a non-object

Body:
In your blade change:

@if(Auth::user()->isTeacher())

to

@if(Auth::user() && Auth::user()->isTeacher())

Your check is not correct, if user is not logged Auth::user() returns null, so before calling isTeacher() you have to check that Auth::user() is an object


问:
C# thread with multiple methods
I'm making an app that manages a library. Currently I'm making the code for the research of the books and I've just come across an issue. I've created a Thread that handles this research, in addition to the one that handles the rest of the execution. I was asking to my self, is it possible that a Thread manages multiple methods? If so how can you do that, as you can only put one method in the declaration of the Thread. For example, when the user presses the search button (in a menubox) I only want the app (through my researchThread) to go to the url, running a goToUrl() method. Then, when the user presses the search button (after writing the keyWord of the book) I want the same thread to run another method (the search() method). As I don't want to create a thousand threads for every function (and as I think that this isn't the right solution), how can I manage this situation? Thanks in advance.</p>

答:
Use Task class instead of threads. Prevent using Threads unnecessarily. Working with Tasks will run your code Asynchronous. You also can use Async and Await keywords.</p>

```<code>    public void Start()
    {
        //Create Task with parameter
        Task search = new Task(() => new Action<int>(SomeSearchMethod)(4));

        // Create Normal Task
        Task download = new Task(SomeDownloadMethod);

        // Create Task with Return value
        Task<string> proccessString = Task.FromResult(SomeProcessing());
        MessageBox.Show(proccessString.Result);

        // Start Task
        search.Start();
        download.Start();

        // Wait untill task finisht
        search.Wait();
        download.Wait();
        /* or for both tasks*/
        Task.WaitAll();
    }

    private void SomeDownloadMethod()
    {
        //logic
    }

    private void SomeSearchMethod(int value)
    {
        MessageBox.Show("Parameter Search" + value.ToString());
    }

    private string SomeProcessing()
    {
        return "Proccess";
    }
</code>```

Title: C# thread with multiple methods

Body:
Use Task class instead of threads. Prevent using Threads unnecessarily. Working with Tasks will run your code Asynchronous. You also can use Async and Await keywords.

    public void Start()
    {
        //Create Task with parameter
        Task search = new Task(() => new Action<int>(SomeSearchMethod)(4));

        // Create Normal Task
        Task download = new Task(SomeDownloadMethod);

        // Create Task with Return value
        Task<string> proccessString = Task.FromResult(SomeProcessing());
        MessageBox.Show(proccessString.Result);

        // Start Task
        search.Start();
        download.Start();

        // Wait untill task finisht
        search.Wait();
        download.Wait();
        /* or for both tasks*/
        Task.WaitAll();
    }

    private void SomeDownloadMethod()
    {
        //logic
    }

    private void SomeSearchMethod(int value)
    {
        MessageBox.Show("Parameter Search" + value.ToString());
    }

    private string SomeProcessing()
    {
        return "Proccess";
    }


问:
How can I specify multiple choices in Class-Diagram?
I am making a class diagram of a system where a user can act as a student, instructor, or assistant. So far, I've created a user class with the following attributes, and methods, where a user can participate in a single course with a specific role, and also can remove from a particular course. Since, a user can have only one role, I've declared it in square brackets -Participant: Role [1].

However, it says only that a user can have one role, but it does not say the different roles of a user. How can I specify this in a class diagram. Should I make a new Role class, or I can specify in the user class?

```<code>USER CLASS:
Attributes:
-username: String
-password: String
-Participant: Role [1]
Methods:
+participate(course: Course, role: Role): void
+remove_user(course: Course): void
+get_average(assignment: Assignment): int
</code>```

答:
You can make Role abstract and then create subclasses for student, instructor, and assistant. That way you can only instantiate one of the subclasses per user.

Alternatively, you can make the Role an enumeration, where each enumeration literal is a particular instance of a Role. That way you can instantiate one of each Role across the entire system: student, instructor, and assistant.

In your system, should all users play the same role, or should each user in a role have additional information, such as the date the role was assigned to the user? The answer to this question tells you which alternative to choose.

BTW, isn't the limitation of a user being a student, instructor, or assistant, ever, a bit too limiting? Why couldn't a user play the role of student in one course while playing the role of an assistant in another course?

Body:
I am making a class diagram of a system where a user can act as a student, instructor, or assistant. So far, I've created a user class with the following attributes, and methods, where a user can participate in a single course with a specific role, and also can remove from a particular course. Since, a user can have only one role, I've declared it in square brackets -Participant: Role [1].

However, it says only that a user can have one role, but it does not say the different roles of a user. How can I specify this in a class diagram. Should I make a new Role class, or I can specify in the user class?

USER CLASS:
Attributes:
-username: String
-password: String
-Participant: Role [1]
Methods:
+participate(course: Course, role: Role): void
+remove_user(course: Course): void
+get_average(assignment: Assignment): int


问:
SQL 2 date ranges overlapping day count
I have a simple web app where users log in and assign ONE date range of when they are free to OFFER some days off, and ONE date range of when they WANT some days off. This takes the form of a Request. User A offers "Jan 01-Jan31" and wants "May 01-May31".

Now user B puts in a request where they OFFER May and also WANT January. In this example, the the requests match.

```<code> Requests Table
 --------------
 "User A", "20170101", "20170131", "20170501", "20170531"
 "User B", "20170501", "20170531", "20170101", "20170131"
</code>```

However, I need it a little bit more complicated than that. Users may not offer or want whole months, but a specific date range, such as :

User A offers Jan01-Jan31 but wants May20-May27

User B offers May15-May31 but wants Jan01-Jan05

In that example, they both match too, however I need to calculate the number of days that each request overlaps another and the request will only match if that overlap number >= X days (say an application set constant of 4 days).

So, each request is unioned with each other again, (to compare every request against every other request) and there needs to be the overlap day count to check for a match.

I found this formula which offers if there is an overlap, but I cant seem to return the day count too:

```<code> where not (t1.startdate > t2.endate or t1.enddate < t2.startdate)
</code>```

See SqlFiddle here: Fiddle

```<code>-- DateGivingFrom, DateGivingTo
-- DateWantFrom, DateWantTo
Create table t (Id int, uid varchar(6),
                dgf date, dgt date,
                Dwf date, dwt date);
   Insert into t values (1,"Human1","20170101","20170131","20170501","20170507");
   Insert into t values (2,"Human2","20170501","20170531","20170120","20170125");

Select *, (select count(*) from t
           where not (v.dgf > t.dwt or v.dgt < t.dwf) )
                  as DatesOverlap,
           ("?") as OverlapDayCount
from t as v ;
</code>```

NOTE

There will be hundreds of users each making a few requests, and also I wont do this calculation each time a user submits a request, as it may be quite intensive. Instead I will have a service which runs a "checker" to do this functionality (as it will then set notifications, send emails, etc, based on results)

This will be php based run in mysql. Many thanks.

答:
The basic idea is a self-join.  I'm not sure what you really want to calculate.  The following calculates the overlap of the two periods:  "g" to "w" and then "w" to "g".</p>

```<code>select t1.*, t2.*,
       datediff(least(t1.dgt, t2.dwt) greatest(t1.dgf, t2.dwf)) as gw_overlap,
       datediff(least(t2.dgt, t1.dwt) greatest(t2.dgf, t1.dwf)) as wg_overlap;
from t t1 join
     t t2
     on t1.dgf <= t2.dwt and t1.dgt >= t2.dwf and -- t1 "g" overlaps t2 "w"
        t2.dgf <= t1.dwt and t2.dgt >= t1.dwf and
        t1.uid <> t2.uid;
</code>```

Title: SQL 2 date ranges overlapping day count

Body:
I have a simple web app where users log in and assign ONE date range of when they are free to OFFER some days off, and ONE date range of when they WANT some days off. This takes the form of a Request. User A offers "Jan 01-Jan31" and wants "May 01-May31".

Now user B puts in a request where they OFFER May and also WANT January. In this example, the the requests match.

 Requests Table
 --------------
 "User A", "20170101", "20170131", "20170501", "20170531"
 "User B", "20170501", "20170531", "20170101", "20170131"

However, I need it a little bit more complicated than that. Users may not offer or want whole months, but a specific date range, such as :

User A offers Jan01-Jan31 but wants May20-May27

User B offers May15-May31 but wants Jan01-Jan05

In that example, they both match too, however I need to calculate the number of days that each request overlaps another and the request will only match if that overlap number >= X days (say an application set constant of 4 days).

So, each request is unioned with each other again, (to compare every request against every other request) and there needs to be the overlap day count to check for a match.

I found this formula which offers if there is an overlap, but I cant seem to return the day count too:

 where not (t1.startdate > t2.endate or t1.enddate < t2.startdate)

See SqlFiddle here: Fiddle

-- DateGivingFrom, DateGivingTo
-- DateWantFrom, DateWantTo
Create table t (Id int, uid varchar(6),
                dgf date, dgt date,
                Dwf date, dwt date);
   Insert into t values (1,"Human1","20170101","20170131","20170501","20170507");
   Insert into t values (2,"Human2","20170501","20170531","20170120","20170125");

Select *, (select count(*) from t
           where not (v.dgf > t.dwt or v.dgt < t.dwf) )
                  as DatesOverlap,
           ("?") as OverlapDayCount
from t as v ;

NOTE

There will be hundreds of users each making a few requests, and also I wont do this calculation each time a user submits a request, as it may be quite intensive. Instead I will have a service which runs a "checker" to do this functionality (as it will then set notifications, send emails, etc, based on results)

This will be php based run in mysql. Many thanks.

Body:
The basic idea is a self-join.  I'm not sure what you really want to calculate.  The following calculates the overlap of the two periods:  "g" to "w" and then "w" to "g".

select t1.*, t2.*,
       datediff(least(t1.dgt, t2.dwt) greatest(t1.dgf, t2.dwf)) as gw_overlap,
       datediff(least(t2.dgt, t1.dwt) greatest(t2.dgf, t1.dwf)) as wg_overlap;
from t t1 join
     t t2
     on t1.dgf <= t2.dwt and t1.dgt >= t2.dwf and -- t1 "g" overlaps t2 "w"
        t2.dgf <= t1.dwt and t2.dgt >= t1.dwf and
        t1.uid <> t2.uid;


问:
jquery change css click
I've created a menu which is one made by jquery for dropdown. It works fine. But I wanna rotate fa-bars. I wroten codes. CSS codes doesn't work. What I missed?</p>

```<code>$(function(){
    var a = 0;
    $('.topnavmenuOpen').click(function(){
        if ( a == 0 ){
            $(this).html('<i class="fa fa-bars" aria-hidden="true"></i>');
            a++;
        } else {
            $(this).html('<i class="fa fa-bars" aria-hidden="true"></i>');
            a = 0;
        }
        $(this).next('ul').slideToggle(500);

    });

$('.topnavmenuOpen').click(function(){
                          $('i .fa').css({
    'transform' : 'rotate(180deg)',
    'transition' : 'width 2s, height 2s, transform 2s'
});
                          });

});
</code>```

答: The problem is this selector: $('i .fa') which means "An element with the class .fa that's within an i element". You want $('i.fa') which means "An i element with the class .fa.

Title: jquery change css click

Body:
I've created a menu which is one made by jquery for dropdown. It works fine. But I wanna rotate fa-bars. I wroten codes. CSS codes doesn't work. What I missed?

$(function(){
    var a = 0;
    $('.topnavmenuOpen').click(function(){
        if ( a == 0 ){
            $(this).html('');
            a++;
        } else {
            $(this).html('');
            a = 0;
        }
        $(this).next('ul').slideToggle(500);

    });

$('.topnavmenuOpen').click(function(){
                          $('i .fa').css({
    'transform' : 'rotate(180deg)',
    'transition' : 'width 2s, height 2s, transform 2s'
});
                          });

});


问:
Win32 registry key writable by Everyone?
Is there a Registry key which is allowed for write access to any users and is shared among them?

I need to store some machine-specific data in my application, but this piece of data must be machine-dependent, not logged-user-depended. HKEY_LOCAL_MACHINE is only writable by Administrator. HKEY_CURRENT_USER is allowed for write, but is not shared with other users.

I think that in Windows filesystem folder C:\ProgramData (environment variable %ALLUSERSPROFILE%) is writable for anyone and is shared, but does Registry has something similar?

答: It is the same for the file system as well as the registry, out of the box nothing is shared between users with a limited user account.  This is trivially solved by creating a directory or registry key that has write access by Everyone.  By an admin or a program that runs with admin rights.</p>

ContentLicense: CC BY-SA 2.5


问:
combining items in a json
I was able to write a solution, but I was wondering if there is a more elegant and efficient way to do it.

```<code>    var arr = [];

//I have a array like this:
    arr = [{
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 1,
        studentName: 'A',
        studentAge: 10
      },
      {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 2,
        studentName: 'B',
        studentAge: 11
      }, {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 3,
        studentName: 'C',
        studentAge: 12
      },

      {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 4,
        studentName: 'D',
        studentAge: 9
      }, {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 5,
        studentName: 'E',
        studentAge: 12
      }
    ];

//want to group the students info in each indiviual teacher like this:
//*
    [{
      "teacherid": 10,
      "teacherName": "andy",
      "age": 30,
      "studentArr": [{
        "studentid": 1,
        "studentName": "A",
        "studentAge": 10
      }, {
        "studentid": 2,
        "studentName": "B",
        "studentAge": 11
      }, {
        "studentid": 3,
        "studentName": "C",
        "studentAge": 12
      }]
    }, {
      "teacherid": 11,
      "teacherName": "May",
      "age": 40,
      "studentArr": [{
        "studentid": 4,
        "studentName": "D",
        "studentAge": 9
      }, {
        "studentid": 5,
        "studentName": "E",
        "studentAge": 12
      }]
    }
    }]
*//

//my solution
    var result = [];
    var first = true;
    arr = _.sortBy(arr, 'teacherid');

    (function() {
      for (var i = 0; i < arr.length; i++) {
        for (var j = i; j < arr.length; j++) {
          console.log("comparing i:" + i + " with j:" + j);

          if (i === j && j === arr.length) {
            console.log("exit " + i + " : " + j)
            return;
          } else if (arr[i].teacherid === arr[j].teacherid) {
            if (first) {
              result.push({
                teacherid: arr[j].teacherid,
                teacherName: arr[j].teacherName,
                age: arr[j].age,
                studentArr: [{
                  studentid: arr[j].studentid,
                  studentName: arr[j].studentName,
                  studentAge: arr[j].studentAge
                }]
              })
            } else {
              //find in result arr, the obj that contain this teacher and push the student in the array
              var teacher = _.find(result, function(item) {
                return (item.teacherid === arr[j].teacherid)
              })
              teacher.studentArr.push({
                studentid: arr[j].studentid,
                studentName: arr[j].studentName,
                studentAge: arr[j].studentAge
              })
            }
            first = false;

          } else {
            first = true;
            i = j - 1;
            j = arr.length; //end inner loop, go back to outer loop and check next teacherID
          }
        }
      }

    })()

    console.log(JSON.stringify(result));
</code>```

This would be a headache if another programmer were to read it. I was wondering if there is a better solution (more efficient and/or more readable) than this. I feel like I brute-forced this

答:
You could use a closure with a hash table for the teachers.

var array = [{ teacherid: 10, teacherName: 'andy', age: 30, studentid: 1, studentName: 'A', studentAge: 10 }, { teacherid: 10, teacherName: 'andy', age: 30, studentid: 2, studentName: 'B', studentAge: 11 }, { teacherid: 10, teacherName: 'andy', age: 30, studentid: 3, studentName: 'C', studentAge: 12 }, { teacherid: 11, teacherName: 'May', age: 40, studentid: 4, studentName: 'D', studentAge: 9 }, { teacherid: 11, teacherName: 'May', age: 40, studentid: 5, studentName: 'E', studentAge: 12 }],
    grouped = array.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a.teacherid]) {
                hash[a.teacherid] = {
                    teacherid: a.teacherid,
                    teacherName: a.teacherName,
                    studentArr: []
                };
                r.push(hash[a.teacherid]);
            }
            hash[a.teacherid].studentArr.push({
                studentid: a.studentid,
                studentName: a.studentName,
                studentAge: a.studentAge
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: combining items in a json

Body:
I was able to write a solution, but I was wondering if there is a more elegant and efficient way to do it.

    var arr = [];

//I have a array like this:
    arr = [{
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 1,
        studentName: 'A',
        studentAge: 10
      },
      {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 2,
        studentName: 'B',
        studentAge: 11
      }, {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 3,
        studentName: 'C',
        studentAge: 12
      },

      {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 4,
        studentName: 'D',
        studentAge: 9
      }, {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 5,
        studentName: 'E',
        studentAge: 12
      }
    ];

//want to group the students info in each indiviual teacher like this:
//*
    [{
      "teacherid": 10,
      "teacherName": "andy",
      "age": 30,
      "studentArr": [{
        "studentid": 1,
        "studentName": "A",
        "studentAge": 10
      }, {
        "studentid": 2,
        "studentName": "B",
        "studentAge": 11
      }, {
        "studentid": 3,
        "studentName": "C",
        "studentAge": 12
      }]
    }, {
      "teacherid": 11,
      "teacherName": "May",
      "age": 40,
      "studentArr": [{
        "studentid": 4,
        "studentName": "D",
        "studentAge": 9
      }, {
        "studentid": 5,
        "studentName": "E",
        "studentAge": 12
      }]
    }
    }]
*//

//my solution
    var result = [];
    var first = true;
    arr = _.sortBy(arr, 'teacherid');

    (function() {
      for (var i = 0; i < arr.length; i++) {
        for (var j = i; j < arr.length; j++) {
          console.log("comparing i:" + i + " with j:" + j);

          if (i === j && j === arr.length) {
            console.log("exit " + i + " : " + j)
            return;
          } else if (arr[i].teacherid === arr[j].teacherid) {
            if (first) {
              result.push({
                teacherid: arr[j].teacherid,
                teacherName: arr[j].teacherName,
                age: arr[j].age,
                studentArr: [{
                  studentid: arr[j].studentid,
                  studentName: arr[j].studentName,
                  studentAge: arr[j].studentAge
                }]
              })
            } else {
              //find in result arr, the obj that contain this teacher and push the student in the array
              var teacher = _.find(result, function(item) {
                return (item.teacherid === arr[j].teacherid)
              })
              teacher.studentArr.push({
                studentid: arr[j].studentid,
                studentName: arr[j].studentName,
                studentAge: arr[j].studentAge
              })
            }
            first = false;

          } else {
            first = true;
            i = j - 1;
            j = arr.length; //end inner loop, go back to outer loop and check next teacherID
          }
        }
      }

    })()

    console.log(JSON.stringify(result));

This would be a headache if another programmer were to read it. I was wondering if there is a better solution (more efficient and/or more readable) than this. I feel like I brute-forced this

Body:
You could use a closure with a hash table for the teachers.

var array = [{ teacherid: 10, teacherName: 'andy', age: 30, studentid: 1, studentName: 'A', studentAge: 10 }, { teacherid: 10, teacherName: 'andy', age: 30, studentid: 2, studentName: 'B', studentAge: 11 }, { teacherid: 10, teacherName: 'andy', age: 30, studentid: 3, studentName: 'C', studentAge: 12 }, { teacherid: 11, teacherName: 'May', age: 40, studentid: 4, studentName: 'D', studentAge: 9 }, { teacherid: 11, teacherName: 'May', age: 40, studentid: 5, studentName: 'E', studentAge: 12 }],
    grouped = array.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a.teacherid]) {
                hash[a.teacherid] = {
                    teacherid: a.teacherid,
                    teacherName: a.teacherName,
                    studentArr: []
                };
                r.push(hash[a.teacherid]);
            }
            hash[a.teacherid].studentArr.push({
                studentid: a.studentid,
                studentName: a.studentName,
                studentAge: a.studentAge
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Copy Value of Local into Pointer
Trying to find the correct way to do this, but can't seem to find the correct syntax anywhere..

all I want to do is copy the the value of a local variable into a pointer, so I may use that pointer anywhere. Otherwise when the method returns the value of the that pointer will be unpredictable.. Heres what I have but it seems to still just reference the address of the local variable

```<code>void method(){

 unsigned int localValue = 0x00FF00AA;
 unsigned int *point = (unsigned int *) 0x00000000;
 *point = localValue;
}
</code>```

but this code just seg faults. Is there a way to do this?

答:
It seg faults, beacause you are trying to write via a NULL pointer.

You can directly give to your pointer the address of the integer you want to use, by using the &-operator.

```<code>unsigned int localValue = 0x00FF00AA;
unsigned int *point = &localValue;
</code>```

EDIT: After the really helpful comments below, I noticed that my first sentence might be wrong, even if it is only a little detail, that makes it sound so. What you are trying to do is not write to a NULL pointer, but dereference it, in order to write to the (non-existent) object it points to.

Title: Copy Value of Local into Pointer

Body:
Trying to find the correct way to do this, but can't seem to find the correct syntax anywhere..

all I want to do is copy the the value of a local variable into a pointer, so I may use that pointer anywhere. Otherwise when the method returns the value of the that pointer will be unpredictable.. Heres what I have but it seems to still just reference the address of the local variable

void method(){

 unsigned int localValue = 0x00FF00AA;
 unsigned int *point = (unsigned int *) 0x00000000;
 *point = localValue;
}

but this code just seg faults. Is there a way to do this?

Body:
It seg faults, beacause you are trying to write via a NULL pointer.

You can directly give to your pointer the address of the integer you want to use, by using the &-operator.

unsigned int localValue = 0x00FF00AA;
unsigned int *point = &localValue;

EDIT: After the really helpful comments below, I noticed that my first sentence might be wrong, even if it is only a little detail, that makes it sound so. What you are trying to do is not write to a NULL pointer, but dereference it, in order to write to the (non-existent) object it points to.


问:
Custom Json Marshaling
I have a third-party json api to work with in go.

It has some endpoints which return data as key-value.

For example here is json for statuses:

```<code>{
  "result": {
    "0": "done",
    "1": "incomplete",
    "2": "completed",
    ....
  }
}
</code>```

So as you see it is not an array it is an object.

Is it possible to marshal this kind of json to array of objects like

```<code>type Status struct {
    Id int
    Status string
}
</code>```

without using additional struct like

```<code>type StatusReposne struct {
    Result map[string]string `json:"result"`
}
</code>```

and code to extract values?

答:
As @mkopriva stated in the comment, it's not possible without some extra work. This code does provide means to Marshal/Unmarshal data to/from a slice of Statuss:

```<code>func main() {
    sr := new(StatusReposne)

    json.Unmarshal([]byte(input), sr)
    fmt.Printf("%+v\n", sr)

    js, _ := json.Marshal(sr)
    fmt.Printf("%s\n", js)
}

type StatusReposne struct {
    Result []Status `json:"result"`
}

type Status struct {
    Id     int
    Status string
}

func (x *StatusReposne) MarshalJSON() ([]byte, error) {
    var buffer struct {
        Result map[string]string `json:"result"`
    }
    buffer.Result = make(map[string]string)
    for _, v := range x.Result {
        buffer.Result[strconv.Itoa(v.Id)] = v.Status
    }
    return json.Marshal(&buffer)
}

func (x *StatusReposne) UnmarshalJSON(b []byte) error {
    var buffer struct {
        Result map[string]string `json:"result"`
    }
    buffer.Result = make(map[string]string)
    json.Unmarshal(b, &buffer)
    for k, v := range buffer.Result {
        k, _ := strconv.Atoi(k)
        x.Result = append(x.Result, Status{Id: k, Status: v})
    }
    return nil
}

var input = `{
  "result": {
    "0": "done",
    "1": "incomplete",
    "2": "completed"
  }
}`
</code>```

Title: Custom Json Marshaling

Body:
I have a third-party json api to work with in go.

It has some endpoints which return data as key-value.

For example here is json for statuses:

{
  "result": {
    "0": "done",
    "1": "incomplete",
    "2": "completed",
    ....
  }
}

So as you see it is not an array it is an object.

Is it possible to marshal this kind of json to array of objects like

type Status struct {
    Id int
    Status string
}

without using additional struct like

type StatusReposne struct {
    Result map[string]string `json:"result"`
}

and code to extract values?

Body:
As @mkopriva stated in the comment, it's not possible without some extra work. This code does provide means to Marshal/Unmarshal data to/from a slice of Statuss:

func main() {
    sr := new(StatusReposne)

    json.Unmarshal([]byte(input), sr)
    fmt.Printf("%+v\n", sr)

    js, _ := json.Marshal(sr)
    fmt.Printf("%s\n", js)
}

type StatusReposne struct {
    Result []Status `json:"result"`
}

type Status struct {
    Id     int
    Status string
}

func (x *StatusReposne) MarshalJSON() ([]byte, error) {
    var buffer struct {
        Result map[string]string `json:"result"`
    }
    buffer.Result = make(map[string]string)
    for _, v := range x.Result {
        buffer.Result[strconv.Itoa(v.Id)] = v.Status
    }
    return json.Marshal(&buffer)
}

func (x *StatusReposne) UnmarshalJSON(b []byte) error {
    var buffer struct {
        Result map[string]string `json:"result"`
    }
    buffer.Result = make(map[string]string)
    json.Unmarshal(b, &buffer)
    for k, v := range buffer.Result {
        k, _ := strconv.Atoi(k)
        x.Result = append(x.Result, Status{Id: k, Status: v})
    }
    return nil
}

var input = `{
  "result": {
    "0": "done",
    "1": "incomplete",
    "2": "completed"
  }
}`

ContentLicense: CC BY-SA 4.0


问:
How to kill python interpreter with long running C/C++ code executed in the backend?
In the python documentation, it seems like signal sent from python side could not kill long-running C/C++ process:

A long-running calculation implemented purely in C (such as regular expression matching on a large body of text) may run uninterrupted for an arbitrary amount of time, regardless of any signals received. The Python signal handlers will be called when the calculation finishes.

Is there a workaround for this? Could I implement something in C/C++ side(i.e, a callback function?) to capture keyboard interruption?

Thanks a lot for help!

答: Found a workaround here, it seems like making the long running CPython program a daemon thread is one way to handle it.</p>


问:
Sublime Text: Switching files in different folders
I have opened a c++ project in Sublime Text and I am working on windows environment.
I need to switch among .cpp and .h files. There is a command Alt+O which can switch these files if they are in the same folder. but my files are placed as follow:

.h in myfolder/include/subfolder/

.cpp in myfolder/src/subfolder/

The file names are same, they just differ in extensions. Right now I use Ctrl+p, but I want single command to do that.
Thanks in Advance

答: Switch File Deluxe does exactly what you want. It overrides Alt+O.


问:
Error 1064 (42000 in mysql code
When i put my code in

```<code>CREATE TABLE EVENT (
    Event_ID SMALLINT PRIMARY KEY NOT NULL AUTO_INCREMENT,
    Event_Name VARCHAR(30) NOT NULL,
    Event_Date DATE NOT NULL,
    Event_Route VARCHAR(40) NOT NULL,
    Event_Location VARCHAR(60) NULL,
    Event_Cost DECIMAL(8,2) NOT NULL,
    Staff_ID SMALLINT FOREIGN KEY NOT NULL,
    Package_ID SMALLINT FOREIGN KEY NOT NULL,
    CONSTRAINT Staff_ID FOREIGN KEY (Staff_ID) REFERENCES STAFF (Staff_ID),
    CONSTRAINT Package_ID FOREIGN KEY (Package_ID) REFERENCES PACKAGE  (Package_ID)
);
</code>```

I get this error message below

ERROR 1064 (42000): You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near 'FOREIGN KEY NOT NULL, Package_ID SMALLINT FOREIGN
  KEY NOT NULL, CONSTRAINT Staff' at line 8

答:
I think the error is pretty clear.  You have key words in the middle of the definition of Package_Id and Staff_Id (FOREIGN KEY). These are not necessary, they are handled by the constraint definition:

```<code>CREATE TABLE EVENT (
    Event_ID SMALLINT PRIMARY KEY NOT NULL AUTO_INCREMENT,
    Event_Name VARCHAR(30) NOT NULL,
    Event_Date DATE NOT NULL,
    Event_Route VARCHAR(40) NOT NULL,
    Event_Location VARCHAR(60) NULL,
    Event_Cost DECIMAL(8,2) NOT NULL,
    Staff_ID SMALLINT NOT NULL,
    Package_ID SMALLINT NOT NULL,
    CONSTRAINT Staff_ID FOREIGN KEY (Staff_ID) REFERENCES STAFF (Staff_ID),
    CONSTRAINT Package_ID FOREIGN KEY (Package_ID) REFERENCES PACKAGE  (Package_ID)
);
</code>```

I would dissuade you from naming the table Event or even Events.  The name is not reserved, but it is a keyword in MySQL.

Title: Error 1064 (42000 in mysql code

Body:
When i put my code in

CREATE TABLE EVENT (
    Event_ID SMALLINT PRIMARY KEY NOT NULL AUTO_INCREMENT,
    Event_Name VARCHAR(30) NOT NULL,
    Event_Date DATE NOT NULL,
    Event_Route VARCHAR(40) NOT NULL,
    Event_Location VARCHAR(60) NULL,
    Event_Cost DECIMAL(8,2) NOT NULL,
    Staff_ID SMALLINT FOREIGN KEY NOT NULL,
    Package_ID SMALLINT FOREIGN KEY NOT NULL,
    CONSTRAINT Staff_ID FOREIGN KEY (Staff_ID) REFERENCES STAFF (Staff_ID),
    CONSTRAINT Package_ID FOREIGN KEY (Package_ID) REFERENCES PACKAGE  (Package_ID)
);

I get this error message below

ERROR 1064 (42000): You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near 'FOREIGN KEY NOT NULL, Package_ID SMALLINT FOREIGN
  KEY NOT NULL, CONSTRAINT Staff' at line 8

Body:
I think the error is pretty clear.  You have key words in the middle of the definition of Package_Id and Staff_Id (FOREIGN KEY). These are not necessary, they are handled by the constraint definition:

CREATE TABLE EVENT (
    Event_ID SMALLINT PRIMARY KEY NOT NULL AUTO_INCREMENT,
    Event_Name VARCHAR(30) NOT NULL,
    Event_Date DATE NOT NULL,
    Event_Route VARCHAR(40) NOT NULL,
    Event_Location VARCHAR(60) NULL,
    Event_Cost DECIMAL(8,2) NOT NULL,
    Staff_ID SMALLINT NOT NULL,
    Package_ID SMALLINT NOT NULL,
    CONSTRAINT Staff_ID FOREIGN KEY (Staff_ID) REFERENCES STAFF (Staff_ID),
    CONSTRAINT Package_ID FOREIGN KEY (Package_ID) REFERENCES PACKAGE  (Package_ID)
);

I would dissuade you from naming the table Event or even Events.  The name is not reserved, but it is a keyword in MySQL.


问:
MySQL: large amount of data
first of all let me try to describe my problem.
Client is using application for a single year and he stored about 7 milions records into mysql database. His plan is to continue working even more on this application but it slows down with this amount of data.

Of course, the question is what will happend in next year, two or five...

This is pretty specific case where ~98% of data is stored in one single relational table (it is link between 2 tables).

What is the "best" solution in this case?
Best includes safe, well designed, the most logical solution which make the app usable for a long time and prevents this situation.

My toughts: keep current table as a history table and create a new one where I can store records for last 3 months and do some movements when records get old?

Respect!

答:
For a many:many mapping table, use the tips described here: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table . That will improve performance in many situations.

Please provide SHOW CREATE TABLE and the SELECTs that are slowing down.

If that much of the data is in the 'link' table, how do the queries differ from a CROSS JOIN?

Partitioning rarely improves performance.  Again, need to see the queries.  MERGE is a MyISAM-based pre-PARTITION kludge.  Do not use it.

History table?  Do the queries look for the "latest" of something?  Again, need to see the schema and queries.

Title: MySQL: large amount of data


问:
PHP query for Database update executing successfully but values are not getting updated on database table
I'm updating customer details by fetching the data from the html form. The PHP query for the database is getting executed but changed data is not reflected in my Database table.

PHP code:

Code to fetch data from the form

```<code>$con = mysqli_connect("localhost","root","","ecommerce");
    if(isset($_POST['savec']))
    {
        global $con;

        $name=$_POST['name'];
        $phone=$_POST['phone'];
        $email=$_POST['email'];
        $passm=$_POST['password'];
        $pass=md5($passm);
        $cust_query="UPDATE er_customer SET customer_name='$name',customer_phone='$phone',customer_email='$email',customer_password='$pass' WHERE customer_id='c_id'";
        $excecute=mysqli_query($con,$cust_query);

        if($excecute)
        {
            echo "<script> alert('Account changes is successfull.') </script>";
        }
    }
</code>```

Form code:

```<code>>    <form method="post" class="registration-form"
> action="account_settings.php" id="form_login"
> enctype="multipart/form-data">
>
>                   <div class="form-group">
>                         <label>Name</label>
>                            <input class="form-control"  name="name" type="text" value="<?php echo"$c_name"; ?>" required>
>
>                     </div>
>
>                   <div class="form-group">
>                         <label>Phone</label>
>                            <input class="form-control" name="phone" type="text" value="<?php echo"$c_phone"; ?>" required>
>
>                     </div>
>
>
>                   <div class="form-group">
>                         <label>Email</label>
>                            <input class="form-control" name="email" type="text" value="<?php echo"$c_email"; ?>" required>
>
>                     </div>
>
>
>                   <div class="form-group">
>                         <label>Password</label>
>                            <input class="form-control" name="password" type="text" value="" required>
>                     </div>
>
>                   </br>
>
>                   <div class="form-group">
>
>                            <input type="submit" class="col-sm-3 btn btn-success" name="savec" value="Save changes" align="center" />
>
>                     </div>
>
>
>               </form>
</code>```

答:
Try changing your update query like this:

```<code>$cust_query="UPDATE er_customer SET customer_name=$name,customer_phone=$phone,customer_email=$email,customer_password=$pass WHERE customer_id=$c_id";
</code>```

Make sure by debugging all variable values you are getting properly

Body:
I'm updating customer details by fetching the data from the html form. The PHP query for the database is getting executed but changed data is not reflected in my Database table.

PHP code:

Code to fetch data from the form

$con = mysqli_connect("localhost","root","","ecommerce");
    if(isset($_POST['savec']))
    {
        global $con;

        $name=$_POST['name'];
        $phone=$_POST['phone'];
        $email=$_POST['email'];
        $passm=$_POST['password'];
        $pass=md5($passm);
        $cust_query="UPDATE er_customer SET customer_name='$name',customer_phone='$phone',customer_email='$email',customer_password='$pass' WHERE customer_id='c_id'";
        $excecute=mysqli_query($con,$cust_query);

        if($excecute)
        {
            echo "";
        }
    }

Form code:

>    <form method="post" class="registration-form"
> action="account_settings.php" id="form_login"
> enctype="multipart/form-data">
>
>

>                         Name
>                            <input class="form-control"  name="name" type="text" value="<?php echo"$c_name"; ?>" required>
>
>

>
>

>                         Phone
>                            <input class="form-control" name="phone" type="text" value="<?php echo"$c_phone"; ?>" required>
>
>

>
>
>

>                         Email
>                            <input class="form-control" name="email" type="text" value="<?php echo"$c_email"; ?>" required>
>
>

>
>
>

>                         Password
>                            <input class="form-control" name="password" type="text" value="" required>
>

>
>

>
>

>
>                            <input type="submit" class="col-sm-3 btn btn-success" name="savec" value="Save changes" align="center" />
>
>

>
>
>               </form>

Body:
Try changing your update query like this:

$cust_query="UPDATE er_customer SET customer_name=$name,customer_phone=$phone,customer_email=$email,customer_password=$pass WHERE customer_id=$c_id";

Make sure by debugging all variable values you are getting properly


问:
Storing a JSON schema in mongodb with spring
I am new to Spring data and mongodb. I have a JSON object which represents a JSON Schema and I need to store that in mongodb using spring data. But the issue with JSON schema is the structure of JSON Schema is dynamic; for example below are two valid JSON schema with completely different structure.

```<code>{
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            "minLength": 10
        },
        "age": {
            "type": "integer"
        }
    },
    "required": [
        "name",
        "age"
    ]
}
</code>```

```<code>{
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "abc": {
                "type": "boolean"
            },
            "xyz": {
                "$ref": "#/definitions/"
            },
            "asd": {
                "type": "null"
            }
        },
        "required": [
            "abc",
            "xyz"
        ]
    }
}
</code>```

How can I define a JAVA POJO Class so that I can map the above JSON with the defined class and store it in mongodb. Or is it possible to do CURD operation in spring without mapping it to a POJO class?

答:
I would recommend using MongoTemplate and serialize and deserailize using Gson/Jackson.

Mongo Template have CRUD methods which takes collection name and DBObject entity which is very similar to if you were to directly use mongo java driver.

So you will have json payload and using one of the mapper library to convert them into Map.

Something like

Deserialise

```<code>ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String,Object>> typeRef
        = new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> map = mapper.readValue(jsonpayload, typeRef);
</code>```

DBObject

```<code>DBObject dbObject = new BasicDBObject(map);
</code>```

MongoTemplate

```<code>mongoTemplate.save(dbObject, "collectionname");
</code>```

You can do something similar for all other CRUD operations.

Body:
I am new to Spring data and mongodb. I have a JSON object which represents a JSON Schema and I need to store that in mongodb using spring data. But the issue with JSON schema is the structure of JSON Schema is dynamic; for example below are two valid JSON schema with completely different structure.

{
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            "minLength": 10
        },
        "age": {
            "type": "integer"
        }
    },
    "required": [
        "name",
        "age"
    ]
}

{
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "abc": {
                "type": "boolean"
            },
            "xyz": {
                "$ref": "#/definitions/"
            },
            "asd": {
                "type": "null"
            }
        },
        "required": [
            "abc",
            "xyz"
        ]
    }
}

How can I define a JAVA POJO Class so that I can map the above JSON with the defined class and store it in mongodb. Or is it possible to do CURD operation in spring without mapping it to a POJO class?

Body:
I would recommend using MongoTemplate and serialize and deserailize using Gson/Jackson.

Mongo Template have CRUD methods which takes collection name and DBObject entity which is very similar to if you were to directly use mongo java driver.

So you will have json payload and using one of the mapper library to convert them into Map.

Something like

Deserialise

ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String,Object>> typeRef
        = new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> map = mapper.readValue(jsonpayload, typeRef);

DBObject

DBObject dbObject = new BasicDBObject(map);

MongoTemplate

mongoTemplate.save(dbObject, "collectionname");

You can do something similar for all other CRUD operations.


问:
Compression to Improve Hard Disk Write Performance
On a modern system can local hard disk write speeds be improved by compressing the output stream?

This question derives from a case I'm working with where a program serially generates and dumps around 1-2GB of text logging data to a raw text file on the hard disk and I think it is IO bound. Would I expect to be able to decrease runtimes by compressing the data before it goes to disk or would the overhead of compression eat up any gain I could get? Would having an idle second core affect this?

I know this would be affected by how much CPU is being used to generate the data so rules of thumb on how much idle CPU time would be needed would be good.

I recall a video talk where someone used compression to improve read speeds for a database but IIRC compressing is a lot more CPU intensive than decompressing.

答:
This depends on lots of factors and I don't think there is one correct answer. It comes down to this:

Can you compress the raw data faster than the raw write performance of your disk times the compression ratio you are achieving (or the multiple in speed you are trying to get) given the CPU bandwidth you have available to dedicate to this purpose?

Given today's relatively high data write rates in the 10's of MBytes/second this is a pretty high hurdle to get over. To the point of some of the other answers, you would likely have to have easily compressible data and would just have to benchmark it with some test of reasonableness type experiments and find out.

Relative to a specific opinion (guess!?) to the point about additional cores. If you thread up the compression of the data and keep the core(s) fed - with the high compression ratio of text, it is likely such a technique would bear some fruit. But this is just a guess. In a single threaded application alternating between disk writes and compression operations, it seems much less likely to me.

OwnerDisplayName: BCS

LastEditorDisplayName: BCS

OwnerDisplayName: InSciTek Jeff

LastEditorDisplayName: InSciTek Jeff


问:
Making csv from txt files
I have a lot of txt files like this:

```<code>Title 1
Text 1(more then 1 line)
</code>```

And I would like to make one csv file from all of them that it will look like this:

```<code>Title 1,Text 1
Title 2,Text 2
Title 3,Text 3
etc
</code>```

How could I do it? I think that awk is good for it but don't know how to realize it.

答:
This is approximately what you posted with some improvements.

```<code>for text in *
do
    awk 'BEGIN {q="\""; print q}
         NR==1 {
                gsub(" "," ")    # why?
                gsub("Title: *","")
                print
               }
         NR>1  {
                gsub(" "," ")    # why?
                gsub("Content: *","")
                gsub(q,q q)
                print
               }

         END {print q}' "$text" >> ../final
done
</code>```

Edit:

If you have a bunch of files that consist of only two lines, try this:

```<code>sed 'N;s/\n/,/' file*.txt
</code>```

If the files contain more than two lines each then it will put each pair of lines on the same line separated by a comma.

Title: Making csv from txt files

Body:
I have a lot of txt files like this:

Title 1
Text 1(more then 1 line)

And I would like to make one csv file from all of them that it will look like this:

Title 1,Text 1
Title 2,Text 2
Title 3,Text 3
etc

How could I do it? I think that awk is good for it but don't know how to realize it.

Body:
This is approximately what you posted with some improvements.

for text in *
do
    awk 'BEGIN {q="\""; print q}
         NR==1 {
                gsub(" "," ")    # why?
                gsub("Title: *","")
                print
               }
         NR>1  {
                gsub(" "," ")    # why?
                gsub("Content: *","")
                gsub(q,q q)
                print
               }

         END {print q}' "$text" >> ../final
done

Edit:

If you have a bunch of files that consist of only two lines, try this:

sed 'N;s/\n/,/' file*.txt

If the files contain more than two lines each then it will put each pair of lines on the same line separated by a comma.


问:
User defined function returns unexpected result
This is my first question on stackoverflow.com!

I have created the following functions to check for the existence of and remove a table in my PostgreSQL database, both before and after removal. Unfortunately, the removal function doesn't give me the expected output. When I evaluate psql.exists.boolean(x,y) with my inputs, it returns the expected result of TRUE, but when I evaluate psql.drop(x,y) with the same inputs, it doesn't return the expected result. Please provide me with some guidance for fixing my erroneous function.

```<code>psql.drop<-function(x,y){
table.bad<-x
dbschema<-y
db.location <- c(y,x)
if (psql.exists.boolean(y,x)==TRUE){
  dbRemoveTable(con,db.location)
    if (psql.exists.boolean(y,x)==TRUE){
      msg<-paste("ERROR! The table",dQuote(paste(db.location, collapse = '.')),"still exists!")
  } else if (psql.exists.boolean(y,x)==FALSE){
      msg<-paste("The table",dQuote(paste(db.location, collapse = '.')),"was successfully removed.")
  } else {
     msg<-paste("ERROR! Something went wrong.")
  }
} else {
  msg<-paste("The table",dQuote(paste(db.location, collapse = '.')),"doesn't exist.")
}
return(print(msg))

psql.drop("test_table_1","test_schema_1")
</code>```

and

```<code>psql.exists.boolean<-function(x,y){
  # table name to check
  table.name<-x
  # schema where table is stored
  dbschema<-y
  # name format in schema
  db.location <- c(dbschema, table.name)
  # check if table existence in specified location is true
  if(dbExistsTable(con,db.location)==TRUE){
    return(TRUE)
  }else{
    return(FALSE)
  }
}

psql.exists.boolean("test_table_1","test_schema_1")
</code>```

答:
Your function psql.exists.boolean takes as input first the table name, then the schema name.
But when you call it within psql.drop, you give it first the schema name, then the table name (psql.exists.boolean(y,x)). </p>

Body:
This is my first question on stackoverflow.com!

I have created the following functions to check for the existence of and remove a table in my PostgreSQL database, both before and after removal. Unfortunately, the removal function doesn't give me the expected output. When I evaluate psql.exists.boolean(x,y) with my inputs, it returns the expected result of TRUE, but when I evaluate psql.drop(x,y) with the same inputs, it doesn't return the expected result. Please provide me with some guidance for fixing my erroneous function.

psql.drop<-function(x,y){
table.bad<-x
dbschema<-y
db.location <- c(y,x)
if (psql.exists.boolean(y,x)==TRUE){
  dbRemoveTable(con,db.location)
    if (psql.exists.boolean(y,x)==TRUE){
      msg<-paste("ERROR! The table",dQuote(paste(db.location, collapse = '.')),"still exists!")
  } else if (psql.exists.boolean(y,x)==FALSE){
      msg<-paste("The table",dQuote(paste(db.location, collapse = '.')),"was successfully removed.")
  } else {
     msg<-paste("ERROR! Something went wrong.")
  }
} else {
  msg<-paste("The table",dQuote(paste(db.location, collapse = '.')),"doesn't exist.")
}
return(print(msg))

psql.drop("test_table_1","test_schema_1")

and

psql.exists.boolean<-function(x,y){
  # table name to check
  table.name<-x
  # schema where table is stored
  dbschema<-y
  # name format in schema
  db.location <- c(dbschema, table.name)
  # check if table existence in specified location is true
  if(dbExistsTable(con,db.location)==TRUE){
    return(TRUE)
  }else{
    return(FALSE)
  }
}

psql.exists.boolean("test_table_1","test_schema_1")


问:
Comparison operator with boolean always returning false
I'm trying to understand objects and functions, this is my code:

```<code>function house(roof) {
  this.roof = roof;
  this.roofdescrip = describehouse();
}

function describehouse(){
  var z = this.roof;
  x="The house has a roof.";
  y="The house does not have a roof.";
  if(z===true){return x;}
  else{return y;}

  }

var myhouse = new house(true);

document.write(myhouse.roofdescrip);
</code>```

always returns

```<code>The house does not have a roof.
</code>```

whether I change the parameter to true or false. Why?

答:
The problem is related to the scope. In your case, this inside the describehouse function is actually the window object. If you try to log this.roof inside the function, you will get undefined. undefined is considered faulty and that is the reason you always get the same result.

To make your code work, you need to bind the function to your object and then call the function.

```<code>function house(roof) {
  this.roof = roof;
  this.roofdescrip = describehouse.bind(this);
}

function describehouse(){
  var z = this.roof;
  console.log(this)
  x="The house has a roof.";
  y="The house does not have a roof.";
  if(z===true){return x;}
  else{return y;}

  }

var myhouse = new house(true);

document.write(myhouse.roofdescrip());
</code>```

Here I put another way to do it.

```<code>class House {
  constructor(roof) {
    this.roof = roof
  }

  describeHouse() {
    const verb = this.roof ? "has" : "does not have"
    return `The house ${verb} a roof.`
  }
}

const myHouse = new House(true)
const otherHouse = new House(false)
console.log(myHouse.describeHouse()) // "The house has a roof."
console.log(otherHouse.describeHouse()) // "The house does not have a roof."
</code>```

Body:
I'm trying to understand objects and functions, this is my code:

function house(roof) {
  this.roof = roof;
  this.roofdescrip = describehouse();
}

function describehouse(){
  var z = this.roof;
  x="The house has a roof.";
  y="The house does not have a roof.";
  if(z===true){return x;}
  else{return y;}

  }

var myhouse = new house(true);

document.write(myhouse.roofdescrip);

always returns

The house does not have a roof.

whether I change the parameter to true or false. Why?

Body:
The problem is related to the scope. In your case, this inside the describehouse function is actually the window object. If you try to log this.roof inside the function, you will get undefined. undefined is considered faulty and that is the reason you always get the same result.

To make your code work, you need to bind the function to your object and then call the function.

function house(roof) {
  this.roof = roof;
  this.roofdescrip = describehouse.bind(this);
}

function describehouse(){
  var z = this.roof;
  console.log(this)
  x="The house has a roof.";
  y="The house does not have a roof.";
  if(z===true){return x;}
  else{return y;}

  }

var myhouse = new house(true);

document.write(myhouse.roofdescrip());

Here I put another way to do it.

class House {
  constructor(roof) {
    this.roof = roof
  }

  describeHouse() {
    const verb = this.roof ? "has" : "does not have"
    return `The house ${verb} a roof.`
  }
}

const myHouse = new House(true)
const otherHouse = new House(false)
console.log(myHouse.describeHouse()) // "The house has a roof."
console.log(otherHouse.describeHouse()) // "The house does not have a roof."


问:
template specialization for all iterators of std::map
I have traits class, saying:

```<code>template <class T>
struct KeyValueTraits
{
    typedef typename T::key_t key_t;
    typedef typename T::value_t value_t;
}
</code>```

Now I would like to declare specialization of this traits for all iterators of std::map

```<code>template < typename... Args >
struct KeyValueTraits<typename std::map<Args...>::iterator >
{
    typedef std::map<Args...> target_t;
    typedef typename target_t::key_type key_t;
    typedef typename target_t::mapped_type value_t;
};
</code>```

Compiler raises an error:

error C2764: 'Args': template parameter not used or deducible in partial specialization

So how to declare traits-type for all possible std::map<...>::iterator?

答:
Here's one possible solution (it changes the KeyValueTraits template signature because it doesn't seem possible otherwise).</p>

```<code>template <class T, class = void>
struct KeyValueTraits
{
    typedef typename T::key_t key_t;
    typedef typename T::value_t value_t;
};

template <class MapIter>
struct KeyValueTraits<MapIter,
                      typename std::enable_if<
                         sizeof(std::declval<MapIter>()->first) &&
                         sizeof(std::declval<MapIter>()->second)
                      >::type>
{
    typedef decltype(std::declval<MapIter>()->first) key_t;
    typedef decltype(std::declval<MapIter>()->second) value_t;
};
</code>```

Body:
I have traits class, saying:

template <class T>
struct KeyValueTraits
{
    typedef typename T::key_t key_t;
    typedef typename T::value_t value_t;
}

Now I would like to declare specialization of this traits for all iterators of std::map

template < typename... Args >
struct KeyValueTraits<typename std::map<Args...>::iterator >
{
    typedef std::map<Args...> target_t;
    typedef typename target_t::key_type key_t;
    typedef typename target_t::mapped_type value_t;
};

Compiler raises an error:

error C2764: 'Args': template parameter not used or deducible in partial specialization

So how to declare traits-type for all possible std::map<...>::iterator?

Body:
Here's one possible solution (it changes the KeyValueTraits template signature because it doesn't seem possible otherwise).

template <class T, class = void>
struct KeyValueTraits
{
    typedef typename T::key_t key_t;
    typedef typename T::value_t value_t;
};

template <class MapIter>
struct KeyValueTraits<MapIter,
                      typename std::enable_if<
                         sizeof(std::declval<MapIter>()->first) &&
                         sizeof(std::declval<MapIter>()->second)
                      >::type>
{
    typedef decltype(std::declval<MapIter>()->first) key_t;
    typedef decltype(std::declval<MapIter>()->second) value_t;
};


问:
Titanium Appcelerator Rounded corners on Annotations(Map module)?
Here is my code split into Alloy/JS/Styling
No Matter where I place the borderRadius/borderWidth properties it ignores it

Alloy:

```<code><Label id="image_label"></Label>
</code>```

JS:

```<code>function setAnnotation(location) {

   var annotation = map.createAnnotation({
   title: location.title,
   subtitle: location.latitude + ', ' + location.longitude,
   latitude: location.latitude,
   longitude: location.longitude,
   image: $.image_label.toImage(),
   borderRadius:22, //DOESNT WORK
   borderWidth: 6, //DOESNT WORK

   });

$.map.setAnnotations([annotation]);
}
</code>```

Style:

```<code>//LABEL ANNOTATION
"#image_label": {
color : 'black',
font : {fontSize:'15dp',font:"monospace",fontWeight:"bold"},
height : '30dp',
width : '30dp',
borderRadius:999,   //DOESNT WORK
borderWidth: 99,  //DOESNT WORK
backgroundImage:'https://pbs.twimg.com/profile_images/604644048/sign051.gif'
</code>```

}

答:
Best way would be create a View and a Label and add the borderRadius/borderWidth/backgroundImage to the View, then at the end asssign the view.toImage() to the annotation. Keep in mind that the annotation itself doesn't have the borderRadius/borderWidth property (http://docs.appcelerator.com/platform/latest/#!/api/Modules.Map.Annotation)

```<code>var view = Ti.UI.createView({
  width:30,
  height:30,
  borderRadius:15,
  borderWidth: 3,
  backgroundImage:'https://pbs.twimg.com/profile_images/604644048/sign051.gif'
});
var lbl = Ti.UI.createLabel({
    text:"2"
});
view.add(lbl);

mapView.addAnnotation(
    maps.createAnnotation({
        latitude: 37.368122,
        longitude: -121.913653,
        title: "company",
        image: view.toImage()
    })
)
</code>```

you could also put that into the view of a widget and fill the text/image with a parameter to use the power of Alloy and keep the code free of view-code.

Body:
Here is my code split into Alloy/JS/Styling
No Matter where I place the borderRadius/borderWidth properties it ignores it

Alloy:

JS:

function setAnnotation(location) {

   var annotation = map.createAnnotation({
   title: location.title,
   subtitle: location.latitude + ', ' + location.longitude,
   latitude: location.latitude,
   longitude: location.longitude,
   image: $.image_label.toImage(),
   borderRadius:22, //DOESNT WORK
   borderWidth: 6, //DOESNT WORK

   });

$.map.setAnnotations([annotation]);
}

Style:

//LABEL ANNOTATION
"#image_label": {
color : 'black',
font : {fontSize:'15dp',font:"monospace",fontWeight:"bold"},
height : '30dp',
width : '30dp',
borderRadius:999,   //DOESNT WORK
borderWidth: 99,  //DOESNT WORK
backgroundImage:'https://pbs.twimg.com/profile_images/604644048/sign051.gif'

}

Body:
Best way would be create a View and a Label and add the borderRadius/borderWidth/backgroundImage to the View, then at the end asssign the view.toImage() to the annotation. Keep in mind that the annotation itself doesn't have the borderRadius/borderWidth property (http://docs.appcelerator.com/platform/latest/#!/api/Modules.Map.Annotation)

var view = Ti.UI.createView({
  width:30,
  height:30,
  borderRadius:15,
  borderWidth: 3,
  backgroundImage:'https://pbs.twimg.com/profile_images/604644048/sign051.gif'
});
var lbl = Ti.UI.createLabel({
    text:"2"
});
view.add(lbl);

mapView.addAnnotation(
    maps.createAnnotation({
        latitude: 37.368122,
        longitude: -121.913653,
        title: "company",
        image: view.toImage()
    })
)

you could also put that into the view of a widget and fill the text/image with a parameter to use the power of Alloy and keep the code free of view-code.


问:
C# Generating new id from database on windows forms application
I have to make automatic generate new AccountID  on my load windows form app.

So for example when users start windows form "Add new Account" in textbox for "Account id" I have to show latest value from database. If i have two accounts in database on windows form in textbox value will be three.

My code perfectly work if i have at least one account in database, but when my database is empty i got exception.

This is my code:

```<code>public int GetLatestAccountID()
{
    try
    {
        command.CommandText = "select Max(AccountID)as maxID from Account";
        command.CommandType = CommandType.Text;

        connection.Open();

        OleDbDataReader reader= command.ExecuteReader();

        if (reader.Read())
        {
            int valueID = Convert.ToInt32(reader["maxID"]);
            return valueID + 1;
        }

        return 1;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (connection!= null)
        {
            connection.Close();
        }
    }
}
</code>```

Also I find answer on stackoverflow:

```<code>object aa = DBNull.Value;
int valueID = (aa as int?).GetValueOrDefault();
</code>```

But this line of code works if my database is empty, but when I have one account in the database, it will always show on my windows form in account id textbox value one. I use Microsoft Access 2007 database.

I appreciate any help.

答: Could you use  SELECT COUNT(column_name) FROM table_name; to count number of accounts instead of selecting which one is the biggest?</p>

Body:
I have to make automatic generate new AccountID  on my load windows form app.

So for example when users start windows form "Add new Account" in textbox for "Account id" I have to show latest value from database. If i have two accounts in database on windows form in textbox value will be three.

My code perfectly work if i have at least one account in database, but when my database is empty i got exception.

This is my code:

public int GetLatestAccountID()
{
    try
    {
        command.CommandText = "select Max(AccountID)as maxID from Account";
        command.CommandType = CommandType.Text;

        connection.Open();

        OleDbDataReader reader= command.ExecuteReader();

        if (reader.Read())
        {
            int valueID = Convert.ToInt32(reader["maxID"]);
            return valueID + 1;
        }

        return 1;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (connection!= null)
        {
            connection.Close();
        }
    }
}

Also I find answer on stackoverflow:

object aa = DBNull.Value;
int valueID = (aa as int?).GetValueOrDefault();

But this line of code works if my database is empty, but when I have one account in the database, it will always show on my windows form in account id textbox value one. I use Microsoft Access 2007 database.

I appreciate any help.