问:
Connecting to an Oracle Database in a C# Windows application with ManagedDataAccess using Bequeath Protocol
I'm attempting to use a Visual Studio C# Windows Application that connects to a local Oracle 12.2 database (using Oracle.ManagedDataAccess.Client) using the Bequeath protocol so that I don't have to go through the Oracle listener since this is just for a local database connection.

I know that sqlplus natively uses the Bequeath protocol when not specifying a connect string or TNS entry:

```<code>sqlplus scott/tiger

*connected*
</code>```

The SID and service_names are both "mydb":

```<code>select instance from v$thread;
-----
mydb

show parameter service_names;
VALUE
-----
mydb
</code>```

I can also use the Bequeath protocol when connecting through SQL Developer (using the connection type of Local/Bequeath).

However, I have been unable to find an example of using Bequeath in a connection string that works (at least for me).

The 12.1 documentation for Oracle Net Services isn't really helpful.  It gives an overview of Bequeath without any examples.

tnsnames.ora:

```<code>MYDB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SID = MYDB)
    )
  )

MYDB_BEQ =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = BEQ)(PROGRAM = oracle)(ARGV0 = oracleMYDB)
      )
    )
    (CONNECT_DATA = (SID = MYDB)
    )
  )
</code>```

The following works using TCP (which goes through the listener):

```<code>new OracleConnection(@"User Id=scott; Password=tiger
;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(
HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)
(SERVICE_NAME=MYDB)))");

*connected*
</code>```

Or using the TNSNAMES entry:

```<code>new OracleConnection("User Id=scott;Password=tiger;Data Source=MYDB")

*connected*
</code>```

I can connect through TNSNAMES using the above BEQ entry using SQLPLUS:

```<code>sqlplus scott/tiger@mydb_beq

*connected*
</code>```

However, I can't seem to get this to work through Oracle.ManagedDataAccess:

```<code>new OracleConnection(@"User Id=scott; Password=tiger
                                      ;Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = BEQ)(PROGRAM = oracle)(ARGV0 = oracleMYDB)))(CONNECT_DATA = (SID = MYDB)))")

ORA-12533: Network Session: Connect transport address syntax error
</code>```

Also tried this to use the TNSNAMES entry that worked above:

```<code>new OracleConnection("User Id=scott;Password=tiger;Data Source=MYDB_BEQ")

ORA-12533: Network Session: Connect transport address syntax error
</code>```

I'm probably missing something basic here, but i'm not sure what else to try...

答:
It doesn't look like that is possible.

In the dataSources Section of the 12c Data Provider for .NET Developer's Guide:

No bequeath (beq) support. Default address is instead TCP loopback
  with port 1521 and Oracle service name from environment (ORACLE_SID)

Body:
I'm attempting to use a Visual Studio C# Windows Application that connects to a local Oracle 12.2 database (using Oracle.ManagedDataAccess.Client) using the Bequeath protocol so that I don't have to go through the Oracle listener since this is just for a local database connection.

I know that sqlplus natively uses the Bequeath protocol when not specifying a connect string or TNS entry:

sqlplus scott/tiger

*connected*

The SID and service_names are both "mydb":

select instance from v$thread;
-----
mydb

show parameter service_names;
VALUE
-----
mydb

I can also use the Bequeath protocol when connecting through SQL Developer (using the connection type of Local/Bequeath).

However, I have been unable to find an example of using Bequeath in a connection string that works (at least for me).

The 12.1 documentation for Oracle Net Services isn't really helpful.  It gives an overview of Bequeath without any examples.

tnsnames.ora:

MYDB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SID = MYDB)
    )
  )

MYDB_BEQ =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = BEQ)(PROGRAM = oracle)(ARGV0 = oracleMYDB)
      )
    )
    (CONNECT_DATA = (SID = MYDB)
    )
  )

The following works using TCP (which goes through the listener):

new OracleConnection(@"User Id=scott; Password=tiger
;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(
HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)
(SERVICE_NAME=MYDB)))");

*connected*

Or using the TNSNAMES entry:

new OracleConnection("User Id=scott;Password=tiger;Data Source=MYDB")

*connected*

I can connect through TNSNAMES using the above BEQ entry using SQLPLUS:

sqlplus scott/tiger@mydb_beq

*connected*

However, I can't seem to get this to work through Oracle.ManagedDataAccess:

new OracleConnection(@"User Id=scott; Password=tiger
                                      ;Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = BEQ)(PROGRAM = oracle)(ARGV0 = oracleMYDB)))(CONNECT_DATA = (SID = MYDB)))")

ORA-12533: Network Session: Connect transport address syntax error

Also tried this to use the TNSNAMES entry that worked above:

new OracleConnection("User Id=scott;Password=tiger;Data Source=MYDB_BEQ")

ORA-12533: Network Session: Connect transport address syntax error

I'm probably missing something basic here, but i'm not sure what else to try...


来源: stackexchange

问:
ImportError: No module named _tkinter in Python 2.7.13
I am running RedHat 4.1.2 offline and trying to get _tkinter working for Python 2.7.13. I have Tcl/tk 8.4 installed, but it doesn't seem to be working right. libtcl8.4.so is located in /usr/lib64/ and I'm not sure if that's related, but I figured I would mention it. Here is the error when I try import Tkinter.

Python terminal output

答:
Perhaps you could try a package manager such as Anaconda and install Tkinter.

This post may help.

ContentLicense: CC BY-SA 3.0


问:
Microsoft Graph schemaExtensions Authorization_RequestDenied
I'm trying to use Microsoft Graph from my app via REST API graph.microsoft.com/beta/schemaExtensions

Here is what I did:

Register app at https://apps.dev.microsoft.com

Checked for all Delegated and Application authorizations

Got access token without a user based on OAuth Client Credentials Grant flow

Asked for Admin Consent with access token retrieved from point 3. and it was successful using https://login.microsoftonline.com/tenant/adminconsent?client_id=xxx&state=12345&redirect_uri=http://localhost:8081

POST to /beta/schemaExtensions with access token retrieved from point 3. and I have this error:

Authorization_RequestDenied - Insufficient privileges to complete the operation

So here are my questions, hoping someone could help me:

How do I check if delegate authorization is ok after Admin Consent request?

Which privileges are missing to use schemaExtensions?

My app should work without a user, it's the preferred approach.

答: To answer the follow up question, the calling user should have read/write access to add custom data to another user. However, you can use open extensions to add custom data using /me/extensions to calling user (as long as the app has user.readwrite or higher permissions).</p>


问:
Make values in tensor fit in given range
I have a 3d tensor and would like to ensure that all values fall within a given range (0-1 in this case). In order to do this I have already written the following code:

```<code>    function capTo1or0 (Tensor3d)

       tensor_width=Tensor3d:size()[2]
       tensor_height=Tensor3d:size()[3]
       tensor_depth=Tensor3d:size()[1]
       for i=1,tensor_width,1 do
           for j=1,tensor_height,1 do
               for k=1,tensor_depth,1 do
                   if(Tensor3d[k][i][j])>1 then

                       Tensor3d[k][i][j]=1

                   end
                   if(Tensor3d[k][i][j]<0.0) then
                        Tensor3d[k][i][j]=0.0
                   end
               end
           end
        end
       return Tensor3d
    end
</code>```

and it works, there is just one problem: performance is terrible, I know that there has to be some better way of doing this then looping over the entire array given that most tensor operations that do not involve manually looping over an array are much faster. Anybody know how to make this faster?

```<code>An example in this is say that I have a `2-3-3` array with the values

    [1,  2,  0.5][0.5,0.2,-0.2]
     [0.1,0.2,0.3][1,  1,   1  ]
    [-2, -1, 2  ][0.2,-5,-1   ]

then I expect an outcome of
    [1,  1,  0.5][0.5,0.2,0]
    [0.1,0.2,0.3][1,  1,   1  ]
    [0, 0, 1  ]  [0.2,0,-1   ]
</code>```

replacing every value under the lower bound of 0 with 0 and every value over the upper bound of 1 with 1.

Anybody know how to do this fast?

答:
I have never used Torch, but it's documentation says:
http://torch7.readthedocs.io/en/rtd/maths/#torch.clamp

[res] torch.clamp([res,] tensor1, min_value, max_value)

Clamp all elements in the tensor into the range [min_value,
  max_value]. ie:

```<code>y_i = x_i, if x_i >= min_value or x_i <= max_value
    = min_value, if x_i < min_value
    = max_value, if x_i > max_value
</code>```

z=torch.clamp(x,0,1) will return a new tensor with the result of x
  bounded between 0 and  1.

torch.clamp(z,x,0,1) will put the result in z.

x:clamp(0,1) will perform the clamp operation in place (putting the
  result in x).

z:clamp(x,0,1) will put the result in z.

I guess that is what you are looking for?

Body:
I have a 3d tensor and would like to ensure that all values fall within a given range (0-1 in this case). In order to do this I have already written the following code:

    function capTo1or0 (Tensor3d)

       tensor_width=Tensor3d:size()[2]
       tensor_height=Tensor3d:size()[3]
       tensor_depth=Tensor3d:size()[1]
       for i=1,tensor_width,1 do
           for j=1,tensor_height,1 do
               for k=1,tensor_depth,1 do
                   if(Tensor3d[k][i][j])>1 then

                       Tensor3d[k][i][j]=1

                   end
                   if(Tensor3d[k][i][j]<0.0) then
                        Tensor3d[k][i][j]=0.0
                   end
               end
           end
        end
       return Tensor3d
    end

and it works, there is just one problem: performance is terrible, I know that there has to be some better way of doing this then looping over the entire array given that most tensor operations that do not involve manually looping over an array are much faster. Anybody know how to make this faster?

An example in this is say that I have a `2-3-3` array with the values

    [1,  2,  0.5][0.5,0.2,-0.2]
     [0.1,0.2,0.3][1,  1,   1  ]
    [-2, -1, 2  ][0.2,-5,-1   ]

