问:
Excel VBA "Subscript out of range" Run Error '9'
I have tried to implement the following code so that I can read a cell value and then places this value into another cell on the same Worksheet.

The worksheet has the following name: TestUserGuidance (Has no spaces)
The code is as follows:

```<code>Sub GuideTest()
    Dim dblPower, dblMass, dblRatedSpeed, dblRefLength, dblAwot, dblEngineSpeed, dblRoadSpeed As Double
    Dim dblPMR As Double

    dblPower = Worksheets("TestUserGuidance").Cell("B1").Value
    Worksheets("TestUserGuidance").Cell("E1") = dblPower
End Sub
</code>```

Could anyone please advise where I'm going wrong?

Thanks

答:
I think vba can't find  the TestUserGuidance sheet. If I run the following in the immediate window I get an "Object doesn't support this property or method" error:

```<code>?worksheets(1).cell("A1")
</code>```

If I run this, I get the error you mention "Subscript out of range":

```<code>?worksheets("non-existent sheet").cell("A1")
</code>```

This suggests to me that the active workbook is incorrect since you would have gotten the other error if vba was able to find the worksheet. Can you try adding ThisWorkbook (and also use range)?

```<code>dblPower = ThisWorkbook.Worksheets("TestUserGuidance").Range("B1").Value
ThisWorkbook.Worksheets("TestUserGuidance").Range("E1") = dblPower
</code>```

Another option would be to rename your worksheet:

Then you won't have to worry about the active workbook (and also get intellisence):

```<code>shtTestUserGuidance.Range("E1") = shtTestUserGuidance.Range("B1")
</code>```

Also, I would suggest you make all the corrections suggested by others. You will likely have other issues moving forward otherwise.

Lastly, if the worksheet is like a template and the structure won't change, you'd be better off just using a formula (i.e. E1's formula: =B1). Even if there's conditional logic, it might be easier to maintain as a formula rather than vba code.

Here are some troubleshooting steps:

Toggle a break point on the line where dblPower is set by clicking on the grey area to the left:

Also open the Immediate window if it's not already there by pressing ctrl+g:

When you run the code, it should pause at the break point. Now you can inspect what's in scope. Try typing the following into the Immediate window and press enter:

```<code>?Worksheets("TestUserGuidance").Name
</code>```

or

```<code>?ActiveWorkbook.Name
</code>```

Note that you can also step through the code line by line by pressing F8 while the cursor is somewhere within the subroutine. Bottom line is that you may need to examine the code line by line in order to figure this out.

Body:
I have tried to implement the following code so that I can read a cell value and then places this value into another cell on the same Worksheet.

The worksheet has the following name: TestUserGuidance (Has no spaces)
The code is as follows:

Sub GuideTest()
    Dim dblPower, dblMass, dblRatedSpeed, dblRefLength, dblAwot, dblEngineSpeed, dblRoadSpeed As Double
    Dim dblPMR As Double

    dblPower = Worksheets("TestUserGuidance").Cell("B1").Value
    Worksheets("TestUserGuidance").Cell("E1") = dblPower
End Sub

Could anyone please advise where I'm going wrong?

Thanks

Body:
I think vba can't find  the TestUserGuidance sheet. If I run the following in the immediate window I get an "Object doesn't support this property or method" error:

?worksheets(1).cell("A1")

If I run this, I get the error you mention "Subscript out of range":

?worksheets("non-existent sheet").cell("A1")

This suggests to me that the active workbook is incorrect since you would have gotten the other error if vba was able to find the worksheet. Can you try adding ThisWorkbook (and also use range)?

dblPower = ThisWorkbook.Worksheets("TestUserGuidance").Range("B1").Value
ThisWorkbook.Worksheets("TestUserGuidance").Range("E1") = dblPower

Another option would be to rename your worksheet:

Then you won't have to worry about the active workbook (and also get intellisence):

shtTestUserGuidance.Range("E1") = shtTestUserGuidance.Range("B1")

Also, I would suggest you make all the corrections suggested by others. You will likely have other issues moving forward otherwise.

Lastly, if the worksheet is like a template and the structure won't change, you'd be better off just using a formula (i.e. E1's formula: =B1). Even if there's conditional logic, it might be easier to maintain as a formula rather than vba code.

Here are some troubleshooting steps:

Toggle a break point on the line where dblPower is set by clicking on the grey area to the left:

Also open the Immediate window if it's not already there by pressing ctrl+g:

When you run the code, it should pause at the break point. Now you can inspect what's in scope. Try typing the following into the Immediate window and press enter:

?Worksheets("TestUserGuidance").Name

or

?ActiveWorkbook.Name

Note that you can also step through the code line by line by pressing F8 while the cursor is somewhere within the subroutine. Bottom line is that you may need to examine the code line by line in order to figure this out.


来源: stackexchange

问:
Distinguish between validation exception and Unhandled error in stored procedure
I had written many stored procedures for my application. Some stored procedures return validation exceptions as per project requirement, while in some cases stored procedure return unhandled fatal errors such as

"Foreign key reference error", "expects parameter which was not supplied" etc.

Now I need to distinguish between those errors in my C# code. In case of unhandled fatal errors, I need to insert error log in database.

Any suggestion on how to distinguish between these two types.

NOTE : I am returning validation exceptions using RAISERROR statement like

RAISERROR(@ErrorMsg,16,1)

UPDATE 1:

I guess everyone falsely interprets my actual issue.
I may get either user defined validation exception (returned by RAISERROR stmt) OR fatal error from query execution within SP. I need to distinguish between these two types at my C# code. Both exceptions are caught in

```<code>catch (SqlException ex)
</code>```

block. After some research, I found that ex.Number is 50000 in case of user defined validation exception and in other cases, it is different.

I am thinking of writing condition on that. If any cleaner approach that this, please suggest.

答:
Use Try Catch Block in C# code and remove your RAISERROR(@ErrorMsg,16,1) from stored procedures.

You can get exact error message inside catch block and validate it and write log.

ContentLicense: CC BY-SA 3.0

Body:
I had written many stored procedures for my application. Some stored procedures return validation exceptions as per project requirement, while in some cases stored procedure return unhandled fatal errors such as

"Foreign key reference error", "expects parameter which was not supplied" etc.

Now I need to distinguish between those errors in my C# code. In case of unhandled fatal errors, I need to insert error log in database.

Any suggestion on how to distinguish between these two types.

NOTE : I am returning validation exceptions using RAISERROR statement like

RAISERROR(@ErrorMsg,16,1)

UPDATE 1:

I guess everyone falsely interprets my actual issue.
I may get either user defined validation exception (returned by RAISERROR stmt) OR fatal error from query execution within SP. I need to distinguish between these two types at my C# code. Both exceptions are caught in

catch (SqlException ex)

block. After some research, I found that ex.Number is 50000 in case of user defined validation exception and in other cases, it is different.

I am thinking of writing condition on that. If any cleaner approach that this, please suggest.


问:
find last 7 days mail from gmail to csv in python
Facing issue while extracting last 7 days email from gmail to csv by using IMAP in python. Below is the code i have built using help from blogs.

```<code># -*- coding: utf-8 -*-
"""
Created on Wed Dec  6 18:34:56 2017

@author: ravi
"""

import email, getpass, imaplib, os , datetime , csv

detach_dir = '.' # directory where to save attachments (default: current)
user = input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")

# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("inbox") # here you a can choose a mail box like INBOX instead
m.list()# to get all the mailboxes

date = (datetime.date.today() - datetime.timedelta(7)).strftime("%d-%b-%Y")
result, data = m.search(None, '(SENTSINCE {date})'.format(date=date))
ids = data[0]
id_list = ids.split()

final_list = [ ]

for emailid in id_list:
    temp_dict = { }
    result, data = m.fetch(id_list, "(RFC822)")# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
    email_body = data[0][1] # getting the mail content
    mail = email.message_from_bytes(email_body) # parsing the mail content to get a mail object
    temp_dict['Sender'] = mail["From"]
    temp_dict['Subject'] = mail["Subject"]
    temp_dict['Date'] = mail["Date"]

    print ("["+mail["From"]+"] :" + mail["Subject"] +mail["Date"])

    print (temp_dict)
    final_list.append(temp_dict)

#exporting the values as .csv
with open('CSV_NAME.csv', 'w', encoding='utf-8', newline = '') as csvfile:
    fieldnames = ['Sender','Subject','Date']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ',')
    writer.writeheader()
    for val in final_list:
        writer.writerow(val)
</code>```

In this code the data is of the type list which is not accepting the type byte. How to resolve this ?

UPDATE1:-

Tried a new piece of code. Understood what the problem is anyway to solve it?

```<code># -*- coding: utf-8 -*-
"""
Created on Tue Dec  5 19:36:33 2017

@author: ravi
"""

import email, getpass, imaplib, os , datetime , csv

detach_dir = '.' # directory where to save attachments (default: current)
user = input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")

# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("inbox") # here you a can choose a mail box like INBOX instead
m.list()# to get all the mailboxes

date = (datetime.date.today() - datetime.timedelta(7)).strftime("%d-%b-%Y")
resp, items = m.uid('search', None, '(SENTSINCE {date})'.format(date=date)) # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
items = items[0].split() # getting the mails id

final_list = [ ]

for emailid in items:
    temp_dict = { }
    resp, data = m.uid('fetch',items,'(RFC822)')# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
    email_body = data[0][1] # getting the mail content
    mail = email.message_from_bytes(email_body) # parsing the mail content to get a mail object
    temp_dict['Sender'] = mail["From"]
    temp_dict['Subject'] = mail["Subject"]
    temp_dict['Date'] = mail["Date"]

    print ("["+mail["From"]+"] :" + mail["Subject"] +mail["Date"])

    print (temp_dict)
    final_list.append(temp_dict)

#exporting the values as .csv
with open('CSV_NAME.csv', 'w', encoding='utf-8', newline = '') as csvfile:
    fieldnames = ['Sender','Subject','Date']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ',')
    writer.writeheader()
    for val in final_list:
        writer.writerow(val)
</code>```

I get the error:-

```<code>---> 31     resp, data = m.uid('fetch',items,'(RFC822)')# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc

\Anaconda3\lib\imaplib.py in _command(self, name, *args)
    943             if isinstance(arg, str):
    944                 arg = bytes(arg, self._encoding)
--> 945             data = data + b' ' + arg
    946
    947         literal = self.literal
TypeError: can't concat bytes to list
</code>```

Anyway to solve it

答:
m.uid('fetch',items,'(RFC822)')

Items cannot be a list: the imaplib commands only take strings or bytes, but items is a list of UIDs.

You'll need to massage it into a string or bytes.

I don't remember if the list results is a list of bytes or string objects, but you can get an IMAP compliant fetch list by comma separating the values.  One of these should work for you:

```<code>uids = ','.join(items)
uids = b','.join(items)
</code>```

Body:
Facing issue while extracting last 7 days email from gmail to csv by using IMAP in python. Below is the code i have built using help from blogs.

# -*- coding: utf-8 -*-
"""
Created on Wed Dec  6 18:34:56 2017

@author: ravi
"""

import email, getpass, imaplib, os , datetime , csv

detach_dir = '.' # directory where to save attachments (default: current)
user = input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")

# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("inbox") # here you a can choose a mail box like INBOX instead
m.list()# to get all the mailboxes

date = (datetime.date.today() - datetime.timedelta(7)).strftime("%d-%b-%Y")
result, data = m.search(None, '(SENTSINCE {date})'.format(date=date))
ids = data[0]
id_list = ids.split()

final_list = [ ]

for emailid in id_list:
    temp_dict = { }
    result, data = m.fetch(id_list, "(RFC822)")# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
    email_body = data[0][1] # getting the mail content
    mail = email.message_from_bytes(email_body) # parsing the mail content to get a mail object
    temp_dict['Sender'] = mail["From"]
    temp_dict['Subject'] = mail["Subject"]
    temp_dict['Date'] = mail["Date"]

    print ("["+mail["From"]+"] :" + mail["Subject"] +mail["Date"])

    print (temp_dict)
    final_list.append(temp_dict)

#exporting the values as .csv
with open('CSV_NAME.csv', 'w', encoding='utf-8', newline = '') as csvfile:
    fieldnames = ['Sender','Subject','Date']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ',')
    writer.writeheader()
    for val in final_list:
        writer.writerow(val)

In this code the data is of the type list which is not accepting the type byte. How to resolve this ?

UPDATE1:-

Tried a new piece of code. Understood what the problem is anyway to solve it?

# -*- coding: utf-8 -*-
"""
Created on Tue Dec  5 19:36:33 2017

@author: ravi
"""

import email, getpass, imaplib, os , datetime , csv

detach_dir = '.' # directory where to save attachments (default: current)
user = input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")

# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("inbox") # here you a can choose a mail box like INBOX instead
m.list()# to get all the mailboxes

date = (datetime.date.today() - datetime.timedelta(7)).strftime("%d-%b-%Y")
resp, items = m.uid('search', None, '(SENTSINCE {date})'.format(date=date)) # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
items = items[0].split() # getting the mails id

final_list = [ ]

for emailid in items:
    temp_dict = { }
    resp, data = m.uid('fetch',items,'(RFC822)')# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
    email_body = data[0][1] # getting the mail content
    mail = email.message_from_bytes(email_body) # parsing the mail content to get a mail object
    temp_dict['Sender'] = mail["From"]
    temp_dict['Subject'] = mail["Subject"]
    temp_dict['Date'] = mail["Date"]

    print ("["+mail["From"]+"] :" + mail["Subject"] +mail["Date"])

    print (temp_dict)
    final_list.append(temp_dict)

#exporting the values as .csv
with open('CSV_NAME.csv', 'w', encoding='utf-8', newline = '') as csvfile:
    fieldnames = ['Sender','Subject','Date']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ',')
    writer.writeheader()
    for val in final_list:
        writer.writerow(val)

I get the error:-

---> 31     resp, data = m.uid('fetch',items,'(RFC822)')# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc

\Anaconda3\lib\imaplib.py in _command(self, name, *args)
    943             if isinstance(arg, str):
    944                 arg = bytes(arg, self._encoding)
--> 945             data = data + b' ' + arg
    946
    947         literal = self.literal
TypeError: can't concat bytes to list

Anyway to solve it

Body:
m.uid('fetch',items,'(RFC822)')

Items cannot be a list: the imaplib commands only take strings or bytes, but items is a list of UIDs.

You'll need to massage it into a string or bytes.

I don't remember if the list results is a list of bytes or string objects, but you can get an IMAP compliant fetch list by comma separating the values.  One of these should work for you:

uids = ','.join(items)
uids = b','.join(items)


问:
How to set gradle home while importing existing project in Android studio
How to set gradle home while importing existing project in Android studio. While trying to import I need to set up this path.

答:
I've stumble across this question, trying to build an Ionic + Cordova app using Gradle from Android Studio installation, rather that installing Gradle separately.

On Centos, the Gradle binary was here:  /home/YOURUSERNAME/.gradle/wrapper/dists/gradle-VERSION-all/CUSTOM_HASH/gradle-VERSION/bin

So, I've added export PATH=/home/maxim/.gradle/wrapper/dists/gradle-4.1-all/bzyivzo6n839fup2jbap0tjew/gradle-4.1/bin:$PATH to my ~/.bashrc and ionic cordova run android command worked just fine.


问:
discord.py client.send_message gets ignored without sending an error

I'm trying to make a function for my bot to save quotes. Basically by calling the command quote with a user and then the quote to be saved, example:

/quote @test I am the best