then I expect an outcome of
    [1,  1,  0.5][0.5,0.2,0]
    [0.1,0.2,0.3][1,  1,   1  ]
    [0, 0, 1  ]  [0.2,0,-1   ]

replacing every value under the lower bound of 0 with 0 and every value over the upper bound of 1 with 1.

Anybody know how to do this fast?

Body:
I have never used Torch, but it's documentation says:
http://torch7.readthedocs.io/en/rtd/maths/#torch.clamp

[res] torch.clamp([res,] tensor1, min_value, max_value)

Clamp all elements in the tensor into the range [min_value,
  max_value]. ie:

y_i = x_i, if x_i >= min_value or x_i <= max_value
    = min_value, if x_i < min_value
    = max_value, if x_i > max_value

z=torch.clamp(x,0,1) will return a new tensor with the result of x
  bounded between 0 and  1.

torch.clamp(z,x,0,1) will put the result in z.

x:clamp(0,1) will perform the clamp operation in place (putting the
  result in x).

z:clamp(x,0,1) will put the result in z.

I guess that is what you are looking for?


问:
How to fit all pixel sized images in a div?
I'm building a web application where I want to display product like in e-commerce website. The images of random dimension have to be fit in a particular box.
I have tried following code but it distorts the image if height is more than width, but looks perfectly if it is vice versa.</p>

```<code><div class="panel panel-default text-center">
                <div class="panel-heading" style="padding:2px;">
                    <a href="#" style=" text-decoration: none;"><img  src="images/abc.jpg" style="width:100%;height:220px;" /></a></a>
                </div>

                <div class="panel-body w3-card" style="padding-top:0px;background-color:#ebebeb;">
                    <a href="#" class="pull-left" style=" text-decoration: none;"><h5 style="margin-bottom:0px;" ><b>Product One</b></h5>
                    <p class="pull-left" style="margin-top:0px;color:#6e6e6e;margin-bottom:0px;"><i class="fa fa-inr"></i> 10,000/-</p></a>
                </div>

            </div>
</code>```

答:
The following is the answer with little modification from the comment.</p>

```<code><div class="panel panel-default text-center">
    <div class="panel-heading" style="padding:2px;overflow:hidden;">
        <a href="#" style=" text-decoration: none;"><img  src="images/abc.jpg" style="max-width: 100%; height: 100%;" /></a></a>
    </div>
    <div class="panel-body w3-card" style="padding-top:0px;background-color:#ebebeb;">
        <a href="#" class="pull-left" style=" text-decoration: none;"><h5 style="margin-bottom:0px;" ><b>Product One</b></h5>
            <p class="pull-left" style="margin-top:0px;color:#6e6e6e;margin-bottom:0px;"><i class="fa fa-inr"></i> 10,000/-</p></a>
        </div>
    </div>
</div>
</code>```

Body:
I'm building a web application where I want to display product like in e-commerce website. The images of random dimension have to be fit in a particular box.
I have tried following code but it distorts the image if height is more than width, but looks perfectly if it is vice versa.

Product One

 10,000/-

Body:
The following is the answer with little modification from the comment.

<div class="panel panel-default text-center">
    <div class="panel-heading" style="padding:2px;overflow:hidden;">
        <a href="#" style=" text-decoration: none;"><img  src="images/abc.jpg" style="max-width: 100%; height: 100%;" /></a></a>
    </div>
    <div class="panel-body w3-card" style="padding-top:0px;background-color:#ebebeb;">
        <a href="#" class="pull-left" style=" text-decoration: none;"><h5 style="margin-bottom:0px;" ><b>Product One</b></h5>
            <p class="pull-left" style="margin-top:0px;color:#6e6e6e;margin-bottom:0px;"><i class="fa fa-inr"></i> 10,000/-</p></a>
        </div>
    </div>
</div>


问:
Object Oriented questions in Javascript
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

```<code>function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

```<code>function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

```<code>var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());
</code>```

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

```<code>var user = new User("Bob", 44);
</code>```

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

答:
Your example #1 shows the usage of the prototype property. This property is available to all javascript objects you create and allows you to add properties or functions to the object declaration, so you had a object with 2 properties and later on you added 4 functions (getters and setters).

You should see the prototype property as the way to modify your object specification at runtime, say you have an object called name:

```<code>var Name = {
  First: "",
  Last: ""
};
</code>```

You can use the prototype to add a function getFullName() later on by simply:

```<code>Name.prototype.getFullName = function() { return this.First + " " + this.Last; }
</code>```

In the example 2 you inline the declaration of these getters and setters in the object declaration so in the end they are the same. Finally on the 3rd example you use the JavaScript object notation you should see JSON.

About your question 2 you can just declare your object as:

```<code>var User = {
  name: "",
  age: 0
};
</code>```

this will give you the same object without getters and setters.

OwnerDisplayName: BrianH

ContentLicense: CC BY-SA 2.5

Title: Object Oriented questions in Javascript

Body:
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

var user = new User("Bob", 44);

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

LastEditorDisplayName: BrianH

Body:
Your example #1 shows the usage of the prototype property. This property is available to all javascript objects you create and allows you to add properties or functions to the object declaration, so you had a object with 2 properties and later on you added 4 functions (getters and setters).

You should see the prototype property as the way to modify your object specification at runtime, say you have an object called name:

var Name = {
  First: "",
  Last: ""
};

You can use the prototype to add a function getFullName() later on by simply:

Name.prototype.getFullName = function() { return this.First + " " + this.Last; }

In the example 2 you inline the declaration of these getters and setters in the object declaration so in the end they are the same. Finally on the 3rd example you use the JavaScript object notation you should see JSON.

About your question 2 you can just declare your object as:

var User = {
  name: "",
  age: 0
};

this will give you the same object without getters and setters.

OwnerDisplayName: Paulo Lopes


问:
Help creating an app with parsing
I'm working on my University thesis creating an android app. As I'm new in android development I would like to read your opinion on that.

I would like to create an app that has a home screen with n buttons. This will be the app for my uni forum. When I press the "announcement" button for example I want to get the announcements from my university site.

The problem is, that this site doesn't have a rss feed and but I want to see the announcements in the app and not with a WebView.

Could you please tell me what I have to search for? HTML parsing? Hope my question is understandable.

答: Take a look into Web Scraping</p>

Title: Help creating an app with parsing

Body: Take a look into Web Scraping


问:
Message says NonType object, but object is a QHBoxLayout
I am new to PyQt and I encounter a rather difficult (to me) problem.

I have a QVBoxLayout. I populate it dynamically with several QHBoxLayout.
Each QHBoxLayout host, in this order, 3 QLineEdit, 1 QLabel and 1 QPushButton.

The button on the right is connected to the function remove_malt  whose code is given below :

```<code>def add_malt(self):#call when clicking on a push button
    maltT=self.s[str(self.malt_list_widget.currentItem().text())]
    self.listMalts.append(maltT)
    h_layout=QtGui.QHBoxLayout()#create an horizontal layout to host widgets for one malt line
    h_layout.addWidget(QtGui.QLineEdit(maltT.full_name))#for grain full name
    h_layout.addWidget(QtGui.QLineEdit())#for percentage
    h_layout.addWidget(QtGui.QLineEdit())#for calculated mass
    h_layout.addWidget(QtGui.QLabel('kg'))#for unit
    h_layout.addWidget(QtGui.QPushButton('X')) #for deletion
    h_layout.itemAt(0).widget().setMinimumSize(400,30)
    h_layout.itemAt(0).widget().setStyleSheet("font-size: 14px;background-color: rgb(230, 230, 230);")
    h_layout.itemAt(0).widget().setReadOnly(True)
    h_layout.itemAt(1).widget().setMaximumSize(50,30)
    h_layout.itemAt(1).widget().setStyleSheet("font-size: 14px;background-color: white;")
    h_layout.itemAt(1).widget().textEdited.connect(self.clean_results)
    h_layout.itemAt(2).widget().setMaximumSize(70,30)
    h_layout.itemAt(2).widget().setStyleSheet("font-size: 14px;background-color: rgb(230,230,0) ;")
    h_layout.itemAt(2).widget().setReadOnly(True)
    h_layout.itemAt(3).widget().setMaximumSize(50,30)
    h_layout.itemAt(3).widget().setStyleSheet("font-size: 14px;")
    h_layout.itemAt(4).widget().setMaximumSize(30,30)
    h_layout.itemAt(4).widget().setStyleSheet("font-size: 14px;color: 'red';background-color: rgb(230,230,230);font-weight: bold; ")

    h_layout.itemAt(4).widget().clicked.connect(self.remove_malt)
    self.grainLayout.addLayout(h_layout)

def remove_malt(self):
    s= self.sender()
    for i in range(self.grainLayout.count()):
        #if i==0:
         #   continue
        print('loop '+str(i))
        #pb=self.grainLayout.itemAt(i).layout().itemAt(4).widget()
        ly=self.grainLayout.itemAt(i).layout()
        print ('voici ly')
        print (ly)
        pb=ly.itemAt(4).widget()
        if s ==pb:
            print('delete '+str(i))
            self.clearLayout(self.grainLayout.itemAt(i).layout())
            del self.listMalts[i]
            return

def clearLayout(self,layout):
    print(layout)
    if layout is not None:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else :
                self.clearLayout(item.layout())
</code>```

The wrapping QVBoxLayout is called grainLayout and the text above is not part of it.
I volontarily broke the line`#pb=self.grainLayout.itemAt(i).layout().itemAt(4).widget() in order to be able to print the value of ly (layout) which is the source of the pb.

I can remove some of the lines (QHBoxLayout) but at some moment, sometime at the last one, some other time at a random position,something wrong happens.
Here is the content of the console

```<code>    loop 0
voici ly
<PyQt4.QtGui.QHBoxLayout object at 0x7faef91e06d8>
delete 0
<PyQt4.QtGui.QHBoxLayout object at 0x7faef91e06d8>
loop 0
voici ly
<PyQt4.QtGui.QHBoxLayout object at 0x7faef91e06d8>
Traceback (most recent call last):
  File "/home/jaaf/beer/MassCalculationWindow.py", line 122, in remove_malt
    pb=ly.itemAt(4).widget()