The program manages to save the quotes no problem, but when it encounters either a client.send_message() or client.say() (I've tried both) it seems to completly ignore them and move on with the rest of the code without raising an error or sending a message. I've tried putting both a send_message a say with only a string each in the beginning of the command, but they still don't send anything (while other commands have no problem at all).

The command:

```<code>@bot.command()
async def quote(user : discord.Member, *words):#gets the user and then makes a list of all other words

    print(user.id)#a string of numbers
    print(testserver.get_member(user.id) == user)#evaluates to True, this is the reason i use user.id, so that its possible to create a member some other time.

    quoteshelf = shelve.open('quotes')
    quote = ''
    for i in range(len(words)):
        quote = quote + ' ' + words[i]

    bot.say('hi')#tests which have not been working
    bot.send_message(testserver, 'bye')

    if user.id in quoteshelf.keys():#checks if the user already exists in the file
        tempshelf = quoteshelf[user.id]#it isnt possible to append directly into the shelf (or at least it seems so)
        tempshelf.append({quote : getdate()})
        quoteshelf[user.id] = tempshelf

        bot.say('work pls')
        bot.send_message(user.server, 'Added: ' + ' to')
        print(1)
        print(quoteshelf[user.id])

    else:#if it isnt in the file then it will create a new one
        quoteshelf[user.id] = [{quote : getdate()}]
        print(2)
        print(quoteshelf[user.id])
        print(user.server)
        print(user.server == testserver)
        bot.say('ok sure')
        bot.send_message(user.server, 'Created directory for and added ')
        print(2)
    quoteshelf.close()
</code>```

The prints are mostly for debugging (I figured I'd keep them in since they might help understand what this command is doing.

I expect this to save the quote with shelf and then send a short confirmation to the channel but well, the second part I can't seem to make work.

So yeah, I appreciate any pointers in the right direction and just tell me if you need to know anything more. Thanks!

(Edit)
A cleaned up version:

```<code>@bot.command()
async def quote(user : discord.Member, *words):
    quoteshelf = shelve.open('quotes')
    quote = ''
    for i in range(len(words)):
        quote = quote + ' ' + words[i]

    if user.id in quoteshelf.keys():
        tempshelf = quoteshelf[user.id]
        tempshelf.append({quote : getdate()})
        quoteshelf[user.id] = tempshelf
        bot.say(user.server, 'Added: ' + quote + ' to ' + user.name)

    else:
        quoteshelf[user.id] = [{quote : getdate()}]
        bot.say('Created directory for ' + user.name + ' and added ' + quote)

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

答: Boy do i feel stupid atm, I just realised that I've forgotten await before every single one of them. So yeah, if anyone has a similar problem, make sure you didn't forget await...</p>

Body:
I'm trying to make a function for my bot to save quotes. Basically by calling the command quote with a user and then the quote to be saved, example:

/quote @test I am the best

The program manages to save the quotes no problem, but when it encounters either a client.send_message() or client.say() (I've tried both) it seems to completly ignore them and move on with the rest of the code without raising an error or sending a message. I've tried putting both a send_message a say with only a string each in the beginning of the command, but they still don't send anything (while other commands have no problem at all).

The command:

@bot.command()
async def quote(user : discord.Member, *words):#gets the user and then makes a list of all other words

    print(user.id)#a string of numbers
    print(testserver.get_member(user.id) == user)#evaluates to True, this is the reason i use user.id, so that its possible to create a member some other time.

    quoteshelf = shelve.open('quotes')
    quote = ''
    for i in range(len(words)):
        quote = quote + ' ' + words[i]

    bot.say('hi')#tests which have not been working
    bot.send_message(testserver, 'bye')

    if user.id in quoteshelf.keys():#checks if the user already exists in the file
        tempshelf = quoteshelf[user.id]#it isnt possible to append directly into the shelf (or at least it seems so)
        tempshelf.append({quote : getdate()})
        quoteshelf[user.id] = tempshelf

        bot.say('work pls')
        bot.send_message(user.server, 'Added: ' + ' to')
        print(1)
        print(quoteshelf[user.id])

    else:#if it isnt in the file then it will create a new one
        quoteshelf[user.id] = [{quote : getdate()}]
        print(2)
        print(quoteshelf[user.id])
        print(user.server)
        print(user.server == testserver)
        bot.say('ok sure')
        bot.send_message(user.server, 'Created directory for and added ')
        print(2)
    quoteshelf.close()

The prints are mostly for debugging (I figured I'd keep them in since they might help understand what this command is doing.

I expect this to save the quote with shelf and then send a short confirmation to the channel but well, the second part I can't seem to make work.

So yeah, I appreciate any pointers in the right direction and just tell me if you need to know anything more. Thanks!

(Edit)
A cleaned up version:

@bot.command()
async def quote(user : discord.Member, *words):
    quoteshelf = shelve.open('quotes')
    quote = ''
    for i in range(len(words)):
        quote = quote + ' ' + words[i]

    if user.id in quoteshelf.keys():
        tempshelf = quoteshelf[user.id]
        tempshelf.append({quote : getdate()})
        quoteshelf[user.id] = tempshelf
        bot.say(user.server, 'Added: ' + quote + ' to ' + user.name)

    else:
        quoteshelf[user.id] = [{quote : getdate()}]
        bot.say('Created directory for ' + user.name + ' and added ' + quote)

    quoteshelf.close()


问:
C++ - constant variable, is it a correct term?
At the end of the artile here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/

It mentions the following sentence:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

Is "constant variables" a correct term to use? Aren't constants different from variables?

Thanks.

答:
Constants in C++ are a special kind of variable. I understand it may sound contradictory for the common sense, but that's how it is in C++.

```<code>int var1 = 1;
int const var2 = 2;
</code>```

The difference between them is only the const keyword, which tells the compiler that the value of var2 must not be changed once it is created:

```<code>var1 = 2; // fine
var2 = 1; // compilation error!
</code>```

This simple rule also causes further constraints to be enforced for const variables, e.g. you can't create a non-const reference to a const variable (as otherwise you could still change its value via that reference). Neither you are allowed to pass var2 to a function with a signature f(int& i), for the same reason. However, you can create const references to them, use their values etc. just as with any "normal" variable. So by and large they are like any other variable.

ContentLicense: CC BY-SA 2.5

Body:
Constants in C++ are a special kind of variable. I understand it may sound contradictory for the common sense, but that's how it is in C++.

int var1 = 1;
int const var2 = 2;

The difference between them is only the const keyword, which tells the compiler that the value of var2 must not be changed once it is created:

var1 = 2; // fine
var2 = 1; // compilation error!

This simple rule also causes further constraints to be enforced for const variables, e.g. you can't create a non-const reference to a const variable (as otherwise you could still change its value via that reference). Neither you are allowed to pass var2 to a function with a signature f(int& i), for the same reason. However, you can create const references to them, use their values etc. just as with any "normal" variable. So by and large they are like any other variable.


问:
Invalid JSON Response in Datatable Codeigniter
I need an expert to fix this . This is my controller that load JSON .

```<code>foreach ($result->result() as $row){
    $customer = $row->customer_name;
    $ipull = $row->ip;
    if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true){
        $PING = $this->routerosapi->comm("/ping", array(
            "address" => $ipull,
            "count" => "2"
        ));
        if( $PING['0']['packet-loss'] == 0){
            $status = "Online";
        } else {
            $status = "Offline";
        }
    } else {
        $this->session->set_flashdata('Connect_False','Failed To get');
        redirect('tmikrotik/router_list');
    }
    $data = array(
        'customer' => $customer,
        'address' => $ipull,
        'status' => $status
    );
    print json_encode($data);
}
</code>```

And this is JSON response:

```<code>{"customer":"Trakindo Utama","address":"192.168.1.3","status":"Online"}{"customer":"Adira Finance","address":"192.168.1.10","status":"Offline"}{"customer":"Mandala Finance","address":"192.168.1.50","status":"Online"}
</code>```

The problem is, when I load it into my data table, show popup invalid JSON response. This is my jQuery code

$(function () {
    var table = $("#cpe-status").DataTable({
        fixedColumns: true,
        fixedHeader: true,
        "pageLength": 10,
        "paging": true,
        "ajax": {
            url: "./cpe",
            type: "GET",
            dataSrc: ""
        },
        "scrollX": true,
        "aoColumns": [
            {"data": "customer", "title": "Host"},
            {"data": "address", "title": "Customer Name"},
            {"data": "status", "title": "Registered"}
            // {"data": "status", "title": "Status"}
        ]
    });
    // setInterval(function () {
    //     table.ajax.reload();
    // }, 10000);
})
```

答:
You are printing each result inside the loop. You should print the result as 1 array. </p>

```<code>/* ============= Declare the data outside the loop ============= */
$data = array();

foreach ($result->result() as $row){
    $customer = $row->customer_name;
    $ipull = $row->ip;
    if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true) {
      $PING = $this->routerosapi->comm("/ping", array(
        "address" => $ipull,
        "count" => "2"
      ));
      if( $PING['0']['packet-loss'] == 0){
        $status = "Online";
      } else {
         $status = "Offline";
      }
    } else {
      $this->session->set_flashdata('Connect_False','Failed To get');
      redirect('tmikrotik/router_list');
    }

    /* ============= Push each result on an array ============= */
    $data[] = array(
      'customer' => $customer,
      'address' => $ipull,
      'status' => $status
    );

  }

/* =============  print result (outside the loop ) ============= */
print json_encode($data);
</code>```

Body:
I need an expert to fix this . This is my controller that load JSON .

foreach ($result->result() as $row){
    $customer = $row->customer_name;
    $ipull = $row->ip;
    if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true){
        $PING = $this->routerosapi->comm("/ping", array(
            "address" => $ipull,
            "count" => "2"
        ));
        if( $PING['0']['packet-loss'] == 0){
            $status = "Online";
        } else {
            $status = "Offline";
        }
    } else {
        $this->session->set_flashdata('Connect_False','Failed To get');
        redirect('tmikrotik/router_list');
    }
    $data = array(
        'customer' => $customer,
        'address' => $ipull,
        'status' => $status
    );
    print json_encode($data);
}

And this is JSON response:

{"customer":"Trakindo Utama","address":"192.168.1.3","status":"Online"}{"customer":"Adira Finance","address":"192.168.1.10","status":"Offline"}{"customer":"Mandala Finance","address":"192.168.1.50","status":"Online"}

The problem is, when I load it into my data table, show popup invalid JSON response. This is my jQuery code

$(function () {
    var table = $("#cpe-status").DataTable({
        fixedColumns: true,
        fixedHeader: true,
        "pageLength": 10,
        "paging": true,
        "ajax": {
            url: "./cpe",
            type: "GET",
            dataSrc: ""
        },
        "scrollX": true,
        "aoColumns": [
            {"data": "customer", "title": "Host"},
            {"data": "address", "title": "Customer Name"},
            {"data": "status", "title": "Registered"}
            // {"data": "status", "title": "Status"}
        ]
    });
    // setInterval(function () {
    //     table.ajax.reload();
    // }, 10000);
})

Body:
You are printing each result inside the loop. You should print the result as 1 array.

/* ============= Declare the data outside the loop ============= */
$data = array();

foreach ($result->result() as $row){
    $customer = $row->customer_name;
    $ipull = $row->ip;
    if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true) {
      $PING = $this->routerosapi->comm("/ping", array(
        "address" => $ipull,
        "count" => "2"
      ));
      if( $PING['0']['packet-loss'] == 0){
        $status = "Online";
      } else {
         $status = "Offline";
      }
    } else {
      $this->session->set_flashdata('Connect_False','Failed To get');
      redirect('tmikrotik/router_list');
    }

    /* ============= Push each result on an array ============= */
    $data[] = array(
      'customer' => $customer,
      'address' => $ipull,
      'status' => $status
    );

  }

/* =============  print result (outside the loop ) ============= */
print json_encode($data);


问:
Get 'Can't resolve all parameters' when I provide the Interceptor
I am trying to implement HttpInterceptor.
When I add it to @NgModule, I get the following error in Chrome:

```<code>Uncaught Error: Can't resolve all parameters for JwtInterceptor: (?, ?).
    at syntaxError (compiler.js:466)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15547)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15382)
</code>```

Spent much time on googling, don’t have an idea what to undertake…

Here is how I provide the Interceptor in AppModule:

```<code>...
providers: [
   {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true
   }
],
...
</code>```

Here is the Interceptor itself, nothing fancy:

```<code>export class JwtInterceptor implements HttpInterceptor {
   constructor(private inj: Injector, private logger: Logger) {
      this.logger.l(true)('Interceptor >>');
   }

   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      this.logger.l(true)('interceptor >>');

      const auth = this.inj.get(AuthService);

      // add token to the request:
      const authReq = req.clone({
         setHeaders: {
            Authorization: `Bearer ${auth.getToken()}`
         }
      });

      // return next.handle(authReq);
      return next.handle(authReq).do((event: HttpEvent<any>) => {
         if (event instanceof HttpResponse) {
            // todo: get refreshed token if it exists:
         }
      }, (err: any) => {
         if (err instanceof HttpErrorResponse) {
            if (err.status === 401) {
               auth.collectFailedRequest(authReq);
               // todo: redirect to the login route or show a modal
            }
         }
      });
   }
}
</code>```

答: My bad, I forgot to add @Injectable() to my interceptor class.

Body:
I am trying to implement HttpInterceptor.
When I add it to @NgModule, I get the following error in Chrome:

Uncaught Error: Can't resolve all parameters for JwtInterceptor: (?, ?).
    at syntaxError (compiler.js:466)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15547)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15382)

Spent much time on googling, don’t have an idea what to undertake…

Here is how I provide the Interceptor in AppModule:

...
providers: [
   {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true
   }
],
...

Here is the Interceptor itself, nothing fancy:

export class JwtInterceptor implements HttpInterceptor {
   constructor(private inj: Injector, private logger: Logger) {
      this.logger.l(true)('Interceptor >>');
   }

   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      this.logger.l(true)('interceptor >>');

      const auth = this.inj.get(AuthService);

      // add token to the request:
      const authReq = req.clone({
         setHeaders: {
            Authorization: `Bearer ${auth.getToken()}`
         }
      });

      // return next.handle(authReq);
      return next.handle(authReq).do((event: HttpEvent<any>) => {
         if (event instanceof HttpResponse) {
            // todo: get refreshed token if it exists:
         }
      }, (err: any) => {
         if (err instanceof HttpErrorResponse) {
            if (err.status === 401) {
               auth.collectFailedRequest(authReq);
               // todo: redirect to the login route or show a modal
            }
         }
      });
   }
}

ContentLicense: CC BY-SA 4.0


问:
React Router 4 <Link> tag updates URL but component is not being rendered to the page
I'm trying to set up login functionality for my react app. Once the user lands on the Login page it has a button on the bottom saying "Sign up". When I click on that link it updates the URL properly and says "/register" in the URL but the Register Component is not rendering. In more traditional routing I would set up a route config that would dictate where all the routes go but from my understanding react router 4 is moving away from that. From reading the docs and some examples I figured simply putting
    Route path="/register" component={Register}
would be enough to tell the Link tag what component to render but that does not seem to be the case. I am using "react-router": "^4.2.0"

Login.js

```<code>import React from 'react';
import LoginForm from '../components/LoginForm';

const Login = () => (
  <div>
    <LoginForm></LoginForm>
  </div>
);

export default Login;
</code>```

LoginForm.js

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { Link, Route } from 'react-router-dom';
import Register from "../pages/Register";

class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: ''
    }
  }

  onSubmit(e) {
    e.preventDefault();

    this.setState({
      error: 'Something went wrong.'
    })
  }

  render() {
    return (
      <form>
        { this.state.error ? <p>{this.state.error}</p> : undefined }
        <TextField type="email" name="email" hintText="Email" fullWidth={true} />
        <TextField type="password" name="password" hintText="Password" fullWidth={true} />
        <RaisedButton label="Login" primary={true} style={buttonStyles} onClick={this.onSubmit.bind(this)} />
        <p style={text}>No account?<Link to="/register"> Sign up</Link></p>

        <Route path="/register" component={Register}></Route>
      </form>
    )
  }
}

export default LoginForm;
</code>```

Register.js

```<code>import React from 'react';
import RegisterForm from '../components/RegisterForm';

const Register = () => (
    <div>
        <RegisterForm></RegisterForm>
    </div>
);

export default Register;
</code>```

RegisterForm.js

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { Link } from 'react-router-dom';

class RegisterForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: ''
        }
    }

    onSubmit(e) {
        e.preventDefault();

        this.setState({
            error: 'Something went wrong.'
        })
    }

    render() {
        return (
            <form>
                { this.state.error ? <p>{this.state.error}</p> : undefined }
                <TextField type="name" name="name" hintText="Name" fullWidth={true} />
                <TextField type="email" name="email" hintText="Email" fullWidth={true} />
                <TextField type="password" name="password" hintText="Password" fullWidth={true} />
                <RaisedButton label="Register" primary={true} onClick={this.onSubmit.bind(this)} />
            </form>
        )
    }
}

export default RegisterForm;
</code>```

答:
Turns out that route tag needed to be inside of my main navigation component and not inside of the LoginForm.js component. I had not included it in my main navigation since you can't get to the register page from the main navigation so why would it need to be declared there?? I thought I would need to dynamically create it by adding it to my LoginForm.js component.</p>

```<code><Route path="/register" component={Register} />
</code>```

Body:
I'm trying to set up login functionality for my react app. Once the user lands on the Login page it has a button on the bottom saying "Sign up". When I click on that link it updates the URL properly and says "/register" in the URL but the Register Component is not rendering. In more traditional routing I would set up a route config that would dictate where all the routes go but from my understanding react router 4 is moving away from that. From reading the docs and some examples I figured simply putting
    Route path="/register" component={Register}
would be enough to tell the Link tag what component to render but that does not seem to be the case. I am using "react-router": "^4.2.0"

Login.js

import React from 'react';
import LoginForm from '../components/LoginForm';

const Login = () => (

    <LoginForm></LoginForm>

);

export default Login;

LoginForm.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { Link, Route } from 'react-router-dom';
import Register from "../pages/Register";

class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: ''
    }
  }

  onSubmit(e) {
    e.preventDefault();

    this.setState({
      error: 'Something went wrong.'
    })
  }

  render() {
    return (
      <form>
        { this.state.error ?
{this.state.error}
 : undefined }
        <TextField type="email" name="email" hintText="Email" fullWidth={true} />
        <TextField type="password" name="password" hintText="Password" fullWidth={true} />
        <RaisedButton label="Login" primary={true} style={buttonStyles} onClick={this.onSubmit.bind(this)} />

No account?<Link to="/register"> Sign up</Link>

        <Route path="/register" component={Register}></Route>
      </form>
    )
  }
}

export default LoginForm;

Register.js

import React from 'react';
import RegisterForm from '../components/RegisterForm';

const Register = () => (

        <RegisterForm></RegisterForm>

);

export default Register;

RegisterForm.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { Link } from 'react-router-dom';

class RegisterForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: ''
        }
    }

    onSubmit(e) {
        e.preventDefault();

        this.setState({
            error: 'Something went wrong.'
        })
    }

    render() {
        return (
            <form>
                { this.state.error ?
{this.state.error}
 : undefined }
                <TextField type="name" name="name" hintText="Name" fullWidth={true} />
                <TextField type="email" name="email" hintText="Email" fullWidth={true} />
                <TextField type="password" name="password" hintText="Password" fullWidth={true} />
                <RaisedButton label="Register" primary={true} onClick={this.onSubmit.bind(this)} />
            </form>
        )
    }
}

export default RegisterForm;

Body:
Turns out that route tag needed to be inside of my main navigation component and not inside of the LoginForm.js component. I had not included it in my main navigation since you can't get to the register page from the main navigation so why would it need to be declared there?? I thought I would need to dynamically create it by adding it to my LoginForm.js component.

<Route path="/register" component={Register} />


问:
Java generics - compile error on method parameter and method return type
Say I've got two interfaces:

```<code>public interface IObjectOne<T>
{
    List<T> digest(final List<T> myList);
}

public interface IObjectTwo<T>
{
    List<T> create();
}
</code>```

And an object which manages concrete implementations of these two interfaces, which must work over the same type.

```<code>public class Entity<T>
{
  private IObjectOne<T> objectOne;
  private IObjectTwo<T> objectTwo;

  ... setters

  public IObjectOne<T> getObjectOne() {
     return objectOne;
  }

  public IObjectTwo<T> getObjectTwo() {
     return objectTwo;
  }
}
</code>```

These Entitys are stored in a Map, and I retrive one of them by a key:

```<code>final Entity<?> entity = entities.get(key);
</code>```

Why cannot I do that?

```<code>entity.getObjectOne().digest(entity.getObjectTwo().create());
</code>```

答:
To do this, you need to do your operation in a method with a type variable:

```<code><T> void doSomething(Entity<T> entity) {
  entity.getObjectOne().digest(entity.getObjectTwo().create());
}
</code>```

You can invoke this even for an Entity<?>, because that wildcard has some type, you just don't know it.

```<code>final Entity<?> entity = entities.get(key);
doSomething(entity);
</code>```

Body:
Say I've got two interfaces:

public interface IObjectOne<T>
{
    List<T> digest(final List<T> myList);
}

public interface IObjectTwo<T>
{
    List<T> create();
}

And an object which manages concrete implementations of these two interfaces, which must work over the same type.

public class Entity<T>
{
  private IObjectOne<T> objectOne;
  private IObjectTwo<T> objectTwo;

  ... setters

  public IObjectOne<T> getObjectOne() {
     return objectOne;
  }

  public IObjectTwo<T> getObjectTwo() {
     return objectTwo;
  }
}

These Entitys are stored in a Map, and I retrive one of them by a key:

final Entity<?> entity = entities.get(key);

Why cannot I do that?

entity.getObjectOne().digest(entity.getObjectTwo().create());

Body:
To do this, you need to do your operation in a method with a type variable:

<T> void doSomething(Entity<T> entity) {
  entity.getObjectOne().digest(entity.getObjectTwo().create());
}

You can invoke this even for an Entity<?>, because that wildcard has some type, you just don't know it.

final Entity<?> entity = entities.get(key);
doSomething(entity);


问:
Delimiters in MySQL
I often see people are using Delimiters. I tried myself to find out what are delimiters and what is their purpose. After 20 minutes of googling, I was not able to find an answer which satisfies me. So, my question is now: What are delimiters and when should I use them?</p>

答:
You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement
we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.

Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.

DELIMITER isn't really a MySQL language command, it's a client command.

Example

```<code>DELIMITER $$

/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$

/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN

    SELECT COUNT(*) INTO the_count FROM employees where department=the_department;

END$$

/*DELIMITER is set to it's default*/
DELIMITER ;
</code>```

Title: Delimiters in MySQL

Body:
You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement
we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.

Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.

DELIMITER isn't really a MySQL language command, it's a client command.

Example

DELIMITER $$

/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$

/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN

    SELECT COUNT(*) INTO the_count FROM employees where department=the_department;

END$$

/*DELIMITER is set to it's default*/
DELIMITER ;


问:
C++ - enum vs. const vs. #define
At the end of the article here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/, it mentions the following:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

How is the bold sentence above achieved?

Thanks.

答:
At least for Visual Studio 2008 which I currently have at hand, this sentence is correct. If you have

```<code>#define X 3
enum MyEnum
{
    MyX = 3
};

int main(int argc, char* argv[])
{
    int i = X;
    int j = (int)MyX;
    return 0;
}
</code>```

and you set a breakpont in main, you can hover your mouse over "MyX" and see that it evaluates to 3. You do not see anything useful if you hover over X.

But this is not a language property but rather IDE behavior. Next versions might do it differently, as well as others IDEs. So just check it out for your IDE to see if this sentence applies in your case.

Title: C++ - enum vs. const vs. #define

Body:
At least for Visual Studio 2008 which I currently have at hand, this sentence is correct. If you have

#define X 3
enum MyEnum
{
    MyX = 3
};

int main(int argc, char* argv[])
{
    int i = X;
    int j = (int)MyX;
    return 0;
}

and you set a breakpont in main, you can hover your mouse over "MyX" and see that it evaluates to 3. You do not see anything useful if you hover over X.

But this is not a language property but rather IDE behavior. Next versions might do it differently, as well as others IDEs. So just check it out for your IDE to see if this sentence applies in your case.


问:
How to safely use possibly unsafe data with Query::select()?
First all, sorry about my english!
I'm trying do a dynamic select in CakePHP when i need change the statements of search. I know can use a variable to do that, but i think about SQL injection. It has other way to do this ?

Example:

```<code>$var = "quantidade";//$var can be other values.
$query->find('')->select('quantidade' => $var);
</code>```

答:
Unlike in other places like Query::where() when using the key => value syntax, there are no SQL injection prevention mechanisms in Query::select(), values passed to this method are being inserted into the query as is (they might get quoted, but not escaped), so you have to take care of securing this yourself.

I'd suggest to use a whitelist, either a hardcoded one:

```<code>$allowedFields = [
    'field_a',
    'field_b'
];

if (in_array($var, $allowedFields, true)) {
    $query = $Table
        ->find()
        ->select([
            'alias' => $var
        ]);
}
</code>```

or one retrieved from the tables schema in case you want to allow all fields, but be careful, only do this if it's definitely safe to expose all possible columns to the user!

```<code>$allowedFields = $Table->getSchema()->columns(); // use schema() in CakePHP < 3.4
</code>```

See also

Cookbook > Database Access & ORM > Query Builder > SQL Injection Prevention

Cookbook > Database Access & ORM > Schema System

API > \Cake\ORM\Table::getSchema()

API > \Cake\ORM\Table::schema()

Body:
First all, sorry about my english!
I'm trying do a dynamic select in CakePHP when i need change the statements of search. I know can use a variable to do that, but i think about SQL injection. It has other way to do this ?

Example:

$var = "quantidade";//$var can be other values.
$query->find('')->select('quantidade' => $var);

Body:
Unlike in other places like Query::where() when using the key => value syntax, there are no SQL injection prevention mechanisms in Query::select(), values passed to this method are being inserted into the query as is (they might get quoted, but not escaped), so you have to take care of securing this yourself.

I'd suggest to use a whitelist, either a hardcoded one:

$allowedFields = [
    'field_a',
    'field_b'
];

if (in_array($var, $allowedFields, true)) {
    $query = $Table
        ->find()
        ->select([
            'alias' => $var
        ]);
}

or one retrieved from the tables schema in case you want to allow all fields, but be careful, only do this if it's definitely safe to expose all possible columns to the user!

$allowedFields = $Table->getSchema()->columns(); // use schema() in CakePHP < 3.4

See also

Cookbook > Database Access & ORM > Query Builder > SQL Injection Prevention

Cookbook > Database Access & ORM > Schema System

API > \Cake\ORM\Table::getSchema()

API > \Cake\ORM\Table::schema()


问:
An efficient algorithm to count the number of integer grids
Consider a square 3 by 3 grid of non-negative integers.  For each row i the sum of the integers is set to be r_i.  Similarly for each column j the sum of integers in that column is set to be c_j.  An instance of the problem is therefore described by 6 non-negative integers.

Is there an efficient algorithm to count how many different
  assignments of integers to the grid there are given the row and column
  sum constraints?

Clearly one could enumerate all possible matrices of non-negative integers with values up to sum r_i and check the constraints for each, but that would be insanely slow.

Example

Say the row constraints are 1 2 3 and the column constraints are 3 2 1. The possible integer grids are:

```<code>┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│0 0 1│0 0 1│0 0 1│0 1 0│0 1 0│0 1 0│0 1 0│1 0 0│1 0 0│1 0 0│1 0 0│1 0 0│
│0 2 0│1 1 0│2 0 0│0 1 1│1 0 1│1 1 0│2 0 0│0 1 1│0 2 0│1 0 1│1 1 0│2 0 0│
│3 0 0│2 1 0│1 2 0│3 0 0│2 1 0│2 0 1│1 1 1│2 1 0│2 0 1│1 2 0│1 1 1│0 2 1│
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
</code>```

In practice my main interest is when the total sum of the grid will be at most 100 but a more general solution would be very interesting.

答:
Is there an efficient algorithm to count how many different assignments of integers to the grid there are given the row and column sum constraints?

upd My answer is wrong for this particular problem, when N is fixed (i.e. becomes constant 3). In this case it is polynomial. Sorry for misleading information.

TL;DR: I think it's at least NP-hard. There is no polinomial algorithm, but maybe there're some heuristic speedups.

For N-by-N grid you have N equations for row sums, N equations for col sums and N^2 non-negative constraints :

For N > 2 this system has more than one possible solution in general. Because there're N^2 unknown variables x_ij and just 2N equations => for N > 2: N^2 > 2N.

You can eliminate 2N - 1 variables to leave with just one equation with K = N^2 - (2N-1) variables getting the sum S. Then you'll have to deal with integer partition problem to find out all possible combinations of K terms to get the S. This problem is NP-complete. And the number of combinations depends not only on the number of terms K, but also on the order of the value S.

This problem reminded me about Simplex method. My first thought was to find just one solution using something like that method and then traverse edges of the convex to find all the possible solutions. And I was hoping that there's an optimal algorithm for that. But no, integer simplex method, which is related to integer linear programming, is NP-hard :(

I hope, there're some kind heuristics for related problems you can use to speedup naive brute force solution.

Body:
Consider a square 3 by 3 grid of non-negative integers.  For each row i the sum of the integers is set to be r_i.  Similarly for each column j the sum of integers in that column is set to be c_j.  An instance of the problem is therefore described by 6 non-negative integers.

Is there an efficient algorithm to count how many different
  assignments of integers to the grid there are given the row and column
  sum constraints?

Clearly one could enumerate all possible matrices of non-negative integers with values up to sum r_i and check the constraints for each, but that would be insanely slow.

Example

Say the row constraints are 1 2 3 and the column constraints are 3 2 1. The possible integer grids are:

┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│0 0 1│0 0 1│0 0 1│0 1 0│0 1 0│0 1 0│0 1 0│1 0 0│1 0 0│1 0 0│1 0 0│1 0 0│
│0 2 0│1 1 0│2 0 0│0 1 1│1 0 1│1 1 0│2 0 0│0 1 1│0 2 0│1 0 1│1 1 0│2 0 0│
│3 0 0│2 1 0│1 2 0│3 0 0│2 1 0│2 0 1│1 1 1│2 1 0│2 0 1│1 2 0│1 1 1│0 2 1│
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘

In practice my main interest is when the total sum of the grid will be at most 100 but a more general solution would be very interesting.


问:
How to modify paths to work for every user? (Python)
Ok I know this is probably a very simple question to answer but I don't know how to find the answer (I don't know the technical words used for this concept,etc)

I have a folder path like this one. Obviously where I've written "MYUSERNAME" I'd normally write my real username