AttributeError: 'NoneType' object has no attribute 'widget'
</code>```

line 122 is the line where pb is evaluated

Reading this, it seems that at the moment of the pb 'NonType object has no attribute 'widget' ly is exactly the same object as before, I mean a QHBoxLayout.

Please, I need help.

答:
In your code you must remove the items, in addition to removing the widgets, besides verifying that the item exists.

Remark: if obj is not None: is equal to if obj:

```<code>def remove_malt(self):
    s= self.sender()
    for i in range(self.grainLayout.count()):
        item =self.grainLayout.itemAt(i)
        if item:
            if s == item.layout().itemAt(4).widget():
                self.clearLayout(item.layout())
                self.grainLayout.removeItem(item)
                del self.listMalts[i]
                return

def clearLayout(self, layout):
    if layout:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget:
                widget.deleteLater()
            else :
                self.clearLayout(item.layout())
            layout.removeItem(item)
</code>```

Body:
I am new to PyQt and I encounter a rather difficult (to me) problem.

I have a QVBoxLayout. I populate it dynamically with several QHBoxLayout.
Each QHBoxLayout host, in this order, 3 QLineEdit, 1 QLabel and 1 QPushButton.

The button on the right is connected to the function remove_malt  whose code is given below :

def add_malt(self):#call when clicking on a push button
    maltT=self.s[str(self.malt_list_widget.currentItem().text())]
    self.listMalts.append(maltT)
    h_layout=QtGui.QHBoxLayout()#create an horizontal layout to host widgets for one malt line
    h_layout.addWidget(QtGui.QLineEdit(maltT.full_name))#for grain full name
    h_layout.addWidget(QtGui.QLineEdit())#for percentage
    h_layout.addWidget(QtGui.QLineEdit())#for calculated mass
    h_layout.addWidget(QtGui.QLabel('kg'))#for unit
    h_layout.addWidget(QtGui.QPushButton('X')) #for deletion
    h_layout.itemAt(0).widget().setMinimumSize(400,30)
    h_layout.itemAt(0).widget().setStyleSheet("font-size: 14px;background-color: rgb(230, 230, 230);")
    h_layout.itemAt(0).widget().setReadOnly(True)
    h_layout.itemAt(1).widget().setMaximumSize(50,30)
    h_layout.itemAt(1).widget().setStyleSheet("font-size: 14px;background-color: white;")
    h_layout.itemAt(1).widget().textEdited.connect(self.clean_results)
    h_layout.itemAt(2).widget().setMaximumSize(70,30)
    h_layout.itemAt(2).widget().setStyleSheet("font-size: 14px;background-color: rgb(230,230,0) ;")
    h_layout.itemAt(2).widget().setReadOnly(True)
    h_layout.itemAt(3).widget().setMaximumSize(50,30)
    h_layout.itemAt(3).widget().setStyleSheet("font-size: 14px;")
    h_layout.itemAt(4).widget().setMaximumSize(30,30)
    h_layout.itemAt(4).widget().setStyleSheet("font-size: 14px;color: 'red';background-color: rgb(230,230,230);font-weight: bold; ")

    h_layout.itemAt(4).widget().clicked.connect(self.remove_malt)
    self.grainLayout.addLayout(h_layout)

def remove_malt(self):
    s= self.sender()
    for i in range(self.grainLayout.count()):
        #if i==0:
         #   continue
        print('loop '+str(i))
        #pb=self.grainLayout.itemAt(i).layout().itemAt(4).widget()
        ly=self.grainLayout.itemAt(i).layout()
        print ('voici ly')
        print (ly)
        pb=ly.itemAt(4).widget()
        if s ==pb:
            print('delete '+str(i))
            self.clearLayout(self.grainLayout.itemAt(i).layout())
            del self.listMalts[i]
            return

def clearLayout(self,layout):
    print(layout)
    if layout is not None:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else :
                self.clearLayout(item.layout())

The wrapping QVBoxLayout is called grainLayout and the text above is not part of it.
I volontarily broke the line`#pb=self.grainLayout.itemAt(i).layout().itemAt(4).widget() in order to be able to print the value of ly (layout) which is the source of the pb.

I can remove some of the lines (QHBoxLayout) but at some moment, sometime at the last one, some other time at a random position,something wrong happens.
Here is the content of the console

    loop 0
voici ly
<PyQt4.QtGui.QHBoxLayout object at 0x7faef91e06d8>
delete 0
<PyQt4.QtGui.QHBoxLayout object at 0x7faef91e06d8>
loop 0
voici ly
<PyQt4.QtGui.QHBoxLayout object at 0x7faef91e06d8>
Traceback (most recent call last):
  File "/home/jaaf/beer/MassCalculationWindow.py", line 122, in remove_malt
    pb=ly.itemAt(4).widget()
AttributeError: 'NoneType' object has no attribute 'widget'

line 122 is the line where pb is evaluated

Reading this, it seems that at the moment of the pb 'NonType object has no attribute 'widget' ly is exactly the same object as before, I mean a QHBoxLayout.

Please, I need help.

Body:
In your code you must remove the items, in addition to removing the widgets, besides verifying that the item exists.

Remark: if obj is not None: is equal to if obj:

def remove_malt(self):
    s= self.sender()
    for i in range(self.grainLayout.count()):
        item =self.grainLayout.itemAt(i)
        if item:
            if s == item.layout().itemAt(4).widget():
                self.clearLayout(item.layout())
                self.grainLayout.removeItem(item)
                del self.listMalts[i]
                return

def clearLayout(self, layout):
    if layout:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget:
                widget.deleteLater()
            else :
                self.clearLayout(item.layout())
            layout.removeItem(item)


问:
Issuse: Scipy Fitting Normal Data
I currently have some experiemental data imported and plotted which is normally distributed.

I then tried using Scipy to fit a normal distrubtion to the data:

```<code>from scipy.stats import norm

def normal_fit(data, offset):
    x = numpy.linspace(0, len(data), len(data))
    params = norm.fit(data - offset)
    normal = norm.pdf(x, params[0], params[1])

    return normal, params
</code>```

However it calculates a mean and standard deviation (4504, 2961) that is incorrect - plotted in red below.

How can I fit the data properly?

Edit: Data is offset to zero as suggested by ev-br, this produces parameters that still don't make much sense (954, 2961)

Title: Issuse: Scipy Fitting Normal Data

Body:
I currently have some experiemental data imported and plotted which is normally distributed.

I then tried using Scipy to fit a normal distrubtion to the data:

from scipy.stats import norm

def normal_fit(data, offset):
    x = numpy.linspace(0, len(data), len(data))
    params = norm.fit(data - offset)
    normal = norm.pdf(x, params[0], params[1])

    return normal, params

However it calculates a mean and standard deviation (4504, 2961) that is incorrect - plotted in red below.

How can I fit the data properly?

Edit: Data is offset to zero as suggested by ev-br, this produces parameters that still don't make much sense (954, 2961)

Body:
I played with similar problem Curve fiting of normal distribution in Python

added b, a offset to the curve fit, seems to need a halfway OK guess value

then the scale factor sign changed?? to I just patched over it, don't understand myself

here is the reworked code with curve_fit, also finds offset:

from scipy.stats import norm
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

x = np.array([ 0.47712125,  0.5445641 ,  0.61193563,  0.67924615,  0.74671202,
    0.81404772,  0.88144172,  0.94885291,  1.01623919,  1.08361011,
    1.15100191,  1.21837793,  1.28578227,  1.3531658 ,  1.42054981,
    1.48794397,  1.55532424,  1.62272161,  1.69010744,  1.75749472,
    1.82488047,  1.89226717,  1.9596566 ,  2.02704774,  2.09443269,
    2.16182302,  2.2292107 ,  2.29659719,  2.36398595,  2.43137342,
    2.49876254,  2.56614983,  2.63353814,  2.700926  ,  2.76831392,
    2.83570198,  2.90308999,  2.97008999,  3.03708997,  3.10408999,
    3.17108999,  3.23808998,  3.30508998,  3.37208999,  3.43908999,
    3.50608998,  3.57308998,  3.64008999,  3.70708999,  3.77408999,
    3.84108999,  3.90808999])/2
y = np.array([  0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
     0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
     0.00000000e+00,   5.50000000e+01,   1.33500000e+02,
     2.49000000e+02,   4.40000000e+02,   7.27000000e+02,
     1.09000000e+03,   1.53000000e+03,   2.21500000e+03,
     3.13500000e+03,   4.44000000e+03,   5.57000000e+03,
     6.77000000e+03,   8.04500000e+03,   9.15500000e+03,
     1.00000000e+04,   1.06000000e+04,   1.06500000e+04,
     1.02000000e+04,   9.29000000e+03,   8.01500000e+03,
     6.50000000e+03,   5.24000000e+03,   4.11000000e+03,
     2.97000000e+03,   1.86000000e+03,   1.02000000e+03,
     5.26500000e+02,   2.49000000e+02,   1.11000000e+02,
     5.27000000e+01,   6.90825000e+00,   4.54329000e+00,
     3.63846500e+00,   3.58135000e+00,   2.37404000e+00,
     1.81840000e+00,   1.20159500e+00,   6.02470000e-01,
     3.43295000e-01,   1.62295000e-01,   7.99350000e-02,
     3.60750000e-02,   1.50000000e-02,   3.61500000e-03,
     8.00000000e-05])+10000