C:\Users\MYUSERNAME\Desktop\Test

I'm using that path for a python code that I've previously compiled, and I want my friends to use that code without having to change the code. How do I automatically fill that "MYUSERNAME" with the username of the current user?
I've tried writing "User" and such in there but nothing works. Even if I have to add a few lines of code I don't care.

答: You need to use relative paths. More info: difference between relative and absolute.</p>


问:
Latest version of Glide giving dependency error
I have upgraded the version of Glide from 4.0.0-RC0 to 4.4.0. But it is giving me an error saying

```<code>Error:Module 'com.github.bumptech.glide:glide:4.4.0' depends on one or more Android Libraries but is a jar
</code>```

It is not saying which jar or any other information.
Does anybody know how to fix this? I am also attaching the entries for Glide in my build.gradle

```<code>compile 'com.github.bumptech.glide:glide:4.4.0'
compile 'com.github.bumptech.glide:okhttp3-integration:4.4.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.4.0'
compile 'com.github.bumptech.glide:annotations:4.4.0'
</code>```

EDIT :  I am using the support library version 27.0.1

答:
This is may be glide issue so, I will prefer to don't update glide to com.github.bumptech.glide:glide:4.4.0 till now. you can use older version like com.github.bumptech.glide:glide:4.3.1 or com.github.bumptech.glide:glide:4.3.0 or com.github.bumptech.glide:glide:4.2.0

you can read more about these issues on

issue 2318

issue 2319

Body:
I have upgraded the version of Glide from 4.0.0-RC0 to 4.4.0. But it is giving me an error saying

Error:Module 'com.github.bumptech.glide:glide:4.4.0' depends on one or more Android Libraries but is a jar

It is not saying which jar or any other information.
Does anybody know how to fix this? I am also attaching the entries for Glide in my build.gradle

compile 'com.github.bumptech.glide:glide:4.4.0'
compile 'com.github.bumptech.glide:okhttp3-integration:4.4.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.4.0'
compile 'com.github.bumptech.glide:annotations:4.4.0'

EDIT :  I am using the support library version 27.0.1


问:
Most reliable way of comparing datetimes?
I primarly use Delphi in my workplace and during some thorough unit tests which involved comparing date times I discovered that a direct comparison using the equals operator was not reliable enough when comparing calculated dates etc. So as a rule I started using CompareDateTime and SameDateTime which are built in functions for date comparisons in Delphi.

In C# by force of habit I compare date/times using the standard operators =<>. We have similar functions like DateTime.Compare and DateTime.Equals for date time comparisons therefore in terms of accuracy & reliability should I really be using the built in functions instead?

Will they give me a more accurate comparison that using the operator?

答:
I'm not really sure, but a colleague of mine told me to always use the Equals operator. For DateTime objects, Equals and Compare are comparing the ticks.

If you want to know more about the TimeSpan method ChrisF mentioned, see here.


问:
Communication between GrovePi vibration sensor and Raspberry pi
[code][1]I have a GrovePi to connect the vibration sensor to raspberry pi. I have downloaded the Groove software on my raspberry pi by using the following command:

cd /home/pi/Desktop
sudo git clone https://github.com/DexterInd/GrovePi
cd /home/pi/Desktop/GrovePi/Script
sudo chmod +x install.sh
sudo ./install.sh
sudo pip install grovepi
```
<p>After this I rebooted my raspberry pi and then when I inside the folder:</p>
<pre class="lang-sh prettyprint-override"><code>cd /home/pi/Desktop/GrovePi/Software/Python
sudo python grove_piezo_vibration_sensor.py
</code>```

I am getting following errors:

```<code>Trceback (most recent call last):

File "grove_piezo_vibration_sensor.py", line 49, in <module>
    print(grovepi.analogRead(piezo))
File "/home/pi/Desktop/GrovePi/Software/Python/grovepi.py", line 227, in analogRead
    return number[1] * 256 +number[2]
TypeError: 'int' object has no attribute '__getitem__'
</code>```

The code that I used was:

import time
import grovepi
# Connect the Grove Piezo Vibration Sensor to analog port A0
# OUT,NC,VCC,GND
piezo = 0

grovepi.pinMode(piezo,"INPUT")

while True:
    try:
        # When vibration is detected, the sensor outputs a logic high signal
        print grovepi.analogRead(piezo)
        time.sleep(.5)
    except IOError:
        print "Error"
```

Can you tell me what am I doing wrong. Thank you!

答:
If you look at the grovepi code, the analogRead function look like this:

```<code>def analogRead(pin):
    write_i2c_block(address, aRead_cmd + [pin, unused, unused])
    read_i2c_byte(address)
    number = read_i2c_block(address)
    return number[1] * 256 + number[2]
</code>```

You're seeing an exception on that last line, where it was expecting some kind of sequence back from read_i2c_block but instead got a single integer.  Looking elsewhere in the code, we see that read_i2c_block looks like this:

```<code>def read_i2c_block(address):
    for i in range(retries):
        try:
            return bus.read_i2c_block_data(address, 1)
        except IOError:
            if debug:
                print ("IOError")
    return -1
</code>```

Now, it looks as if read_i2c_block_data (from the smbus module) will always return a list.  That means the only way you're getting a single integer back from the above function is if it encounters an IOError exception.  This will be masked by the exception IOError block, and the function will then return -1.

There are a number of problems with this code in the grovepi module.  First, anything calling read_i2c_block (like the analogRead function) should be checking for the -1 return value.  Second, masking the exception like this isn't particularly helpful, because the exception probably contains information that would point to the source of the problem.  Consider replacing the above code with:

```<code>    for i in range(retries):
        try:
            return bus.read_i2c_block_data(address, 1)
        except IOError:
            if debug:
                raise
</code>```

And then enable debug mode.  That should be something like:

```<code>import grovepi
grovepi.debug = 1
</code>```

Now, run your code, and you should see the exception. See if it contains any more details about the error.

Body:
[code][1]I have a GrovePi to connect the vibration sensor to raspberry pi. I have downloaded the Groove software on my raspberry pi by using the following command:

cd /home/pi/Desktop
sudo git clone https://github.com/DexterInd/GrovePi
cd /home/pi/Desktop/GrovePi/Script
sudo chmod +x install.sh
sudo ./install.sh
sudo pip install grovepi

After this I rebooted my raspberry pi and then when I inside the folder:

cd /home/pi/Desktop/GrovePi/Software/Python
sudo python grove_piezo_vibration_sensor.py

I am getting following errors:

Trceback (most recent call last):

File "grove_piezo_vibration_sensor.py", line 49, in <module>
    print(grovepi.analogRead(piezo))
File "/home/pi/Desktop/GrovePi/Software/Python/grovepi.py", line 227, in analogRead
    return number[1] * 256 +number[2]
TypeError: 'int' object has no attribute '__getitem__'

The code that I used was:

import time
import grovepi
# Connect the Grove Piezo Vibration Sensor to analog port A0
# OUT,NC,VCC,GND
piezo = 0

grovepi.pinMode(piezo,"INPUT")

while True:
    try:
        # When vibration is detected, the sensor outputs a logic high signal
        print grovepi.analogRead(piezo)
        time.sleep(.5)
    except IOError:
        print "Error"

Can you tell me what am I doing wrong. Thank you!

Body:
If you look at the grovepi code, the analogRead function look like this:

def analogRead(pin):
    write_i2c_block(address, aRead_cmd + [pin, unused, unused])
    read_i2c_byte(address)
    number = read_i2c_block(address)
    return number[1] * 256 + number[2]

You're seeing an exception on that last line, where it was expecting some kind of sequence back from read_i2c_block but instead got a single integer.  Looking elsewhere in the code, we see that read_i2c_block looks like this:

def read_i2c_block(address):
    for i in range(retries):
        try:
            return bus.read_i2c_block_data(address, 1)
        except IOError:
            if debug:
                print ("IOError")
    return -1

Now, it looks as if read_i2c_block_data (from the smbus module) will always return a list.  That means the only way you're getting a single integer back from the above function is if it encounters an IOError exception.  This will be masked by the exception IOError block, and the function will then return -1.

There are a number of problems with this code in the grovepi module.  First, anything calling read_i2c_block (like the analogRead function) should be checking for the -1 return value.  Second, masking the exception like this isn't particularly helpful, because the exception probably contains information that would point to the source of the problem.  Consider replacing the above code with:

    for i in range(retries):
        try:
            return bus.read_i2c_block_data(address, 1)
        except IOError:
            if debug:
                raise

And then enable debug mode.  That should be something like:

import grovepi
grovepi.debug = 1

Now, run your code, and you should see the exception. See if it contains any more details about the error.


问:
macOS NSTextfield looses focus when NSPopover open
I am trying to make a search autocomplete in my macOS application:

I have a window with a NSTextField. When value changes, I display an NSPopover which contains NSOutlineView and the list is updated as the user is typing text.
The user can select a result in the NSOutlineView then.

But, if I make NSOutlineView enabled to be able to click on a result, the NSTextField looses focus when NSPopover opens.
If I set isEnabled to false for the NSOutlineView, NSTextField keeps focus but I can't select a result in the list.

Do you have any idea to keep focus on NSTextField without disable NSOutlineView ?

Thank you.

答:
I have found a solution:

Before NSPopover.show(), I store the current textField selected range:

```<code>let range = textField.currentEditor()?.selectedRange
</code>```

And after:

```<code>textField.selectText(self)
textField.currentEditor()?.selectedRange = range ?? NSMakeRange(0, 0)
</code>```

If I call selectText() without setting the selected range, it will select all text.
Moreover, save the selected range keeps cursor position.

Body:
I have found a solution:

Before NSPopover.show(), I store the current textField selected range:

let range = textField.currentEditor()?.selectedRange

And after:

textField.selectText(self)
textField.currentEditor()?.selectedRange = range ?? NSMakeRange(0, 0)

If I call selectText() without setting the selected range, it will select all text.
Moreover, save the selected range keeps cursor position.


问:
How can I generate a HmacSHA256 signature of a string
Is there any way to create a HmacSHA256 signature of a string in php?</p>

答:
Here is an example of datatrans transaction signing (swiss e-payment solution) before call PSP with HMAC-SHA-256.

Hope it could help some developers.

```<code>$hmacKey    = 30911337928580013;