#numpy.random.normal(loc=0.0, scale=2.0, size=100)
'''
norm.pdf(x) = exp(-x**2/2)/sqrt(2*pi)
norm.pdf(x, loc, scale) == norm.pdf(y) / scale with y = (x - loc) / scale
'''
def datafit(x,N,u,sig,b):
    y = N*np.exp(-((x-u)/sig)**2/2)/(np.sqrt(2*np.pi)) + b
    return y
popt,popc = curve_fit(datafit,x,y,p0=[np.max(y),2,2,1000])

# scipy norm.pdf with scaling factors to match datafit()
scale = abs(popt[2]) # I don't know why, but it 1s needed with b
Normal_distribution = popt[0]*scale*norm.pdf(x, popt[1], scale) + popt[3]

plt.plot(x,y, 'b-')
plt.plot(x, datafit(x+.1, *popt), 'g')
plt.plot(x, Normal_distribution, 'r')


问:
Trying to get an object value in from a key in Javascript
I'm trying to get a country label (name) from a value (country code) in an object.

In Vue.js I'm trying to build a computed property to return the name of the country based on the country code from an API request.

In the template:

```<code>countryLabel () {
    var countries = require('../../plugins/countries')
    var countryCode = this.content.country
    function getLabelByValue(countries, countryCode) {
        return Object.keys(countries).find(label => countries[value] === countryCode)
    }
}
</code>```

From a list of countries:

```<code>module.exports = [
    { value: 'AF', label: 'Afghanistan' },
    { value: 'AX', label: 'Aland Islands' },
    { value: 'AL', label: 'Albania' },
    { value: 'DZ', label: 'Algeria' },
    { value: 'AS', label: 'American Samoa' },
    { value: 'AD', label: 'Andorra' },
    { value: 'AO', label: 'Angola' },
    { value: 'AI', label: 'Anguilla' },
    { value: 'AQ', label: 'Antarctica' },
    { value: 'AG', label: 'Antigua and Barbuda' },
    ...
]
</code>```

答:
You probably don't want to be calling Object.keys on an array.

Something like this is probably more what you want:

```<code>function getLabelByValue(countries, countryCode) {
    const entry = countries.find(item => item.value === countryCode);
    return entry ? entry.label : null;
}
</code>```

The problem is that calling Object.keys on an array will return an array of numbers that have been converted to strings:

```<code>> console.log(Object.keys(['this', 'is', 'an', 'array']));
['0', '1', '2', '3']
</code>```

Since your exports is already an array, you can call find() on it directly.

Body:
I'm trying to get a country label (name) from a value (country code) in an object.

In Vue.js I'm trying to build a computed property to return the name of the country based on the country code from an API request.

In the template:

countryLabel () {
    var countries = require('../../plugins/countries')
    var countryCode = this.content.country
    function getLabelByValue(countries, countryCode) {
        return Object.keys(countries).find(label => countries[value] === countryCode)
    }
}

From a list of countries:

module.exports = [
    { value: 'AF', label: 'Afghanistan' },
    { value: 'AX', label: 'Aland Islands' },
    { value: 'AL', label: 'Albania' },
    { value: 'DZ', label: 'Algeria' },
    { value: 'AS', label: 'American Samoa' },
    { value: 'AD', label: 'Andorra' },
    { value: 'AO', label: 'Angola' },
    { value: 'AI', label: 'Anguilla' },
    { value: 'AQ', label: 'Antarctica' },
    { value: 'AG', label: 'Antigua and Barbuda' },
    ...
]

Body:
You probably don't want to be calling Object.keys on an array.

Something like this is probably more what you want:

function getLabelByValue(countries, countryCode) {
    const entry = countries.find(item => item.value === countryCode);
    return entry ? entry.label : null;
}

The problem is that calling Object.keys on an array will return an array of numbers that have been converted to strings:

> console.log(Object.keys(['this', 'is', 'an', 'array']));
['0', '1', '2', '3']

Since your exports is already an array, you can call find() on it directly.


问:
JSP Login page not working
I'm trying to create a login page for a site (I'm using a tutorial right now - never done this before).  When I go to use the "login" page, it pops a 404 error.  Here is the code.

LoginPage.jsp

```<code><%@ page language="java"
    contentType="text/html; charset=windows-1256"
    pageEncoding="windows-1256"
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
        <title>Login Page</title>
    </head>

    <body>
        <form action="LoginServlet">

            Please enter your username
            <input type="text" name="un"/><br>

            Please enter your password
            <input type="text" name="pw"/>

            <input type="submit" value="submit">

        </form>
    </body>
</html>
</code>```

LoginServlet.java

```<code>package ExamplePackage;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
                       throws ServletException, java.io.IOException {

try
{

     UserBean user = new UserBean();
     user.setUserName(request.getParameter("un"));
     user.setPassword(request.getParameter("pw"));

     user = UserDAO.login(user);

     if (user.isValid())
     {

          HttpSession session = request.getSession(true);
          session.setAttribute("currentSessionUser",user);
          response.sendRedirect("userLogged.jsp"); //logged-in page
     }

     else
          response.sendRedirect("invalidLogin.jsp"); //error page
}

catch (Throwable theException)
{
     System.out.println(theException);
}
       }
    }
</code>```

UserBean.Java

```<code>package ExamplePackage;

public class UserBean {

      private String username;
      private String password;
      private String firstName;
      private String lastName;
      public boolean valid;

      public String getFirstName() {
         return firstName;
    }

      public void setFirstName(String newFirstName) {
         firstName = newFirstName;
    }

      public String getLastName() {
         return lastName;
            }

      public void setLastName(String newLastName) {
         lastName = newLastName;
            }

      public String getPassword() {
         return password;
    }

      public void setPassword(String newPassword) {
         password = newPassword;
    }

      public String getUsername() {
         return username;
            }

      public void setUserName(String newUsername) {
         username = newUsername;
            }

      public boolean isValid() {
         return valid;
    }

      public void setValid(boolean newValid) {
         valid = newValid;
    }
}
</code>```

UserDAO.java

```<code>package ExamplePackage;

   import java.text.*;
   import java.util.*;
   import java.sql.*;

   public class UserDAO
   {
      static Connection currentCon = null;
      static ResultSet rs = null;

      public static UserBean login(UserBean bean) {

         //preparing some objects for connection
         Statement stmt = null;

         String username = bean.getUsername();
         String password = bean.getPassword();

         String searchQuery =
               "select * from users where username='"
                        + username
                        + "' AND password='"
                        + password
                        + "'";

      // "System.out.println" prints in the console; Normally used to trace the process
      System.out.println("Your user name is " + username);
      System.out.println("Your password is " + password);
      System.out.println("Query: "+searchQuery);

      try
      {
         //connect to DB
         currentCon = ConnectionManager.getConnection();
         stmt=currentCon.createStatement();
         rs = stmt.executeQuery(searchQuery);
         boolean more = rs.next();

         // if user does not exist set the isValid variable to false
         if (!more)
         {
            System.out.println("Sorry, you are not a registered user! Please sign up first");
            bean.setValid(false);
         }

         //if user exists set the isValid variable to true
         else if (more)
         {
            String firstName = rs.getString("FirstName");
            String lastName = rs.getString("LastName");

            System.out.println("Welcome " + firstName);
            bean.setFirstName(firstName);
            bean.setLastName(lastName);
            bean.setValid(true);
         }
      }

      catch (Exception ex)
      {
         System.out.println("Log In failed: An Exception has occurred! " + ex);
      }

      //some exception handling
      finally
      {
         if (rs != null)    {
            try {
               rs.close();
            } catch (Exception e) {}
               rs = null;
            }

         if (stmt != null) {
            try {
               stmt.close();
            } catch (Exception e) {}
               stmt = null;
            }

         if (currentCon != null) {
            try {
               currentCon.close();
            } catch (Exception e) {
            }

            currentCon = null;
         }
      }

return bean;

      }
   }
</code>```

ConnectionManager.java

```<code>package ExamplePackage;

import java.sql.*;
import java.util.*;

   public class ConnectionManager {

      static Connection con;
      static String url;

      public static Connection getConnection()
      {

         try
         {
            String url = "jdbc:odbc:" + "logindb";
            // assuming "DataSource" is your DataSource name

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            try
            {
               con = DriverManager.getConnection(url,"root","root");

            // assuming your SQL Server's   username is "username"
            // and password is "password"

            }

            catch (SQLException ex)
            {
               ex.printStackTrace();
            }
         }

         catch(ClassNotFoundException e)
         {
            System.out.println(e);
         }

      return con;
}
   }
</code>```

Error:

HTTP Status [404] – [Not Found]

Type Status Report

Message /LoginExample/LoginServlet

Description The origin server did not find a current representation
  for the target resource or is not willing to disclose that one exists.

Apache Tomcat/9.0.0.M21

答:
in your jsp page, the form is mapped on the url-pattern "LoginServlet" servlet:

```<code><form action="LoginServlet">
</code>```

The error is because in your web.xml file in WEB-INF, the LoginServlet is mapped onto something else. If you want it to work, you need to specify this in the web.xml:

```<code>  <servlet>
    <description>LoginServlet</description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>yourpackagename.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
</code>```

Title: JSP Login page not working

Body:
I'm trying to create a login page for a site (I'm using a tutorial right now - never done this before).  When I go to use the "login" page, it pops a 404 error.  Here is the code.

LoginPage.jsp

<%@ page language="java"
    contentType="text/html; charset=windows-1256"
    pageEncoding="windows-1256"
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
        <title>Login Page</title>

        <form action="LoginServlet">

            Please enter your username
            <input type="text" name="un"/>

            Please enter your password
            <input type="text" name="pw"/>

            <input type="submit" value="submit">

        </form>

LoginServlet.java