$merchantId = 1100004624;
$amount     = $total * 100;
$currency   = 'EUR';
$refno      = $orderId;

// HMAC Hex to byte
$secret     = hex2bin("$hmacKey");

// Concat infos
$string     = $merchantId . $amount. $currency . $refno;

// generate SIGN
$sign       = bin2hex(hash_hmac('sha256', $string, $secret));
</code>```

Note: the merchant ID and HMAC key are both from Datatrans documentation available here : https://admin.sandbox.datatrans.com/showcase/doc/Technical_Implementation_Guide.pdf

Body:
Here is an example of datatrans transaction signing (swiss e-payment solution) before call PSP with HMAC-SHA-256.

Hope it could help some developers.

$hmacKey    = 30911337928580013;

$merchantId = 1100004624;
$amount     = $total * 100;
$currency   = 'EUR';
$refno      = $orderId;

// HMAC Hex to byte
$secret     = hex2bin("$hmacKey");

// Concat infos
$string     = $merchantId . $amount. $currency . $refno;

// generate SIGN
$sign       = bin2hex(hash_hmac('sha256', $string, $secret));

Note: the merchant ID and HMAC key are both from Datatrans documentation available here : https://admin.sandbox.datatrans.com/showcase/doc/Technical_Implementation_Guide.pdf


问:
Reading options inside a function and return it as a value
I'm trying to write a function which will parse my arguments. Here is how it looks like:

```<code>opts_get(){
    CONFIG=()
    while getopts "f:" opt; do
        case $opt in
            f)
                CONFIG=$OPTARG
                ;;
            :)
                echo "Option -$OPTARG requires argument" 1>&2
                exit 1
                ;;
            \?)
                echo "Invalid option -$OPTARG" 1>&2
                exit 1
                ;;
        esac
    done
    echo $CONFIG
}

echo $(opts_get)
</code>```

But unfortunately it prints empty line even if I pass the -f sdf option.

If I put the reading option code outside of any function

```<code>CONFIG=()
while getopts "f:" opt; do
    case $opt in
        f)
            CONFIG=$OPTARG
            ;;
        :)
            echo "Option -$OPTARG requires argument" 1>&2
            exit 1
            ;;
        \?)
            echo "Invalid option -$OPTARG" 1>&2
            exit 1
            ;;
    esac
done
echo $CONFIG #prints what I want
</code>```

答:
You are not passing the arguments the function. You need to pass it from the script to the function as below.

```<code>echo $(opts_get "$@")
</code>```

The 2nd case worked because the positional arguments form the command line are directly read by getopts. Also do fix the variable initialization to just CONFIG="" and not as an array declaration.

You also need to make sure that ${OPTIND} is local to the function by either unsetting it or declaring it local, otherwise you will encounter unexpected behaviour when invoking the function multiple times.

Body:
I'm trying to write a function which will parse my arguments. Here is how it looks like:

opts_get(){
    CONFIG=()
    while getopts "f:" opt; do
        case $opt in
            f)
                CONFIG=$OPTARG
                ;;
            :)
                echo "Option -$OPTARG requires argument" 1>&2
                exit 1
                ;;
            \?)
                echo "Invalid option -$OPTARG" 1>&2
                exit 1
                ;;
        esac
    done
    echo $CONFIG
}

echo $(opts_get)

But unfortunately it prints empty line even if I pass the -f sdf option.

If I put the reading option code outside of any function

CONFIG=()
while getopts "f:" opt; do
    case $opt in
        f)
            CONFIG=$OPTARG
            ;;
        :)
            echo "Option -$OPTARG requires argument" 1>&2
            exit 1
            ;;
        \?)
            echo "Invalid option -$OPTARG" 1>&2
            exit 1
            ;;
    esac
done
echo $CONFIG #prints what I want

Body:
You are not passing the arguments the function. You need to pass it from the script to the function as below.

echo $(opts_get "$@")

The 2nd case worked because the positional arguments form the command line are directly read by getopts. Also do fix the variable initialization to just CONFIG="" and not as an array declaration.

You also need to make sure that ${OPTIND} is local to the function by either unsetting it or declaring it local, otherwise you will encounter unexpected behaviour when invoking the function multiple times.


问:
One liner for iterating through two lists and removing item from one if exists in the other
Have two lists:

```<code>one = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
two = ['aaa', 'qqq', 'rrr', 'bbb', 'zzz']
</code>```

Currently I searched through both and if one exists in the other it is removed like so:

```<code>for i in one:
    for j in two:
        if j in i:
            one.remove(i)
</code>```

This returns

```<code>a = ['ccc', 'ddd', 'eee']
</code>```

Just wondering if there's a more pythonic way of doing it than how I currently am?

答:
Just use sets:

```<code>a = list(set(one) - set(two))
</code>```

gives the expected result.

Body:
Have two lists:

one = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
two = ['aaa', 'qqq', 'rrr', 'bbb', 'zzz']

Currently I searched through both and if one exists in the other it is removed like so:

for i in one:
    for j in two:
        if j in i:
            one.remove(i)

This returns

a = ['ccc', 'ddd', 'eee']

Just wondering if there's a more pythonic way of doing it than how I currently am?

Body:
Just use sets:

a = list(set(one) - set(two))

gives the expected result.


问:
How to solve this logic operation? (homework)
The teacher gave us this question and I couldn't answer it and I hope to get here some help.

Perform the following logic operation:

1- AB5D AND CD5F

2- DD1D XOR B159

And I want to know the step that I should follow to find the right answer.

答:
Convert the individual hex characters to binary, put them over one another, and for each column, if both are 1, the result will be one; in all other cases, the result will be zero.  Write this down below the two other binary strings.  Then, when you have done this for all digits, convert it back to hex.

Example:

```<code>A = 1010
C = 1100
    ----
    1000 = 8
</code>```

There is your first digit of ANDing AB5D and CD5F.  Keep doing it like that, and you'll get it.

The XOR operation gives a 1 where EITHER one or the other digit is 1, but not both.

It'd be worthwhile to brush up on all your bitwise operations, as well; they can all be done the same way.

Body:
Convert the individual hex characters to binary, put them over one another, and for each column, if both are 1, the result will be one; in all other cases, the result will be zero.  Write this down below the two other binary strings.  Then, when you have done this for all digits, convert it back to hex.

Example:

A = 1010
C = 1100
    ----
    1000 = 8

There is your first digit of ANDing AB5D and CD5F.  Keep doing it like that, and you'll get it.

The XOR operation gives a 1 where EITHER one or the other digit is 1, but not both.

It'd be worthwhile to brush up on all your bitwise operations, as well; they can all be done the same way.


问:
UITextView link tap recognition is delayed
In an iOS 7 app, I have a UITextView with a link in it, but tapping the link doesn't fire. It only responds to an awkward "tap and hold". I want it to respond as soon as a user taps on it, like how a UIWebView link tap works. Here is my setup:

```<code>- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."];
    [text addAttribute:NSLinkAttributeName value:@"myurl://tapped" range:NSMakeRange(6, 16)];

    self.textView.attributedText = text;
    self.textView.editable = NO;
    self.textView.delaysContentTouches = NO;
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    if ([[URL scheme] isEqualToString:@"myurl"])
    {
        // Handle tap

        return NO;
    }

    return YES;
}
</code>```

The Apple Documentation for the shouldInteractWithURL method states: "The text view calls this method if the user taps or long-presses the URL link". The long-press is working, but the tap doesn't seem to work.

Does anyone know how to get this to respond immediately?

答:
Swift 4 solution

Handles links using tap gesture recognizer

Whether isSelectable is true or false, it works

```<code>let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleLinkTap(_:)))
textView.addGestureRecognizer(tapRecognizer)

@objc func handleLinkTap(_ recognizer: UITapGestureRecognizer) {
    let tapLocation = recognizer.location(in: textView)
    guard
        let textPosition = textView.closestPosition(to: tapLocation),
        let url = textView.textStyling(at: textPosition, in: .forward)?[NSAttributedStringKey.link.rawValue],
        let urlString = (url as? String) ?? (url as? URL)?.absoluteString,
        urlString == "myurl"
    else { return }

    let url = URL(string: urlString)!
    // Do whatever you want with this URL, such as
    UIApplication.shared.openURL(url)
}
</code>```

Body:
In an iOS 7 app, I have a UITextView with a link in it, but tapping the link doesn't fire. It only responds to an awkward "tap and hold". I want it to respond as soon as a user taps on it, like how a UIWebView link tap works. Here is my setup:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."];
    [text addAttribute:NSLinkAttributeName value:@"myurl://tapped" range:NSMakeRange(6, 16)];

    self.textView.attributedText = text;
    self.textView.editable = NO;
    self.textView.delaysContentTouches = NO;
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    if ([[URL scheme] isEqualToString:@"myurl"])
    {
        // Handle tap

        return NO;
    }

    return YES;
}

The Apple Documentation for the shouldInteractWithURL method states: "The text view calls this method if the user taps or long-presses the URL link". The long-press is working, but the tap doesn't seem to work.

Does anyone know how to get this to respond immediately?

Body:
Swift 4 solution

Handles links using tap gesture recognizer

Whether isSelectable is true or false, it works

let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleLinkTap(_:)))
textView.addGestureRecognizer(tapRecognizer)

@objc func handleLinkTap(_ recognizer: UITapGestureRecognizer) {
    let tapLocation = recognizer.location(in: textView)
    guard
        let textPosition = textView.closestPosition(to: tapLocation),
        let url = textView.textStyling(at: textPosition, in: .forward)?[NSAttributedStringKey.link.rawValue],
        let urlString = (url as? String) ?? (url as? URL)?.absoluteString,
        urlString == "myurl"
    else { return }

    let url = URL(string: urlString)!
    // Do whatever you want with this URL, such as
    UIApplication.shared.openURL(url)
}


问:
ViewModel for multiple tables without links between tables
I'm trying to write a View Model in an ASP.NET MVC5 project to show data from different tables on a form that the user can then edit and save. I'm using the following :-

VS 2017, c#, MySQL Database, Entity Framework 6.1.3, MySQL Connector 6.9.9, Code First from Database (existing database that I can't change)

To complicate matters, there are no links between the tables in the database, so I cannot work out how to create a suitable View Model that will then allow me to save the changes.

Here are the 4 table models :-

```<code>public partial class evc_bearer
{
    [Key]
    [Column(Order = 0]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long evcid { get; set; }

    [Key]
    [Column(Order = 1]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long bearerid { get; set; }

    public int vlan { get; set; }

    [Column("ref")]
    public string _ref { get; set; }

    [Required]
    public string port { get; set; }

    [Required]
    public string endpoint { get; set; }
}

    public partial class bearer
{
    [Key]
    public long id { get; set; }

    [Column("ref")]
    [Required]
    public string _ref { get; set; }

    public string name { get; set; }

    public long? site { get; set; }

    public long? provider { get; set; }

    public long? mtu { get; set; }

    public float? rental { get; set; }

    public int? offsiteprovider { get; set; }

    public float? offsiteproviderrental { get; set; }

    public bool? aend { get; set; }

    public int? equipmentport { get; set; }

    public string orderref { get; set; }

    public string offsiteref { get; set; }

    public string notes { get; set; }

    public float? bookingfactor { get; set; }
}

public partial class evc
{
    [Key]
    public long id { get; set; }

    [Required]
    public string type { get; set; }

    public byte servicetype { get; set; }

    public byte cos { get; set; }

    public int cir { get; set; }

    public int pir { get; set; }

    public bool burst { get; set; }

    [Column("ref")]
    public string _ref { get; set; }

    public string orderref { get; set; }

    public byte state { get; set; }

    public string notes { get; set; }

    public float? rental { get; set; }
}

    public partial class evc_provider
{
    [Key]
    public long id { get; set; }

    [Required]
    public string provider { get; set; }
}
</code>```

This is the View Model I tried writing :-

```<code>public partial class evcBearersVM
{
    [Key]
    [Column(Order = 0)]
    public long evcid { get; set; }

    [Key]
    [Column(Order = 1)]
    public long id { get; set; }

    [Column("ref")]
    public string b_ref { get; set; }

    public string b_name { get; set; }

    public string ep_provider { get; set; }

    public int eb_vlan { get; set; }

    public string eb_port { get; set; }

    public string eb_endpoint { get; set; }
}
</code>```

This is the Linq query I used to populate the View Model :-

```<code>IQueryable<evcBearersVM> data = from eb in csdb.evc_bearers
    join b in csdb.bearers on eb.bearerid equals b.id
    join ep in csdb.evc_providers on b.provider equals ep.id
    join e in csdb.evcs on eb.evcid equals e.id
    where (eb.evcid == evcid && b.id == id)
    select new evcBearersVM
    {
        evcid = eb.evcid,
        id = b.id,
        b_ref = b._ref,
        b_name = b.name,
        ep_provider = ep.provider,
        eb_vlan = eb.vlan,
        eb_port = eb.port,
        eb_endpoint = eb._ref
    };
</code>```

So the query works and joins the tables to get the data I need and I can display this date in various views as needed. What I now need to do is be able to edit a row and save it back to the database. I have an Edit View that is showing the data I need but I'm not sure how to save changes given that it's a View Model and the DB Context isn't aware of it. Grateful for any help.

答:
What you should do is, use the same view model as your HttpPost action method parameter and inside the action method, read the entities  you want to udpate using the Id's (you can get this from the view model, assuming your form is submitting those) and update only those properties you need to update.</p>

```<code>[HttpPost]
public ActionResult Edit(evcBearersVM model)
{
    var b = csdb.bearers.FirstOrDefault(a=>a.id==model.id);
    if(b!=null)
    {
       b.name = model.b_name;
       b._ref = model.b_ref;
       csdb.SaveChanges();
    }
    // Update the other entity as well.

    return RedirectToAction("Index");
}
</code>```

Body:
I'm trying to write a View Model in an ASP.NET MVC5 project to show data from different tables on a form that the user can then edit and save. I'm using the following :-

VS 2017, c#, MySQL Database, Entity Framework 6.1.3, MySQL Connector 6.9.9, Code First from Database (existing database that I can't change)

To complicate matters, there are no links between the tables in the database, so I cannot work out how to create a suitable View Model that will then allow me to save the changes.

Here are the 4 table models :-

public partial class evc_bearer
{
    [Key]
    [Column(Order = 0]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long evcid { get; set; }

    [Key]
    [Column(Order = 1]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long bearerid { get; set; }

    public int vlan { get; set; }

    [Column("ref")]
    public string _ref { get; set; }

    [Required]
    public string port { get; set; }

    [Required]
    public string endpoint { get; set; }
}

    public partial class bearer
{
    [Key]
    public long id { get; set; }

    [Column("ref")]
    [Required]
    public string _ref { get; set; }

    public string name { get; set; }

    public long? site { get; set; }

    public long? provider { get; set; }

    public long? mtu { get; set; }

    public float? rental { get; set; }

    public int? offsiteprovider { get; set; }

    public float? offsiteproviderrental { get; set; }

    public bool? aend { get; set; }

    public int? equipmentport { get; set; }

    public string orderref { get; set; }

    public string offsiteref { get; set; }

    public string notes { get; set; }

    public float? bookingfactor { get; set; }
}

public partial class evc
{
    [Key]
    public long id { get; set; }

    [Required]
    public string type { get; set; }

    public byte servicetype { get; set; }

    public byte cos { get; set; }

    public int cir { get; set; }

    public int pir { get; set; }

    public bool burst { get; set; }

    [Column("ref")]
    public string _ref { get; set; }

    public string orderref { get; set; }

    public byte state { get; set; }

    public string notes { get; set; }

    public float? rental { get; set; }
}

    public partial class evc_provider
{
    [Key]
    public long id { get; set; }

    [Required]
    public string provider { get; set; }
}

This is the View Model I tried writing :-

public partial class evcBearersVM
{
    [Key]
    [Column(Order = 0)]
    public long evcid { get; set; }

    [Key]
    [Column(Order = 1)]
    public long id { get; set; }

    [Column("ref")]
    public string b_ref { get; set; }

    public string b_name { get; set; }

    public string ep_provider { get; set; }

    public int eb_vlan { get; set; }

    public string eb_port { get; set; }

    public string eb_endpoint { get; set; }
}

This is the Linq query I used to populate the View Model :-

IQueryable<evcBearersVM> data = from eb in csdb.evc_bearers
    join b in csdb.bearers on eb.bearerid equals b.id
    join ep in csdb.evc_providers on b.provider equals ep.id
    join e in csdb.evcs on eb.evcid equals e.id
    where (eb.evcid == evcid && b.id == id)
    select new evcBearersVM
    {
        evcid = eb.evcid,
        id = b.id,
        b_ref = b._ref,
        b_name = b.name,
        ep_provider = ep.provider,
        eb_vlan = eb.vlan,
        eb_port = eb.port,
        eb_endpoint = eb._ref
    };

So the query works and joins the tables to get the data I need and I can display this date in various views as needed. What I now need to do is be able to edit a row and save it back to the database. I have an Edit View that is showing the data I need but I'm not sure how to save changes given that it's a View Model and the DB Context isn't aware of it. Grateful for any help.

Body:
What you should do is, use the same view model as your HttpPost action method parameter and inside the action method, read the entities  you want to udpate using the Id's (you can get this from the view model, assuming your form is submitting those) and update only those properties you need to update.

[HttpPost]
public ActionResult Edit(evcBearersVM model)
{
    var b = csdb.bearers.FirstOrDefault(a=>a.id==model.id);
    if(b!=null)
    {
       b.name = model.b_name;
       b._ref = model.b_ref;
       csdb.SaveChanges();
    }
    // Update the other entity as well.

    return RedirectToAction("Index");
}