package ExamplePackage;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
                       throws ServletException, java.io.IOException {

try
{

     UserBean user = new UserBean();
     user.setUserName(request.getParameter("un"));
     user.setPassword(request.getParameter("pw"));

     user = UserDAO.login(user);

     if (user.isValid())
     {

          HttpSession session = request.getSession(true);
          session.setAttribute("currentSessionUser",user);
          response.sendRedirect("userLogged.jsp"); //logged-in page
     }

     else
          response.sendRedirect("invalidLogin.jsp"); //error page
}

catch (Throwable theException)
{
     System.out.println(theException);
}
       }
    }

UserBean.Java

package ExamplePackage;

public class UserBean {

      private String username;
      private String password;
      private String firstName;
      private String lastName;
      public boolean valid;

      public String getFirstName() {
         return firstName;
    }

      public void setFirstName(String newFirstName) {
         firstName = newFirstName;
    }

      public String getLastName() {
         return lastName;
            }

      public void setLastName(String newLastName) {
         lastName = newLastName;
            }

      public String getPassword() {
         return password;
    }

      public void setPassword(String newPassword) {
         password = newPassword;
    }

      public String getUsername() {
         return username;
            }

      public void setUserName(String newUsername) {
         username = newUsername;
            }

      public boolean isValid() {
         return valid;
    }

      public void setValid(boolean newValid) {
         valid = newValid;
    }
}

UserDAO.java

package ExamplePackage;

   import java.text.*;
   import java.util.*;
   import java.sql.*;

   public class UserDAO
   {
      static Connection currentCon = null;
      static ResultSet rs = null;

      public static UserBean login(UserBean bean) {

         //preparing some objects for connection
         Statement stmt = null;

         String username = bean.getUsername();
         String password = bean.getPassword();

         String searchQuery =
               "select * from users where username='"
                        + username
                        + "' AND password='"
                        + password
                        + "'";

      // "System.out.println" prints in the console; Normally used to trace the process
      System.out.println("Your user name is " + username);
      System.out.println("Your password is " + password);
      System.out.println("Query: "+searchQuery);

      try
      {
         //connect to DB
         currentCon = ConnectionManager.getConnection();
         stmt=currentCon.createStatement();
         rs = stmt.executeQuery(searchQuery);
         boolean more = rs.next();

         // if user does not exist set the isValid variable to false
         if (!more)
         {
            System.out.println("Sorry, you are not a registered user! Please sign up first");
            bean.setValid(false);
         }

         //if user exists set the isValid variable to true
         else if (more)
         {
            String firstName = rs.getString("FirstName");
            String lastName = rs.getString("LastName");

            System.out.println("Welcome " + firstName);
            bean.setFirstName(firstName);
            bean.setLastName(lastName);
            bean.setValid(true);
         }
      }

      catch (Exception ex)
      {
         System.out.println("Log In failed: An Exception has occurred! " + ex);
      }

      //some exception handling
      finally
      {
         if (rs != null)    {
            try {
               rs.close();
            } catch (Exception e) {}
               rs = null;
            }

         if (stmt != null) {
            try {
               stmt.close();
            } catch (Exception e) {}
               stmt = null;
            }

         if (currentCon != null) {
            try {
               currentCon.close();
            } catch (Exception e) {
            }

            currentCon = null;
         }
      }

return bean;

      }
   }

ConnectionManager.java

package ExamplePackage;

import java.sql.*;
import java.util.*;

   public class ConnectionManager {

      static Connection con;
      static String url;

      public static Connection getConnection()
      {

         try
         {
            String url = "jdbc:odbc:" + "logindb";
            // assuming "DataSource" is your DataSource name

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            try
            {
               con = DriverManager.getConnection(url,"root","root");

            // assuming your SQL Server's   username is "username"
            // and password is "password"

            }

            catch (SQLException ex)
            {
               ex.printStackTrace();
            }
         }

         catch(ClassNotFoundException e)
         {
            System.out.println(e);
         }

      return con;
}
   }

Error:

HTTP Status [404] – [Not Found]

Type Status Report

Message /LoginExample/LoginServlet

Description The origin server did not find a current representation
  for the target resource or is not willing to disclose that one exists.

Apache Tomcat/9.0.0.M21

Body:
in your jsp page, the form is mapped on the url-pattern "LoginServlet" servlet:

<form action="LoginServlet">

The error is because in your web.xml file in WEB-INF, the LoginServlet is mapped onto something else. If you want it to work, you need to specify this in the web.xml:

  <servlet>
    <description>LoginServlet</description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>yourpackagename.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>


问:
com.github.tomakehurst.wiremock.client.VerificationException: Expected status 201 for http://localhost:8080/__admin/mappings/new but was 404
This is my Test Class:

```<code>public class CompanionDevicesRestServiceTest {

    public static ComDevicesRestService comDevicesRestService;
    public static IComDevices cdevicesService;
    public static ComDevices cdevicesRequest;

    @BeforeClass
    public static void init(){
        cdevicesService = new StubComDevicesService();
        comDevicesRestService = new ComDevicesRestService(cdevicesService);
        cdevicesRequest = mock(ComDevices.class);
    }

    @Test
    public void testPostCdevices() throws JsonProcessingException{
        WireMock.stubFor(WireMock.post(WireMock.urlEqualTo("/cdevices"))
                  .withHeader("Accept", WireMock.equalTo("application/json"))
                   .willReturn(WireMock.aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("Some content")));

    }
}
</code>```

I am getting the following error :

com.github.tomakehurst.wiremock.client.VerificationException: Expected status 201 for http://localhost:8080/__admin/mappings/new but was 404
          at com.github.tomakehurst.wiremock.client.HttpAdminClient.postJsonAssertOkAndReturnBody(HttpAdminClient.java:156)
          at com.github.tomakehurst.wiremock.client.HttpAdminClient.addStubMapping(HttpAdminClient.java:65)
          at com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:138)
          at com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:134)
          at com.github.tomakehurst.wiremock.client.WireMock.givenThat(WireMock.java:65)
          at com.github.tomakehurst.wiremock.client.WireMock.stubFor(WireMock.java:69)
          at com.charter.cdevices.rest.CompanionDevicesRestServiceTest.testPostCdevices(CompanionDevicesRestServiceTest.java:33)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
          at java.lang.reflect.Method.invoke(Unknown Source)
          at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
          at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
          at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
          at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
          at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
          at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
          at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
          at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
          at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
          at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
          at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
          at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
          at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
          at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
          at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
          at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
          at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
          at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
          at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
          at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

答:
For this example, I suppose the wiremock was started externally,right? So you should add the configure for with the host and the port:</p>

```<code>configureFor("localhost", 8080);
</code>```

Body:
This is my Test Class:

public class CompanionDevicesRestServiceTest {

    public static ComDevicesRestService comDevicesRestService;
    public static IComDevices cdevicesService;
    public static ComDevices cdevicesRequest;

    @BeforeClass
    public static void init(){
        cdevicesService = new StubComDevicesService();
        comDevicesRestService = new ComDevicesRestService(cdevicesService);
        cdevicesRequest = mock(ComDevices.class);
    }

    @Test
    public void testPostCdevices() throws JsonProcessingException{
        WireMock.stubFor(WireMock.post(WireMock.urlEqualTo("/cdevices"))
                  .withHeader("Accept", WireMock.equalTo("application/json"))
                   .willReturn(WireMock.aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("Some content")));

    }
}

I am getting the following error :

com.github.tomakehurst.wiremock.client.VerificationException: Expected status 201 for http://localhost:8080/__admin/mappings/new but was 404
          at com.github.tomakehurst.wiremock.client.HttpAdminClient.postJsonAssertOkAndReturnBody(HttpAdminClient.java:156)
          at com.github.tomakehurst.wiremock.client.HttpAdminClient.addStubMapping(HttpAdminClient.java:65)
          at com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:138)
          at com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:134)
          at com.github.tomakehurst.wiremock.client.WireMock.givenThat(WireMock.java:65)
          at com.github.tomakehurst.wiremock.client.WireMock.stubFor(WireMock.java:69)
          at com.charter.cdevices.rest.CompanionDevicesRestServiceTest.testPostCdevices(CompanionDevicesRestServiceTest.java:33)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
          at java.lang.reflect.Method.invoke(Unknown Source)
          at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
          at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
          at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
          at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
          at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
          at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
          at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
          at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
          at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
          at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
          at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
          at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
          at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
          at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
          at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
          at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
          at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
          at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
          at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
          at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Body:
For this example, I suppose the wiremock was started externally,right? So you should add the configure for with the host and the port:

configureFor("localhost", 8080);


问:
sorting list in python accoeding to one dimension

Possible Duplicate:

  Sorting a tuple that contains tuples

hi

I have a list that goes A=[[a,'3'],[g,'1'],[y,2]]

I am looking for a quick way to arrange it according to the numbers (second dimension), so

NewA=[[g,'1'],[y,'2'],[a,'3']]

thanks

ariel

答:
```<code>from operator import itemgetter
newA = sorted(a, key=itemgetter(1))
</code>```


问:
How do I do a simple HTTP request against the dataflow API on gcloud with node?
I want to monitor my dataflow jobs with an application. The application I'm developing is a nodejs application and ideally it would exist a package like @google-cloud/bigquery but for dataflow instead. I'm fully aware that I might not be able to start job, if it is not a template job, but it should be an easy way to list jobs or get job information.

Update:

I found this spec, https://dataflow.googleapis.com/$discovery/rest?version=v1b3, but I don't understand what location is for the list operation. The spec was linked from this page: https://cloud.google.com/dataflow/docs/reference/rest/

答:
I did find the solution myself. There is a repo that basically has all the APIs for gcloud out there: https://github.com/google/google-api-nodejs-client

After I found that I could easily do what I wanted:

```<code>'use strict';

var google = require('googleapis');
var dataflow = google.dataflow('v1b3');

google.auth.getApplicationDefault(function (err, authClient, projectId) {
    if (err) {
        throw err;
    }

    // The createScopedRequired method returns true when running on GAE or a local developer
    // machine. In that case, the desired scopes must be passed in manually. When the code is
    // running in GCE or a Managed VM, the scopes are pulled from the GCE metadata server.
    // See https://cloud.google.com/compute/docs/authentication for more information.
    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
        // Scopes can be specified either as an array or as a single, space-delimited string.
        authClient = authClient.createScoped([
            'https://www.googleapis.com/auth/compute'
        ]);
    }

    // Fetch the list of GCE zones within a project.
    // NOTE: You must fill in your valid project ID before running this sample!
    var compute = google.compute({
        version: 'v1',
        auth: authClient
    });

    var result = dataflow.projects.jobs.list({
        'projectId': projectId,
        'auth': authClient
    }, function (err, result) {
        console.log(err, result);
    });
});
</code>```

Body:
I did find the solution myself. There is a repo that basically has all the APIs for gcloud out there: https://github.com/google/google-api-nodejs-client

After I found that I could easily do what I wanted:

'use strict';

var google = require('googleapis');
var dataflow = google.dataflow('v1b3');

google.auth.getApplicationDefault(function (err, authClient, projectId) {
    if (err) {
        throw err;
    }

    // The createScopedRequired method returns true when running on GAE or a local developer
    // machine. In that case, the desired scopes must be passed in manually. When the code is
    // running in GCE or a Managed VM, the scopes are pulled from the GCE metadata server.
    // See https://cloud.google.com/compute/docs/authentication for more information.
    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
        // Scopes can be specified either as an array or as a single, space-delimited string.
        authClient = authClient.createScoped([
            'https://www.googleapis.com/auth/compute'
        ]);
    }

    // Fetch the list of GCE zones within a project.
    // NOTE: You must fill in your valid project ID before running this sample!
    var compute = google.compute({
        version: 'v1',
        auth: authClient
    });

    var result = dataflow.projects.jobs.list({
        'projectId': projectId,
        'auth': authClient
    }, function (err, result) {
        console.log(err, result);
    });
});


问:
Disabled other select if value equal to 1
I have dynamic select option. Only 0 and 1 user can select.

If user select value = 1, I want disable other select & keep current.

If user select value = 0 from current option so other select enable again.

HTML

```<code>A :
<select name="quantity[1]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
B :
<select name="quantity[2]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
C:
<select name="quantity[3]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
</code>```

jQuery

```<code>$(document).on('change keyup keypress', '.trigger', function() {
  $(".quantity").prop("disabled", true);

  $('.quantity option:selected').each(function() {
    quantity += parseInt($(this).val()) || 0;
    if (quantity == 1) {
      $(this).prop("disabled", false);
    } else {
      $(this).prop("disabled", true);
    }
  });
});
</code>```

https://jsfiddle.net/qq1q6orw/2/

答:
Here is a sample example:

$(document).on('change keyup keypress', '.trigger', function() {
  var flag = $(this).val() == 1;
  $(".quantity").not(this).prop("disabled", flag);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
A :
<select name="quantity[1]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select> B :
<select name="quantity[2]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select> C:
<select name="quantity[3]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select></code>```

Body:
I have dynamic select option. Only 0 and 1 user can select.

If user select value = 1, I want disable other select & keep current.

If user select value = 0 from current option so other select enable again.

HTML

A :
<select name="quantity[1]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
B :
<select name="quantity[2]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
C:
<select name="quantity[3]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>

jQuery

$(document).on('change keyup keypress', '.trigger', function() {
  $(".quantity").prop("disabled", true);

  $('.quantity option:selected').each(function() {
    quantity += parseInt($(this).val()) || 0;
    if (quantity == 1) {
      $(this).prop("disabled", false);
    } else {
      $(this).prop("disabled", true);
    }
  });
});

https://jsfiddle.net/qq1q6orw/2/

Body:
Here is a sample example:

$(document).on('change keyup keypress', '.trigger', function() {
  var flag = $(this).val() == 1;
  $(".quantity").not(this).prop("disabled", flag);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
A :
<select name="quantity[1]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select> B :
<select name="quantity[2]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select> C:
<select name="quantity[3]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>


问:
Data Objects from $.ajax with json are shallow
I've got a JSON looking like this (design might be wrong)

```<code>{
  "Supermarkt": {
    "name": "Supermarkt",
    "translations": {
      "trolley": "Einkaufswagen",
      "vegetables": "Gemüse",
      "cocoa": "Kakao",
      "chocolate": "Schokolade"
    },
    "pronunciations": []
  },
  "Script1336Kidee": {
    "name": "Script1336Kidee",
    "translations": {
      "Trojaner": "RAT",
      "Laufzeit-Packer": "Magie",
      "PHP": "Der letzte Dreck",
      "JavaScript": "Wild-West"
    },
    "pronunciations": []
  }
}
</code>```

Which I get with a ajax call (already JSON-decoded through dataType: "json" $.ajax option):

```<code>let lessonCall = $.ajax("https://www2.htw-dresden.de/~s70357/vokabel.php/",{dataType: "json"});
lessonCall.fail((jqXHR, status, error) => {
    console.log(status);
    console.log(error);
});
lessonCall.done((data,status) => {
    console.log(status);
    console.log(data);
    for (let lesson in data){
        console.log(lesson);
        console.log(lesson.name);
    }
});
</code>```

Problem is lesson.name is undefined although console.log(data); show the healthy data Object with the healthy subsub-Objects, but lesson seems to be just a string-like thing.

How can I iterate through my "name"s?!

答:
Try this:</p>

```<code>for (let i in data){
    let lesson = data[i];
    console.log(lesson);
    console.log(lesson.name);
}
</code>```

Body:
I've got a JSON looking like this (design might be wrong)

{
  "Supermarkt": {
    "name": "Supermarkt",
    "translations": {
      "trolley": "Einkaufswagen",
      "vegetables": "Gemüse",
      "cocoa": "Kakao",
      "chocolate": "Schokolade"
    },
    "pronunciations": []
  },
  "Script1336Kidee": {
    "name": "Script1336Kidee",
    "translations": {
      "Trojaner": "RAT",
      "Laufzeit-Packer": "Magie",
      "PHP": "Der letzte Dreck",
      "JavaScript": "Wild-West"
    },
    "pronunciations": []
  }
}

Which I get with a ajax call (already JSON-decoded through dataType: "json" $.ajax option):

let lessonCall = $.ajax("https://www2.htw-dresden.de/~s70357/vokabel.php/",{dataType: "json"});
lessonCall.fail((jqXHR, status, error) => {
    console.log(status);
    console.log(error);
});
lessonCall.done((data,status) => {
    console.log(status);
    console.log(data);
    for (let lesson in data){
        console.log(lesson);
        console.log(lesson.name);
    }
});

Problem is lesson.name is undefined although console.log(data); show the healthy data Object with the healthy subsub-Objects, but lesson seems to be just a string-like thing.

How can I iterate through my "name"s?!

Body:
Try this:

for (let i in data){
    let lesson = data[i];
    console.log(lesson);
    console.log(lesson.name);
}


问:
R datatable in DT the shiny filter "none" option doesn't work
I have just switched to using dataTables in my shiny app. In the ui, I have dataTableOutput("affordabilityTable") in a mainPanel and the following renderDataTable in the server

```<code>output$affordabilityTable <- renderDataTable({
    dt <- data.table::copy(data.afford())
    dt <- DT::datatable(dt, options = list(autoHideNavigation = TRUE, rownames = FALSE, filter = "none"))
#   dt <- DT::datatable(dt, options = list(dom = 't',ordering = F))
dt
})
</code>```

The commented code works, in the sense that it turns off filtering, column sorting, etc. It does leave row numbers in the first column which I can't figure out how to get rid of. The uncommented datatable line leaves all the filter features showing.

The code I have included is not complete enough to reproduce the problem with row numbers but I'm hoping there is some fix that is obvious to someone with some datatable experience.

答:
rownames parameter is part of datatable call, not inside the options. Or more specifically

```<code>dt <- DT::datatable(dt, rownames = FALSE, options = list(dom = 't',ordering = F))
</code>```

I knew this is confusing. You can think that the options are the original js module datatable parameters, while there are some other parameters added by DT::datatable.

Body:
I have just switched to using dataTables in my shiny app. In the ui, I have dataTableOutput("affordabilityTable") in a mainPanel and the following renderDataTable in the server

output$affordabilityTable <- renderDataTable({
    dt <- data.table::copy(data.afford())
    dt <- DT::datatable(dt, options = list(autoHideNavigation = TRUE, rownames = FALSE, filter = "none"))
#   dt <- DT::datatable(dt, options = list(dom = 't',ordering = F))
dt
})

The commented code works, in the sense that it turns off filtering, column sorting, etc. It does leave row numbers in the first column which I can't figure out how to get rid of. The uncommented datatable line leaves all the filter features showing.

The code I have included is not complete enough to reproduce the problem with row numbers but I'm hoping there is some fix that is obvious to someone with some datatable experience.

Body:
rownames parameter is part of datatable call, not inside the options. Or more specifically

dt <- DT::datatable(dt, rownames = FALSE, options = list(dom = 't',ordering = F))

I knew this is confusing. You can think that the options are the original js module datatable parameters, while there are some other parameters added by DT::datatable.


问:
How to limit the number of words in a textarea in summernote
I'm trying to limit the number of words allowed in a summernote.

example, I want to limit up to 50 words only.

Do you have any idea?

```<code>$(document).ready(function() {
    $('#summernote').summernote({
        height: 20,
   });
});
</code>```

答:
Thought I would contribute to this post as this helped me arrive to my desired solution.  It seems the suggested answer has not been accepted.

I created a variable for maxLength and the following is how I configured summernote callbacks.  Please note the version of summernote I am using has the editing area as .note-editable.  The solution below is typescript and I have a span that I target which displays the remaining character count.

```<code>callbacks: {
onKeydown(e) {

  // The text method will ignore HTML tags and preserve non-breaking
  // space allowing for a true character count

  let content: string = $('.note-editable').text();

  // This checks if the character is alphanumeric (i.e. not a backspace or return key)

  let isCharacter: boolean = (/[a-zA-Z0-9-_ ]/.test(String.fromCharCode(e.keyCode)));

  // If the current content length is at max, preventDefault will disallow
  // any more characters

  if (isCharacter) {
    if (content.length >= maxLength) {
      e.preventDefault();
    }
  }
},
onKeyup(e) {

  // After the result of checking the character and max length exceeded,
  // take the resulting count and determine and display characters remaining

  let content: string = $('.note-editable').text();
  let charactersRemaining: number = maxLength - content.length;
  $('#SomeDivId span').text(charactersRemaining);
}
</code>```

Body:
I'm trying to limit the number of words allowed in a summernote.

example, I want to limit up to 50 words only.

Do you have any idea?

$(document).ready(function() {
    $('#summernote').summernote({
        height: 20,
   });
});

Body:
Thought I would contribute to this post as this helped me arrive to my desired solution.  It seems the suggested answer has not been accepted.

I created a variable for maxLength and the following is how I configured summernote callbacks.  Please note the version of summernote I am using has the editing area as .note-editable.  The solution below is typescript and I have a span that I target which displays the remaining character count.

callbacks: {
onKeydown(e) {

  // The text method will ignore HTML tags and preserve non-breaking
  // space allowing for a true character count

  let content: string = $('.note-editable').text();

  // This checks if the character is alphanumeric (i.e. not a backspace or return key)

  let isCharacter: boolean = (/[a-zA-Z0-9-_ ]/.test(String.fromCharCode(e.keyCode)));

  // If the current content length is at max, preventDefault will disallow
  // any more characters

  if (isCharacter) {
    if (content.length >= maxLength) {
      e.preventDefault();
    }
  }
},
onKeyup(e) {

  // After the result of checking the character and max length exceeded,
  // take the resulting count and determine and display characters remaining

  let content: string = $('.note-editable').text();
  let charactersRemaining: number = maxLength - content.length;
  $('#SomeDivId span').text(charactersRemaining);
}


问:
C - fscanf error with char *
I'm trying to read a txt file with this format:

```<code>8590 2 07 Goku
8591 2 07 Vegeta
6973 2 07 Picolo
5432 3 02 Jerez
6773 3 02 Sour
4689 4 03 Mosco
6981 5 06 Cabba
7891 5 06 Frost
</code>```

The columns are: hp, universe color, universe number and name. What I do is this read the line and save the parameters in an array of structures called warrior with this format:

```<code>typedef struct Warrior{
    int hp;
    int color;
    int universe;
    char * name;
    int posX;
    int posY;
    int ki;
} warrior;

warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){
    warrior guerrero;
    guerrero.hp = inHp;
    guerrero.color = inColor;
    guerrero.universe = inUniverse;
    guerrero.name = inName;
    guerrero.posX= 0;
    guerrero.posY= 0;
    guerrero.ki=0;
    return guerrero;
}
</code>```

The readFile code is:

```<code>warrior * readFile(char * nameFile, warrior * listGuerrero){
    FILE * filePointer;
    int sizeFile = 0, ch = 0;
    int inHp, inColor, inUniverse;
    char inName[50];

    filePointer = fopen(nameFile, "r");

    while(fscanf(filePointer, "%d %d %d %s\n", &inHp, &inColor, &inUniverse, inName) != EOF){
        sizeFile ++;
    }

    rewind(filePointer);

    listGuerrero = (warrior *)malloc(sizeFile*sizeof(warrior));
    for(int k = 0; k < sizeFile; k++){
        fscanf(filePointer, "%d %d %d %s\n", &inHp, &inColor, &inUniverse, &inName[0]);
        listGuerrero[k] = createWarrior(inHp,inColor,inUniverse,inName);
        printf("k: %d - HP: %d - Color: %d - Universo: %d - Nombre: %s \n", k, listGuerrero[k].hp, listGuerrero[k].color, listGuerrero[k].universe, listGuerrero[k].name);
    }

    fclose(filePointer);
    return listGuerrero;
}
</code>```

But for some reason I can't understand, the final list of warriors all have the same name like:

```<code>j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Frost
j: 1 - HP: 8591 - Color: 2 - Universo: 7 - Nombre: Frost
j: 2 - HP: 6973 - Color: 2 - Universo: 7 - Nombre: Frost
j: 3 - HP: 5432 - Color: 3 - Universo: 2 - Nombre: Frost
j: 4 - HP: 6773 - Color: 3 - Universo: 2 - Nombre: Frost
j: 5 - HP: 4689 - Color: 4 - Universo: 3 - Nombre: Frost
j: 6 - HP: 6981 - Color: 5 - Universo: 6 - Nombre: Frost
j: 7 - HP: 7891 - Color: 5 - Universo: 6 - Nombre: Frost
</code>```

Is something wrong with the inName pointer?

When I debug, the first iteration prints:

```<code>j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Goku
</code>```

And the second iteration prints:

```<code>j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Vegeta
j: 1 - HP: 8591 - Color: 2 - Universo: 7 - Nombre: Vegeta
</code>```

and so on.

答:
All of your input from scanf is written to the same memory location given for inName[50]. In each iterration you are overwritting the content, but assigning the same address to the guerrero.name. And when you print out, you get last entry printed.

You may try this:

```<code>warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){
...
guerrero.name = strdup(inName);
....
return guerrero;
}
</code>```

Title: C - fscanf error with char *

Body:
I'm trying to read a txt file with this format:

8590 2 07 Goku
8591 2 07 Vegeta
6973 2 07 Picolo
5432 3 02 Jerez
6773 3 02 Sour
4689 4 03 Mosco
6981 5 06 Cabba
7891 5 06 Frost

The columns are: hp, universe color, universe number and name. What I do is this read the line and save the parameters in an array of structures called warrior with this format:

typedef struct Warrior{
    int hp;
    int color;
    int universe;
    char * name;
    int posX;
    int posY;
    int ki;
} warrior;

warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){
    warrior guerrero;
    guerrero.hp = inHp;
    guerrero.color = inColor;
    guerrero.universe = inUniverse;
    guerrero.name = inName;
    guerrero.posX= 0;
    guerrero.posY= 0;
    guerrero.ki=0;
    return guerrero;
}

The readFile code is:

warrior * readFile(char * nameFile, warrior * listGuerrero){
    FILE * filePointer;
    int sizeFile = 0, ch = 0;
    int inHp, inColor, inUniverse;
    char inName[50];

    filePointer = fopen(nameFile, "r");

    while(fscanf(filePointer, "%d %d %d %s\n", &inHp, &inColor, &inUniverse, inName) != EOF){
        sizeFile ++;
    }

    rewind(filePointer);

    listGuerrero = (warrior *)malloc(sizeFile*sizeof(warrior));
    for(int k = 0; k < sizeFile; k++){
        fscanf(filePointer, "%d %d %d %s\n", &inHp, &inColor, &inUniverse, &inName[0]);
        listGuerrero[k] = createWarrior(inHp,inColor,inUniverse,inName);
        printf("k: %d - HP: %d - Color: %d - Universo: %d - Nombre: %s \n", k, listGuerrero[k].hp, listGuerrero[k].color, listGuerrero[k].universe, listGuerrero[k].name);
    }

    fclose(filePointer);
    return listGuerrero;
}

But for some reason I can't understand, the final list of warriors all have the same name like:

j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Frost
j: 1 - HP: 8591 - Color: 2 - Universo: 7 - Nombre: Frost
j: 2 - HP: 6973 - Color: 2 - Universo: 7 - Nombre: Frost
j: 3 - HP: 5432 - Color: 3 - Universo: 2 - Nombre: Frost
j: 4 - HP: 6773 - Color: 3 - Universo: 2 - Nombre: Frost
j: 5 - HP: 4689 - Color: 4 - Universo: 3 - Nombre: Frost
j: 6 - HP: 6981 - Color: 5 - Universo: 6 - Nombre: Frost
j: 7 - HP: 7891 - Color: 5 - Universo: 6 - Nombre: Frost

Is something wrong with the inName pointer?

When I debug, the first iteration prints:

j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Goku

And the second iteration prints:

j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Vegeta
j: 1 - HP: 8591 - Color: 2 - Universo: 7 - Nombre: Vegeta

and so on.

Body:
All of your input from scanf is written to the same memory location given for inName[50]. In each iterration you are overwritting the content, but assigning the same address to the guerrero.name. And when you print out, you get last entry printed.

You may try this:

warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){
...
guerrero.name = strdup(inName);
....
return guerrero;
}


问:
Batch Rename Classes in Entity Framework Database First
Is it possible to batch rename the Class (Entity) names in auto generated .cs files inside edmx model? I need to have uppercase first letter for all the entities e.g. "account" needs to be changed to "Account".

```<code>partial class account
    {
        public long id { get; set; }
        public int idPartner { get; set; }
        public string accountName { get; set; }
    }
</code>```

Visual Studio has been generating lower case names for MySql tables used in the project which has been deployed in production & the table names cannot be changed.
I know that mappings can be changed using property window in edmx designer but it is not useful in this case because of so many tables. Is there a tool which can do this? If there is none, then what are the exact steps to modify the edmx & other files so that I can create a tool for batch modification of all the entities?

答:
I'm not sure whether Entity Framework 6 has improved the situation over EF 5.  I had a similar issue a while back with EF 5 and found a solution wherein I was able to successfully transform the VS-generated EDMX.  Basically, it's a console app that takes in an EDMX file and transforms it.

I merely (successfully) used the tool.  You'll find the original with notes here: https://www.tabsoverspaces.com/233202-changing-entity-names-i-e-removing-prefix-in-entity-frameworks-edmx-in-batch/

Credit to Jiří Činčura (www.tabsoverspaces.com)

Below is the code:

```<code>static void TransformEDMXEntities(string inputFile, string outputFile)
{
    XDocument xdoc = XDocument.Load(inputFile);

    const string CSDLNamespace = "http://schemas.microsoft.com/ado/2009/11/edm";
    const string MSLNamespace = "http://schemas.microsoft.com/ado/2009/11/mapping/cs";
    const string DesignerNamespace = "http://schemas.microsoft.com/ado/2009/11/edmx";
    XElement csdl = xdoc.Descendants(XName.Get("Schema", CSDLNamespace)).First();
    XElement msl = xdoc.Descendants(XName.Get("Mapping", MSLNamespace)).First();
    XElement designerDiagram = xdoc.Descendants(XName.Get("Designer", DesignerNamespace)).First();

    Func<string, string> transformation = (string input) =>
    {
        const string PREFIX = "tbl";
        Regex re = new Regex(string.Format(@"{0}(\w+)", Regex.Escape(PREFIX)), RegexOptions.None);
        return re.Replace(input, new MatchEvaluator(
            (Match m) =>
            {
                return m.Groups[1].Value;
            }));
    };

    TransformCSDL(CSDLNamespace, csdl, transformation);
    TransformMSL(MSLNamespace, msl, transformation);
    TransformDesigner(DesignerNamespace, designerDiagram, transformation);

    using (XmlTextWriter writer = new XmlTextWriter(outputFile, Encoding.Default))
    {
        xdoc.WriteTo(writer);
    }
}

static void TransformDesigner(string DesignerNamespace, XElement designerDiagram, Func<string, string> transformation)
{
    foreach (var item in designerDiagram.Elements(XName.Get("EntityTypeShape", DesignerNamespace)))
    {
        item.Attribute("EntityType").Value = transformation(item.Attribute("EntityType").Value);
    }
}

static void TransformMSL(string MSLNamespace, XElement msl, Func<string, string> transformation)
{
    foreach (var entitySetMapping in msl.Element(XName.Get("EntityContainerMapping", MSLNamespace)).Elements(XName.Get("EntitySetMapping", MSLNamespace)))
    {
        entitySetMapping.Attribute("Name").Value = transformation(entitySetMapping.Attribute("Name").Value);
        foreach (var entityTypeMapping in entitySetMapping.Elements(XName.Get("EntityTypeMapping", MSLNamespace)))
        {
            entityTypeMapping.Attribute("TypeName").Value = transformation(entityTypeMapping.Attribute("TypeName").Value);
        }
    }
}

static void TransformCSDL(string CSDLNamespace, XElement csdl, Func<string, string> transformation)
{
    foreach (var entitySet in csdl.Element(XName.Get("EntityContainer", CSDLNamespace)).Elements(XName.Get("EntitySet", CSDLNamespace)))
    {
        entitySet.Attribute("Name").Value = transformation(entitySet.Attribute("Name").Value);
        entitySet.Attribute("EntityType").Value = transformation(entitySet.Attribute("EntityType").Value);
    }
    foreach (var associationSet in csdl.Element(XName.Get("EntityContainer", CSDLNamespace)).Elements(XName.Get("AssociationSet", CSDLNamespace)))
    {
        foreach (var end in associationSet.Elements(XName.Get("End", CSDLNamespace)))
        {
            end.Attribute("EntitySet").Value = transformation(end.Attribute("EntitySet").Value);
        }
    }

    foreach (var entityType in csdl.Elements(XName.Get("EntityType", CSDLNamespace)))
    {
        entityType.Attribute("Name").Value = transformation(entityType.Attribute("Name").Value);
    }
    foreach (var association in csdl.Elements(XName.Get("Association", CSDLNamespace)))
    {
        foreach (var end in association.Elements(XName.Get("End", CSDLNamespace)))
        {
            end.Attribute("Type").Value = transformation(end.Attribute("Type").Value);
        }
    }
}
</code>```

Body:
Is it possible to batch rename the Class (Entity) names in auto generated .cs files inside edmx model? I need to have uppercase first letter for all the entities e.g. "account" needs to be changed to "Account".

partial class account
    {
        public long id { get; set; }
        public int idPartner { get; set; }
        public string accountName { get; set; }
    }

Visual Studio has been generating lower case names for MySql tables used in the project which has been deployed in production & the table names cannot be changed.
I know that mappings can be changed using property window in edmx designer but it is not useful in this case because of so many tables. Is there a tool which can do this? If there is none, then what are the exact steps to modify the edmx & other files so that I can create a tool for batch modification of all the entities?

Body:
I'm not sure whether Entity Framework 6 has improved the situation over EF 5.  I had a similar issue a while back with EF 5 and found a solution wherein I was able to successfully transform the VS-generated EDMX.  Basically, it's a console app that takes in an EDMX file and transforms it.

I merely (successfully) used the tool.  You'll find the original with notes here: https://www.tabsoverspaces.com/233202-changing-entity-names-i-e-removing-prefix-in-entity-frameworks-edmx-in-batch/

Credit to Jiří Činčura (www.tabsoverspaces.com)

Below is the code:

static void TransformEDMXEntities(string inputFile, string outputFile)
{
    XDocument xdoc = XDocument.Load(inputFile);

    const string CSDLNamespace = "http://schemas.microsoft.com/ado/2009/11/edm";
    const string MSLNamespace = "http://schemas.microsoft.com/ado/2009/11/mapping/cs";
    const string DesignerNamespace = "http://schemas.microsoft.com/ado/2009/11/edmx";
    XElement csdl = xdoc.Descendants(XName.Get("Schema", CSDLNamespace)).First();
    XElement msl = xdoc.Descendants(XName.Get("Mapping", MSLNamespace)).First();
    XElement designerDiagram = xdoc.Descendants(XName.Get("Designer", DesignerNamespace)).First();

    Func<string, string> transformation = (string input) =>
    {
        const string PREFIX = "tbl";
        Regex re = new Regex(string.Format(@"{0}(\w+)", Regex.Escape(PREFIX)), RegexOptions.None);
        return re.Replace(input, new MatchEvaluator(
            (Match m) =>
            {
                return m.Groups[1].Value;
            }));
    };

    TransformCSDL(CSDLNamespace, csdl, transformation);
    TransformMSL(MSLNamespace, msl, transformation);
    TransformDesigner(DesignerNamespace, designerDiagram, transformation);

    using (XmlTextWriter writer = new XmlTextWriter(outputFile, Encoding.Default))
    {
        xdoc.WriteTo(writer);
    }
}

static void TransformDesigner(string DesignerNamespace, XElement designerDiagram, Func<string, string> transformation)
{
    foreach (var item in designerDiagram.Elements(XName.Get("EntityTypeShape", DesignerNamespace)))
    {
        item.Attribute("EntityType").Value = transformation(item.Attribute("EntityType").Value);
    }
}

static void TransformMSL(string MSLNamespace, XElement msl, Func<string, string> transformation)
{
    foreach (var entitySetMapping in msl.Element(XName.Get("EntityContainerMapping", MSLNamespace)).Elements(XName.Get("EntitySetMapping", MSLNamespace)))
    {
        entitySetMapping.Attribute("Name").Value = transformation(entitySetMapping.Attribute("Name").Value);
        foreach (var entityTypeMapping in entitySetMapping.Elements(XName.Get("EntityTypeMapping", MSLNamespace)))
        {
            entityTypeMapping.Attribute("TypeName").Value = transformation(entityTypeMapping.Attribute("TypeName").Value);
        }
    }
}

static void TransformCSDL(string CSDLNamespace, XElement csdl, Func<string, string> transformation)
{
    foreach (var entitySet in csdl.Element(XName.Get("EntityContainer", CSDLNamespace)).Elements(XName.Get("EntitySet", CSDLNamespace)))
    {
        entitySet.Attribute("Name").Value = transformation(entitySet.Attribute("Name").Value);
        entitySet.Attribute("EntityType").Value = transformation(entitySet.Attribute("EntityType").Value);
    }
    foreach (var associationSet in csdl.Element(XName.Get("EntityContainer", CSDLNamespace)).Elements(XName.Get("AssociationSet", CSDLNamespace)))
    {
        foreach (var end in associationSet.Elements(XName.Get("End", CSDLNamespace)))
        {
            end.Attribute("EntitySet").Value = transformation(end.Attribute("EntitySet").Value);
        }
    }

    foreach (var entityType in csdl.Elements(XName.Get("EntityType", CSDLNamespace)))
    {
        entityType.Attribute("Name").Value = transformation(entityType.Attribute("Name").Value);
    }
    foreach (var association in csdl.Elements(XName.Get("Association", CSDLNamespace)))
    {
        foreach (var end in association.Elements(XName.Get("End", CSDLNamespace)))
        {
            end.Attribute("Type").Value = transformation(end.Attribute("Type").Value);
        }
    }
}


答:
There are a number of unnecessary selectors and there's unnecessary logic in your posted code. You can simply tell jQuery not to disable the active select using .not()

$(document).on('change keyup keypress', '.trigger', function() {

  var quantity = $(this).val();
  if (quantity == 1) {
    $('.quantity').not(this).prop("disabled", true);
  } else {
    $('.quantity').not(this).prop("disabled", false);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
A :
<select name="quantity[1]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
B :
<select name="quantity[2]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
C:
<select name="quantity[3]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select></code>```

Title: Disabled other select if value equal to 1

Body:
There are a number of unnecessary selectors and there's unnecessary logic in your posted code. You can simply tell jQuery not to disable the active select using .not()

$(document).on('change keyup keypress', '.trigger', function() {

  var quantity = $(this).val();
  if (quantity == 1) {
    $('.quantity').not(this).prop("disabled", true);
  } else {
    $('.quantity').not(this).prop("disabled", false);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
A :
<select name="quantity[1]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
B :
<select name="quantity[2]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
C:
<select name="quantity[3]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>

ContentLicense: CC BY-SA 4.0