问:
Decrypting Apple VAS Data received
I have sending data from NFC Pass to POS terminal where i have included encryptionPublicKey. I have been trying to decrypt the Apple VAS only Data received on NFC POS terminal.
i am not aware of these encryption and decryption processes.
Can anyone help on this to decrypt the data received?</p>

答: Public key goes into the pass.  Private key goes into the terminal or your payments app.</p>

Title: Decrypting Apple VAS Data received


来源: stackexchange

问:
How to bring ajax search onkeyup with jquery
My Script to call ajax

```<code><script language="javascript">
function search_func(value)
{
    $.ajax({
       type: "GET",
       url: "sample.php",
       data: {'search_keyword' : value},
       dataType: "text",
       success: function(msg){
                   //Receiving the result of search here
       }
    });
}
</script>
</code>```

HTML

```<code>   <input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
</code>```

Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.

For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.

When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.

Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.

I believe I had explained up to reader knowledge.

答:
Keep hold of the XMLHttpRequest object that $.ajax() returns and then on the next keyup, call .abort().  That should kill the previous ajax request and let you do the new one.

```<code>var req = null;

function search_func(value)
{
    if (req != null) req.abort();

    req = $.ajax({
        type: "GET",
        url: "sample.php",
        data: {'search_keyword' : value},
        dataType: "text",
        success: function(msg){
                    //Receiving the result of search here
        }
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My Script to call ajax

HTML

   <input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">

Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.

For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.

When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.

Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.

I believe I had explained up to reader knowledge.

Body:
Keep hold of the XMLHttpRequest object that $.ajax() returns and then on the next keyup, call .abort().  That should kill the previous ajax request and let you do the new one.

var req = null;

function search_func(value)
{
    if (req != null) req.abort();

    req = $.ajax({
        type: "GET",
        url: "sample.php",
        data: {'search_keyword' : value},
        dataType: "text",
        success: function(msg){
                    //Receiving the result of search here
        }
    });
}


问:
How to enable my python code to read from Arabic content in Excel?
I have two related problems. I'm working on Arabic dataset using Excel. I think that Excel somehow reads the contents as ؟؟؟؟؟ , because when I tried to replace this character '؟' with this '?' it replaces the whole text in the sheet. But when I replace or search for another letter it works.

Second, I'm trying to edit the sheet using python, but I'm unable to write Arabic letters (I'm using jGRASP). For example when I write the letter 'ل' it appears as 0644, and when I run the code this message appears : "ُError encoding text. Unable to encode text using charset windows-1252 ".

答:
0644 is the character code of the character in hex. jGRASP displays that when the font does not contain the character. You can use "Settings" > "Font" in jGRASP to choose a CSD font that contains the characters you need. Finding one that has those characters and also works well as a coding font might not be possible, so you may need to switch between two fonts.

jGRASP uses the system character encoding for loading and saving files by default. Windows-1252 is an 8-bit encoding used on English language Windows systems. You can use "File" > "Save As" to save the file with the same name but a different encoding (charset). Once you do that, jGRASP will remember it (per file) and you can load and save normally. Alternately, you can use "Settings" > "CSD Windows Settings" > "Workspace" and change the "Default Charset" setting to make the default something other than the system default.

ContentLicense: CC BY-SA 4.0


问:
What is the format for adding a compliance standard to an existing policy with the Prisma Cloud API?
I'm having trouble adding a Compliance Standard to an existing Policy via the Pal Alto Prisma Cloud API.

Everytime I send the request, I'm returned with a 500 Server Error (and, unfortunately, the API documentation is super unhelpful with this). I'm not sure if I'm sending the right information to add a compliance standard as the API documentation doesn't show what info needs to be sent. If I leave out required fields (name, policyType, and severity), I'm returned a 400 error (bad request, which makes sense). But I can't figure out why I keep getting the 500 Server Error.

In essence, my code looks like:

import requests

url = https://api2.redlock.io/policy/{policy_id}

header = {'Content-Type': 'application/json', 'x-redlock-auth': 'token'}

payload = {
    'name': 'policy_name',
    'policyType': 'policy_type',
    'severity': 'policy_severity',
    'complianceMetadata': [
        {
            'standardName': 'standard_name',
            'requirementId': 'requirement_ID',
            'sectionId': 'section_id'
        }
    ]
}

response = requests.request('PUT', url, json=payload, header=header)
```

The response should be a 200 with the policy's metadata returned in JSON format with the new compliance standard.

答:
For those using the RedLock API, I managed to figure it out.

Though non-descriptive, 500 errors generally mean the JSON being sent to the server is incorrect. In this case, the payload was incorrect.

The correct JSON for updating a policy's compliance standard is:

req_header = {'Content-Type':'application/json','x-redlock-auth':jwt_token}

# This is a small function to get a policy by ID
policy = get_redlock_policy_by_ID(req_header, 'policy_ID')

new_standard =  {
         "standardName":"std-name",
         "requirementId":"1.1",
         "sectionId":"1.1.1",
         "customAssigned":true,
         "complianceId":"comp-id",
         "requirementName":"req-name"
      }

policy['complianceMetadata'].append(new_standard)

requests.put('{}/policy/{}'.format(REDLOCK_API_URL, policy['policyId']), json=policy, headers=req_header)
```

Body:
I'm having trouble adding a Compliance Standard to an existing Policy via the Pal Alto Prisma Cloud API.

Everytime I send the request, I'm returned with a 500 Server Error (and, unfortunately, the API documentation is super unhelpful with this). I'm not sure if I'm sending the right information to add a compliance standard as the API documentation doesn't show what info needs to be sent. If I leave out required fields (name, policyType, and severity), I'm returned a 400 error (bad request, which makes sense). But I can't figure out why I keep getting the 500 Server Error.

In essence, my code looks like:

import requests

url = https://api2.redlock.io/policy/{policy_id}

header = {'Content-Type': 'application/json', 'x-redlock-auth': 'token'}

payload = {
    'name': 'policy_name',
    'policyType': 'policy_type',
    'severity': 'policy_severity',
    'complianceMetadata': [
        {
            'standardName': 'standard_name',
            'requirementId': 'requirement_ID',
            'sectionId': 'section_id'
        }
    ]
}

response = requests.request('PUT', url, json=payload, header=header)

The response should be a 200 with the policy's metadata returned in JSON format with the new compliance standard.


问:
Looping an array together with a jquery hover function
I'm trying to... God, this is hard to explain.

I got an array called 'triggers' with these variables:

"#1_trigger","#2_trigger","#3_trigger"

And inside a jQuery each(), I create another variable called 'targets' that copies everything from 'triggers' and replaces all _trigger to _target. I then append the 'triggers' to anchor IDs, and 'targets' to hidden div IDs.

What I want to do, is this: When hovering a _trigger, the _target will show up. I've managed to make it work with only one variable, but not with multiple.

As I said, it's kind of hard to explain what I want to do in text, so here's a demo and my progress so far:
http://jsfiddle.net/WJWe3/6/

I've been stuck with this one for too many hours now, please help!

答:
here's how i would do this
http://jsfiddle.net/WJWe3/15/

```<code><div id="experiment">
    <p><a>test 1</a> <span class='hidden'>hidden 1</span></p>
    <p><a>test 2</a> <span class='hidden'>hidden 2</span></p>
    <p><a>test 3</a> <span class='hidden'>hidden 3</span></p>
</div>
</code>```

...

```<code>$('#experiment a').hover(
    function(){
        $(this).siblings('span').stop().fadeTo("normal",1);
    },
    function(){
        $(this).siblings('span').stop().fadeTo("normal",0);
    }
);
</code>```

Body:
here's how i would do this
http://jsfiddle.net/WJWe3/15/

<div id="experiment">
    <p><a>test 1</a> <span class='hidden'>hidden 1</span></p>
    <p><a>test 2</a> <span class='hidden'>hidden 2</span></p>
    <p><a>test 3</a> <span class='hidden'>hidden 3</span></p>
</div>

...

$('#experiment a').hover(
    function(){
        $(this).siblings('span').stop().fadeTo("normal",1);
    },
    function(){
        $(this).siblings('span').stop().fadeTo("normal",0);
    }
);


问:
Querying ArrayList return Index of Arraylist
I have a function which is not doing what I am expecting.

```<code>Private Function getIndexOfArrayList(arrlist As Array) As Integer
    For index As Integer = 0 To arrlist.Length - 1 Step 1
        If (arrlist(index).Equals(If((mscbpisdepaap.Text.ToString = mscbpisdepaap.SelectedItem.ToString), mscbpisdepaap.SelectedItem.ToString, String.Empty))) Then
            Return index

        End If

    Next
    Return -1

End Function
</code>```

The function should compare a set of arraylist with the equal property. And if this is true, it should return the index. If not, it should return -1

But this function is not doing what I am expecting, it always returns -1.

Did I make some mistakes with the ternary operator here?

If I am not doing that with the ternary operator, I got my correct index.

The function should give me the correct index, if there is no index, it should retrieve -1.

Can someone proofread that function please?

答:
Don't pass arrList as Array use String()

arrList is an unfortunate choice for your variable name. There is such a thing as an ArrayList although it is obsolete. Also the name of your Function is misleading; you are dealing with an array not ArrayList.

Remove the extra set of parenthesis in the outer If.
Don't call .ToString on a Text property, it is already a String.
There is another extra set of parenthesis around your inner If condition.

```<code>Private A() As String = {"Mathew", "Mark", "Luke", "John"}

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    Dim i = getIndexOfArray(A)
    Debug.Print(i.ToString)
End Sub

Private Function getIndexOfArray(arrlist As String()) As Integer
    For index As Integer = 0 To arrlist.Length - 1 Step 1
        If arrlist(index).Equals(If(ComboBox1.Text = ComboBox1.SelectedItem.ToString, ComboBox1.SelectedItem.ToString, String.Empty)) Then
            Return index
        End If
    Next
    Return -1
End Function

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ComboBox1.Items.AddRange(A)
End Sub
</code>```

Doesn't the SelectedItem always equal the Text property?

Body:
I have a function which is not doing what I am expecting.

Private Function getIndexOfArrayList(arrlist As Array) As Integer
    For index As Integer = 0 To arrlist.Length - 1 Step 1
        If (arrlist(index).Equals(If((mscbpisdepaap.Text.ToString = mscbpisdepaap.SelectedItem.ToString), mscbpisdepaap.SelectedItem.ToString, String.Empty))) Then
            Return index

        End If

    Next
    Return -1

End Function

The function should compare a set of arraylist with the equal property. And if this is true, it should return the index. If not, it should return -1

But this function is not doing what I am expecting, it always returns -1.

Did I make some mistakes with the ternary operator here?

If I am not doing that with the ternary operator, I got my correct index.

The function should give me the correct index, if there is no index, it should retrieve -1.

Can someone proofread that function please?

Body:
Don't pass arrList as Array use String()

arrList is an unfortunate choice for your variable name. There is such a thing as an ArrayList although it is obsolete. Also the name of your Function is misleading; you are dealing with an array not ArrayList.

Remove the extra set of parenthesis in the outer If.
Don't call .ToString on a Text property, it is already a String.
There is another extra set of parenthesis around your inner If condition.

Private A() As String = {"Mathew", "Mark", "Luke", "John"}

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    Dim i = getIndexOfArray(A)
    Debug.Print(i.ToString)
End Sub

Private Function getIndexOfArray(arrlist As String()) As Integer
    For index As Integer = 0 To arrlist.Length - 1 Step 1
        If arrlist(index).Equals(If(ComboBox1.Text = ComboBox1.SelectedItem.ToString, ComboBox1.SelectedItem.ToString, String.Empty)) Then
            Return index
        End If
    Next
    Return -1
End Function

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ComboBox1.Items.AddRange(A)
End Sub

Doesn't the SelectedItem always equal the Text property?


问:
Node.js https pem error: routines:PEM_read_bio:no start line
I am messing with login form right now with node.js, I tried creating a pem key and csr using

```<code>openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
</code>```

However I been getting errors for running node server.js

Here is my server.js

```<code>var http = require('http'),
    express = require('express'),
UserServer = require('./lib/user-server');

var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('./key.pem', 'utf8'),
  cert: fs.readFileSync('./csr.pem', 'utf8')
};

var app = express();

app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

var httpserver = http.createServer(app).listen('3004', '127.0.0.1');
var https_server = https.createServer(options, app).listen('3005', '127.0.0.1');
UserServer.listen(https_server);
</code>```

Here is the error

```<code>crypto.js:104
  if (options.cert) c.context.setCert(options.cert);
                          ^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
    at Object.exports.createCredentials (crypto.js:104:31)
    at Server (tls.js:1107:28)
    at new Server (https.js:35:14)
    at Object.exports.createServer (https.js:54:10)
</code>```

I tried running

```<code>openssl x509 -text -inform DER -in key.pem
</code>```

It gives

```<code>unable to load certificate
140735208206812:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319:
140735208206812:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=X509
</code>```

I am not exactly sure what does the error mean as my encryption file is .pem file already, so any help would be much appreciated.

Thanks

答:
For me the issues was I had the key and cert swapped.

```<code>var options = {
   key: fs.readFileSync('/etc/letsencrypt/live/mysite.com/privkey.pem'),
   cert: fs.readFileSync('/etc/letsencrypt/live/mysite.com/fullchain.pem'),
   ca: fs.readFileSync('/etc/letsencrypt/live/mysite.com/chain.pem')
};
</code>```

EDIT

More Complete Example (Maybe not completely functional)

Server.js

```<code>    var fs = require('fs');

    var sessionKey = 'ai_session:';
    var memcachedAuth = require('memcached-auth');

    var clients = {};
    var users = {};

    var options = {
      key: fs.readFileSync('/etc/letsencrypt/live/somesite.com/privkey.pem'),
      cert: fs.readFileSync('/etc/letsencrypt/live/somesite.com/fullchain.pem'),
      ca: fs.readFileSync('/etc/letsencrypt/live/somesite.com/chain.pem')
    };

    var origins = 'https://www.somesite.com:*';
    var https = require('https').createServer(options,function(req,res){

        // Set CORS headers
        res.setHeader('Access-Control-Allow-Origin', origins);
        res.setHeader('Access-Control-Request-Method', '*');
        res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
        res.setHeader('Access-Control-Allow-Headers', '*');

    });

    var io = require('socket.io')(https);
    https.listen(3000);

    io.sockets.on('connection', function(socket){

      socket.on('auth', function(data){

          var session_id = sessionKey+data.token;
          memcachedAuth.is_logged_in(session_id).then( (response) => {

          if(response.is_logged_in){

              // user is logged in
              socket.emit('is_logged_in', true);

              messenger.addUser(socket);

              // dynamic room
              socket.on('room', function(room){
             socket.join(room);
             console.log('joing room '+room);
              });

              socket.on('message', function(data){
              messenger.receive(data.message_data);
              });
          }else{
              // Not logged in
              socket.emit('is_logged_in', false);
          }
          }).catch( (error) => {
          console.log(error);
          });

      });

    });

    var messenger = {
        socket: (socket)=>{
          return socket;
        },
        subscribe: (room)=>{

        },
        unsubscribe: (room)=>{

        },
        send: (data)=>{

        },
        receive: (data)=>{
        console.log(data);
          //connected
          if (clients[data.user_name]){
            console.log('user');
          }
        },
        addUser: (socket)=>{
        socket.on('add-user', function(data){
            clients[data] = {
              "socket": socket.id
            };
            console.log('Adding User:' + data);
            console.log(clients);
        });
        },
        private: (socket)=>{
        // Not working yet...
        socket.on('message', function(data){

            console.log("Sending: " + data + " to " + data.user_name);

            if (clients[data.user_name]){
              io.sockets.connected[clients[data.user_name].socket].emit("response", data);
            } else {
              console.log("User does not exist: " + data.user_name);
            }
        });
        },
        disconnect:()=>{
        //Removing the socket on disconnect
        socket.on('disconnect', function() {
         for(var name in clients) {
           if(clients[name].socket === socket.id) {
             delete clients[name];
             break;
           }
         }
        });
        }
    }
</code>```

I have created a repo on github including a more complete version of the above code if anyone is interested: https://github.com/snowballrandom/Memcached-Auth

Body:
I am messing with login form right now with node.js, I tried creating a pem key and csr using

openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem

However I been getting errors for running node server.js

Here is my server.js

var http = require('http'),
    express = require('express'),
UserServer = require('./lib/user-server');

var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('./key.pem', 'utf8'),
  cert: fs.readFileSync('./csr.pem', 'utf8')
};

var app = express();

app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

var httpserver = http.createServer(app).listen('3004', '127.0.0.1');
var https_server = https.createServer(options, app).listen('3005', '127.0.0.1');
UserServer.listen(https_server);

Here is the error

crypto.js:104
  if (options.cert) c.context.setCert(options.cert);
                          ^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
    at Object.exports.createCredentials (crypto.js:104:31)
    at Server (tls.js:1107:28)
    at new Server (https.js:35:14)
    at Object.exports.createServer (https.js:54:10)

I tried running

openssl x509 -text -inform DER -in key.pem

It gives

unable to load certificate
140735208206812:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319:
140735208206812:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=X509

I am not exactly sure what does the error mean as my encryption file is .pem file already, so any help would be much appreciated.

Thanks

Body:
For me the issues was I had the key and cert swapped.

var options = {
   key: fs.readFileSync('/etc/letsencrypt/live/mysite.com/privkey.pem'),
   cert: fs.readFileSync('/etc/letsencrypt/live/mysite.com/fullchain.pem'),
   ca: fs.readFileSync('/etc/letsencrypt/live/mysite.com/chain.pem')
};

EDIT

More Complete Example (Maybe not completely functional)

Server.js

    var fs = require('fs');

    var sessionKey = 'ai_session:';
    var memcachedAuth = require('memcached-auth');

    var clients = {};
    var users = {};

    var options = {
      key: fs.readFileSync('/etc/letsencrypt/live/somesite.com/privkey.pem'),
      cert: fs.readFileSync('/etc/letsencrypt/live/somesite.com/fullchain.pem'),
      ca: fs.readFileSync('/etc/letsencrypt/live/somesite.com/chain.pem')
    };

    var origins = 'https://www.somesite.com:*';
    var https = require('https').createServer(options,function(req,res){

        // Set CORS headers
        res.setHeader('Access-Control-Allow-Origin', origins);
        res.setHeader('Access-Control-Request-Method', '*');
        res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
        res.setHeader('Access-Control-Allow-Headers', '*');

    });

    var io = require('socket.io')(https);
    https.listen(3000);

    io.sockets.on('connection', function(socket){

      socket.on('auth', function(data){

          var session_id = sessionKey+data.token;
          memcachedAuth.is_logged_in(session_id).then( (response) => {

          if(response.is_logged_in){

              // user is logged in
              socket.emit('is_logged_in', true);

              messenger.addUser(socket);

              // dynamic room
              socket.on('room', function(room){
             socket.join(room);
             console.log('joing room '+room);
              });

              socket.on('message', function(data){
              messenger.receive(data.message_data);
              });
          }else{
              // Not logged in
              socket.emit('is_logged_in', false);
          }
          }).catch( (error) => {
          console.log(error);
          });

      });

    });

    var messenger = {
        socket: (socket)=>{
          return socket;
        },
        subscribe: (room)=>{

        },
        unsubscribe: (room)=>{

        },
        send: (data)=>{

        },
        receive: (data)=>{
        console.log(data);
          //connected
          if (clients[data.user_name]){
            console.log('user');
          }
        },
        addUser: (socket)=>{
        socket.on('add-user', function(data){
            clients[data] = {
              "socket": socket.id
            };
            console.log('Adding User:' + data);
            console.log(clients);
        });
        },
        private: (socket)=>{
        // Not working yet...
        socket.on('message', function(data){

            console.log("Sending: " + data + " to " + data.user_name);

            if (clients[data.user_name]){
              io.sockets.connected[clients[data.user_name].socket].emit("response", data);
            } else {
              console.log("User does not exist: " + data.user_name);
            }
        });
        },
        disconnect:()=>{
        //Removing the socket on disconnect
        socket.on('disconnect', function() {
         for(var name in clients) {
           if(clients[name].socket === socket.id) {
             delete clients[name];
             break;
           }
         }
        });
        }
    }

I have created a repo on github including a more complete version of the above code if anyone is interested: https://github.com/snowballrandom/Memcached-Auth


问:
Undefined function with javascripts
I'm writing a small 'quote calculator'. I want to print the summary to the browser with innerHTML, but I'm still getting "undefined" instead of the price. But in my console.log everything works fine, I can console.log the variable price and get the expected result.

//Variables

const form = document.getElementById('request-quote');
const html = new HTMLUI();

//Event Listeners

eventListeners();

function eventListeners() {
  document.addEventListener('DOMContentLoaded', function() {
    //Create the <option> for the years
    html.displayYears();
  });
  //when the form is submitted

  form.addEventListener('submit', function(e) {
    e.preventDefault();

    //get values from the form
    const make = document.getElementById('make').value;
    const year = document.getElementById('year').value;

    //Read the radio buttons

    const level =
      document.querySelector('input[name="level"]:checked').value;

    // Validation
    if (make === '' || year === '' || level === '') {
      html.displayErrors('All fields are mendatory')
    } else {
      //Make the quotation
      const insurance = new Insurance(make, year, level);
      const price = insurance.calculateQuotation(insurance);
      //print
      html.showResults(price);
    }

  });
}
// Create another prototype with for the object HTMLUI. to print Errors

//Object
// Everything related to the calculation and quotation

function Insurance(make, year, level) {
  this.make = make;
  this.year = year;
  this.level = level;
}

//calculation

Insurance.prototype.calculateQuotation = function(insurance) {
  let price;
  const base = 2000;

  //get make
  const make = insurance.make;

  /**
   1. america: 15
   2. Asia : 5
   3. europia: 35
  */

  switch (make) {
    case '1':
      price = base * 1.15;
      break

    case '2':
      price = base * 1.05;
      break

    case '3':
      price = base * 1.35;
      break
  }

  //get level

  const level = insurance.level;

  price = this.calculateLevel(price, level);

  //get year

  const year = insurance.year;
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.log(price);

}
//return difference between years

Insurance.prototype.getYearDifference = function(year) {
  return new Date().getFullYear() - year;
  // each year the cost must be 3% cheaper

}

//add value based on level

Insurance.prototype.calculateLevel = function(price, level) {
  //basic increase 30%

  //complete increases 50%
  if (level === 'basic') {
    price = price * 1.30;
  } else {
    price = price * 1.50;
  }
  return price;
}

function HTMLUI() {}
//display the latest 20 years in the select
HTMLUI.prototype.displayYears = function() {
  //Max & minimum years
  const max = new Date().getFullYear();
  min = max - 20;
  //Generate the list
  const selectYears = document.getElementById('year');

  //print the values

  for (let i = max; i >= min; i--) {
    const option = document.createElement('option')
    option.value = i;
    option.textContent = i;
    selectYears.appendChild(option);
  }
}

//Print Error, by creating a prototype

HTMLUI.prototype.displayErrors = function(message) {
  //create div
  const div = document.createElement('div');
  div.classList = 'error';

  //insert message
  div.innerText = `

${message}

    `;

  form.insertBefore(div, document.querySelector('.form-group'));

  //Remove the error

  setTimeout(function() {
    document.querySelector('.error').remove();
  }, 3000);
}

HTMLUI.prototype.showResults = function(price) {
  //print result
  const result = document.getElementById('result');

  //create a div with the result

  const div = document.createElement('div');
  //insert the result
  div.innerHTML = `

Total: $ ${price}

    `;
  //insert into html

  result.appendChild(div)
}
```

I am expecting to print the value of the variable price( which will actually be the price) but I'm getting "undefined" while trying to print the price

答:
It shows undefined cause you never returned a result. You need to return the 'price' variable to fix it.</p>

```<code>...
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.log(price);
  return price;
}
</code>```

Title: Undefined function with javascripts

Body:
I'm writing a small 'quote calculator'. I want to print the summary to the browser with innerHTML, but I'm still getting "undefined" instead of the price. But in my console.log everything works fine, I can console.log the variable price and get the expected result.

//Variables

const form = document.getElementById('request-quote');
const html = new HTMLUI();

//Event Listeners

eventListeners();

function eventListeners() {
  document.addEventListener('DOMContentLoaded', function() {
    //Create the <option> for the years
    html.displayYears();
  });
  //when the form is submitted

  form.addEventListener('submit', function(e) {
    e.preventDefault();

    //get values from the form
    const make = document.getElementById('make').value;
    const year = document.getElementById('year').value;

    //Read the radio buttons

    const level =
      document.querySelector('input[name="level"]:checked').value;

    // Validation
    if (make === '' || year === '' || level === '') {
      html.displayErrors('All fields are mendatory')
    } else {
      //Make the quotation
      const insurance = new Insurance(make, year, level);
      const price = insurance.calculateQuotation(insurance);
      //print
      html.showResults(price);
    }

  });
}
// Create another prototype with for the object HTMLUI. to print Errors

//Object
// Everything related to the calculation and quotation

function Insurance(make, year, level) {
  this.make = make;
  this.year = year;
  this.level = level;
}

//calculation

Insurance.prototype.calculateQuotation = function(insurance) {
  let price;
  const base = 2000;

  //get make
  const make = insurance.make;

  /**
   1. america: 15
   2. Asia : 5
   3. europia: 35
  */

  switch (make) {
    case '1':
      price = base * 1.15;
      break

    case '2':
      price = base * 1.05;
      break

    case '3':
      price = base * 1.35;
      break
  }

  //get level

  const level = insurance.level;

  price = this.calculateLevel(price, level);

  //get year

  const year = insurance.year;
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.log(price);

}
//return difference between years

Insurance.prototype.getYearDifference = function(year) {
  return new Date().getFullYear() - year;
  // each year the cost must be 3% cheaper

}

//add value based on level

Insurance.prototype.calculateLevel = function(price, level) {
  //basic increase 30%

  //complete increases 50%
  if (level === 'basic') {
    price = price * 1.30;
  } else {
    price = price * 1.50;
  }
  return price;
}

function HTMLUI() {}
//display the latest 20 years in the select
HTMLUI.prototype.displayYears = function() {
  //Max & minimum years
  const max = new Date().getFullYear();
  min = max - 20;
  //Generate the list
  const selectYears = document.getElementById('year');

  //print the values

  for (let i = max; i >= min; i--) {
    const option = document.createElement('option')
    option.value = i;
    option.textContent = i;
    selectYears.appendChild(option);
  }
}

//Print Error, by creating a prototype

HTMLUI.prototype.displayErrors = function(message) {
  //create div
  const div = document.createElement('div');
  div.classList = 'error';

  //insert message
  div.innerText = `

${message}

    `;

  form.insertBefore(div, document.querySelector('.form-group'));

  //Remove the error

  setTimeout(function() {
    document.querySelector('.error').remove();
  }, 3000);
}

HTMLUI.prototype.showResults = function(price) {
  //print result
  const result = document.getElementById('result');

  //create a div with the result

  const div = document.createElement('div');
  //insert the result
  div.innerHTML = `

Total: $ ${price}

    `;
  //insert into html

  result.appendChild(div)
}

I am expecting to print the value of the variable price( which will actually be the price) but I'm getting "undefined" while trying to print the price

Body:
It shows undefined cause you never returned a result. You need to return the 'price' variable to fix it.

...
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.log(price);
  return price;
}


问:
find max in self join after multiple joins
i'm trying to find the highest number of interviews from each category (month and city) by joining two different tables and doing a self join in sql

```<code>`select distinct table1.event_id, table1.month, table1.city

from

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table1,

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table2

WHERE table1.event_id <> table2.event_id
AND table1.month = table2.month
AND table1.city = table2.city`
</code>```

the above code works that shows a self join after multiple join to compare every event_id for the number of total_interviews, but when i add after where

```<code>AND table1.total_interviews > all (select table2.total_interviews FROM table2 WHERE table2.event_id <> table1.event_id)
</code>```

to find the max value, it gives me an error saying there is no such column for table1 and table2.

the reason why i added this is so that i can determine which event_id has the highest number of interviews compared to the rest, but i haven't been able to find out how to do this

答:
Trying to work back from what I think is the source data, before your initial self join, does this give you what you want? This is in sql server.

```<code>declare @i table(id int, n int, m varchar(30), city varchar(2))
insert @i values (1,4,'Jan','SF')
,(2,5,'Feb','NY')
,(3,6,'Mar','LA')
,(4,3,'Jan','SF')
,(5,2,'Feb','NY')
,(6,1,'Mar','LA')

;with cte as (
    select *, row_number() over(partition by m,city order by n desc) roworder
    from @i
)
select id,m,city from cte
where roworder=1
order by id
</code>```

Result is this:

```<code>id  m   city
1   Jan SF
2   Feb NY
3   Mar LA
</code>```

Body:
i'm trying to find the highest number of interviews from each category (month and city) by joining two different tables and doing a self join in sql

`select distinct table1.event_id, table1.month, table1.city

from

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table1,

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table2

WHERE table1.event_id <> table2.event_id
AND table1.month = table2.month
AND table1.city = table2.city`

the above code works that shows a self join after multiple join to compare every event_id for the number of total_interviews, but when i add after where

AND table1.total_interviews > all (select table2.total_interviews FROM table2 WHERE table2.event_id <> table1.event_id)

to find the max value, it gives me an error saying there is no such column for table1 and table2.

the reason why i added this is so that i can determine which event_id has the highest number of interviews compared to the rest, but i haven't been able to find out how to do this

Body:
Trying to work back from what I think is the source data, before your initial self join, does this give you what you want? This is in sql server.

declare @i table(id int, n int, m varchar(30), city varchar(2))
insert @i values (1,4,'Jan','SF')
,(2,5,'Feb','NY')
,(3,6,'Mar','LA')
,(4,3,'Jan','SF')
,(5,2,'Feb','NY')
,(6,1,'Mar','LA')

;with cte as (
    select *, row_number() over(partition by m,city order by n desc) roworder
    from @i
)
select id,m,city from cte
where roworder=1
order by id

Result is this:

id  m   city
1   Jan SF
2   Feb NY
3   Mar LA


问:
How can I maintain single copy of a 2d vector in clojure
I want to maintain a single copy of vector in whole class. I have to update vector many times in recursion.

```<code> ;this is to update cell in vector
(defn to-plus [data x y]
 (update data y (fn [row] (apply str (assoc (vec row) x \+)))))

;here i am getting values in board and calling to-plus to update board
;now i need to maintain a single copy of board
(let [board (read-in-board "map.txt")]
(print-maze board)
(println(str (get-in board [1 4])))
(print-maze (to-plus board 1 4))
(println(to-plus board 1 4)))
</code>```

I am trying to solve maze problem using recursion and random walk. I am new to Clojure.

```<code>;Data is of type
---#--###----
-#---#----##-
####-#-#-#-##
---#---#-#---
-+-####---##-
-#------#----
-############
------------@
</code>```

答:
Use to-array-2d then aget and aset

above answer got down voted by L.F.  Adding more detail below:

“...maintain a single copy of vector...”
Ans: Use to-array-2d to convert immutable nested-vector into mutable 2d array.

“...update vector many times in recursion...”
Ans: Use aget and aset to read and update the mutable 2d array created.

Body:
I want to maintain a single copy of vector in whole class. I have to update vector many times in recursion.

 ;this is to update cell in vector
(defn to-plus [data x y]
 (update data y (fn [row] (apply str (assoc (vec row) x \+)))))

;here i am getting values in board and calling to-plus to update board
;now i need to maintain a single copy of board
(let [board (read-in-board "map.txt")]
(print-maze board)
(println(str (get-in board [1 4])))
(print-maze (to-plus board 1 4))
(println(to-plus board 1 4)))

I am trying to solve maze problem using recursion and random walk. I am new to Clojure.

;Data is of type
---#--###----
-#---#----##-
####-#-#-#-##
---#---#-#---
-+-####---##-
-#------#----
-############
------------@


问:
Why use Facade pattern for EJB session bean
I want to ask what is the reason to use Facade Pattern when access EJB Session Bean. In my Netbeans 6.9.1, if I do New > Sessions Bean for Entity Classes, and let say that I select User entity, then Netbeans would generate this code

```<code>AbstractFacade.java
public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public T edit(T entity) {
        return getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        ...
    }

    public int count() {
        ...
    }
</code>```

AND

```<code>UserFacade.java

package com.bridgeye.ejb;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class UserFacade extends AbstractFacade<User> {
    @PersistenceContext(unitName = "Bridgeye2-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }
}
</code>```

I want to ask what is the benefit of this. If I have 10 entities, then Netbeans would generated 10 Facade classes plus the AbstractFacade. This seems to be overkill to me. Let say somewhere inside my managed bean, i have to persist a User and School then I have do this

```<code>someManagedBean.java

...
@EJB
private UserFacade userEJB;

@EJB
private SchoolFacade schoolEJB;

...

public void someMethod(User user, School school){
    ...
    userEJB.create(user);
    schoolEJB.create(school);
}
</code>```

Is this the right things to do?

答:
The point of using EJBs at all is that they provide features such as declarative transactions and security via annotations (or XML configurations). If you don't use those features, there is no point in having EJBs.

Additionally, that autogenerated facade code is jsut a starting point (and a bad one). The EJBs should form a domain API, not a wrapper for all individual CRUD operations. They should only contain the operations you actually want to be performed on your domain model, and many of them should span several CRUD operations that need to be performend within a transaction. For example:

```<code>@TransactionAttribute
public void transferUser(User u, School from, School to){
    from.getUsers().remove(u);
    to.getUsers().add(u);
    u.setSchool(to);
    getEntityManager().merge(from);
    getEntityManager().merge(to);
    getEntityManager().merge(u);
}
</code>```

The app server will execute all operations within a transaction, which ensures, for example, that you cannot have a situation where an exception is thrown for some reason and you end up with User that is removed from one Schoold but not added to the other one.

Body:
I want to ask what is the reason to use Facade Pattern when access EJB Session Bean. In my Netbeans 6.9.1, if I do New > Sessions Bean for Entity Classes, and let say that I select User entity, then Netbeans would generate this code

AbstractFacade.java
public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public T edit(T entity) {
        return getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        ...
    }

    public int count() {
        ...
    }

AND

UserFacade.java

package com.bridgeye.ejb;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class UserFacade extends AbstractFacade<User> {
    @PersistenceContext(unitName = "Bridgeye2-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }
}

I want to ask what is the benefit of this. If I have 10 entities, then Netbeans would generated 10 Facade classes plus the AbstractFacade. This seems to be overkill to me. Let say somewhere inside my managed bean, i have to persist a User and School then I have do this

someManagedBean.java

...
@EJB
private UserFacade userEJB;

@EJB
private SchoolFacade schoolEJB;

...

public void someMethod(User user, School school){
    ...
    userEJB.create(user);
    schoolEJB.create(school);
}

Is this the right things to do?

Body:
The point of using EJBs at all is that they provide features such as declarative transactions and security via annotations (or XML configurations). If you don't use those features, there is no point in having EJBs.

Additionally, that autogenerated facade code is jsut a starting point (and a bad one). The EJBs should form a domain API, not a wrapper for all individual CRUD operations. They should only contain the operations you actually want to be performed on your domain model, and many of them should span several CRUD operations that need to be performend within a transaction. For example:

@TransactionAttribute
public void transferUser(User u, School from, School to){
    from.getUsers().remove(u);
    to.getUsers().add(u);
    u.setSchool(to);
    getEntityManager().merge(from);
    getEntityManager().merge(to);
    getEntityManager().merge(u);
}

The app server will execute all operations within a transaction, which ensures, for example, that you cannot have a situation where an exception is thrown for some reason and you end up with User that is removed from one Schoold but not added to the other one.


问:
How to set full-window background image using React styling
I'm trying to do something very basic in React, but I am having trouble. I want to set a image to be the full-window background of my website.

With CSS styling, I managed to get the image to appear. But I was having trouble setting the image to be a full-window background. So I tried my hand at React styling.

```<code>import React, { Component } from "react";
import logo from "./logo.svg";
import code from "./code.jpg";
import "./App.css";

function App() {
  var styles = StyleSheet.create({
    bgImage: {
      flex: 1,
      flexDirection: "row",
      justifyContent: "center",
      alignItems: "stretch",
      resizeMode: "stretch"
    }
  });
  return (
    <React.Fragment>
      <Image
        source={require("image!background")}
        style={styles.bgImage}
        alt="background"
      >
        pizza
      </Image>
    </React.Fragment>
  );
}

export default App;
</code>```

I'm pretty new to React. Thanks to anybody who can help me understand what is happening!

答:
```<code>  <Image
    source={require("image!background")}
    style={styles.bgImage}
     width="100%"
    alt="background"
  >
</code>```

Edit:

yes this is true, you in fact do not have <Image /> defined, where is it coming from?

Did you mean to use the html  element. All uppercase elements are react specific and cant be globally registered so you have to import that <Image /> component here, wherever it is defined in your app.

The second error is also valid. what is it you are trying to do with the syntax
"image!background"

This is not valid syntax as far as I know. the " ! " usually denotes a "is not" in a conditional. such as

```<code>2 !== 3
</code>```

or

```<code>2 is not equal to 3
</code>```

Body:
I'm trying to do something very basic in React, but I am having trouble. I want to set a image to be the full-window background of my website.

With CSS styling, I managed to get the image to appear. But I was having trouble setting the image to be a full-window background. So I tried my hand at React styling.

import React, { Component } from "react";
import logo from "./logo.svg";
import code from "./code.jpg";
import "./App.css";

function App() {
  var styles = StyleSheet.create({
    bgImage: {
      flex: 1,
      flexDirection: "row",
      justifyContent: "center",
      alignItems: "stretch",
      resizeMode: "stretch"
    }
  });
  return (
    <React.Fragment>
      <Image
        source={require("image!background")}
        style={styles.bgImage}
        alt="background"
      >
        pizza
      </Image>
    </React.Fragment>
  );
}

export default App;

I'm pretty new to React. Thanks to anybody who can help me understand what is happening!

Body:
  <Image
    source={require("image!background")}
    style={styles.bgImage}
     width="100%"
    alt="background"
  >

Edit:

yes this is true, you in fact do not have <Image /> defined, where is it coming from?

Did you mean to use the html <img /> element. All uppercase elements are react specific and cant be globally registered so you have to import that <Image /> component here, wherever it is defined in your app.

The second error is also valid. what is it you are trying to do with the syntax
"image!background"

This is not valid syntax as far as I know. the " ! " usually denotes a "is not" in a conditional. such as

2 !== 3

or

2 is not equal to 3


问:
How to offer scalars as coordinates of the data points for pyplot's plot function?
I am reading document of the pyplot's plot function here: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot. It said the Parameters x, y: array-like or scalar.

I understand how to using array-like data, but not scalar. Can anyone give some examples to show how to use scalar x, y parameter? Thanks.

答:
You are thinking too much about the the definition of scalar number. For this purpose, it just means a int or float. Use the following code to plot.

```<code>plt.plot(x, y)
plt.show()
</code>```

Also make sure that you have imported matplotlib correctly. The best method is

```<code>import matplotlib as plt
</code>```

Body:
You are thinking too much about the the definition of scalar number. For this purpose, it just means a int or float. Use the following code to plot.

plt.plot(x, y)
plt.show()

Also make sure that you have imported matplotlib correctly. The best method is

import matplotlib as plt


问:
Unable to Sign In to iTunes Connect: "Your Apple ID isn't enabled for iTunes Connect"
I am a member of my company's development team, with the role of Admin. I can access the Member Center of the team at https://developer.apple.com/

However, when I I attempt to sign in at https://itunesconnect.apple.com I am presented with the following error message:

Your Apple ID isn't enabled for iTunes Connect. Learn More

I am an admin on the development team. When I visit Developer > Member Center > People I do not see any permissions related to iTunes Connect.

How do I gain access to my team's iTunes Connect portal?

答:
For anyone who's still facing this issue. The above solutions did not work for me at this point in time. This is what I've done to get it working (from apple's help):

How to generate an app-specific password

Sign in to your Apple ID account page.

In the Security section, click Generate Password below App-Specific Passwords.

Follow the steps on your screen. After you generate your app-specific password, enter or paste it into the password field of the app as you would normally.


问:
When a 'view.rx.isHidden' has changed, how can i emit a single to let annother view know, can i observe 'view.rx.isHidden'?
I have a view A, click on a button to make it show or hide the way through RxSwift: .bind(to: nearbyVc.view.rx.isHidden)
Now I want to monitor view A propertyisHidden and do something Other things, how can I make it?

答:
Don't use your view as if it was a model. You are programmatically changing the isHidden property of the view when your model changes, so have those model changes also do the "other things".

So for example:

```<code>let validInput = textField.rx.text.map { $0.length > 0 }

validInput
    .map { !$0 }
    .bind(to: inputButton.rx.isHidden)
    .disposed(by: bag)

validInput
    .bind(onNext: { _ in /* do other thing */ })
    .disposed(by: bag)
</code>```

In the above validInput is the model.

Body:
Don't use your view as if it was a model. You are programmatically changing the isHidden property of the view when your model changes, so have those model changes also do the "other things".

So for example:

let validInput = textField.rx.text.map { $0.length > 0 }

validInput
    .map { !$0 }
    .bind(to: inputButton.rx.isHidden)
    .disposed(by: bag)

validInput
    .bind(onNext: { _ in /* do other thing */ })
    .disposed(by: bag)

In the above validInput is the model.


问:
Are there any differences for @Context injected on a Class or a Method?
In JAX-RS we can inject @Context instances like HttpServletRequest as a class field or as a method parameter.

Are there any differences between those two options?

I belive Singletons will have some sort of proxy injected instead, but are there any side-effects to be aware of? Or are they transparent and it's just a matter of personal taste?

答:
For the most part, it is simply personal preference.

My advice would be to inject as class fields, as the @Context annotation will eventually be replaced by @Inject from CDI - and the @Inject annotation does not target method parameters.  You can read more of the discussion here.


问:
Spring Security How to check if login form credentials are valid?
How to proceed if I want to check if credentials are valid ?

For example, I want to be sure that username is valid (valid email, limited size and so on) so I can display the error to the user before even attempting to authenticate using Spring Security.

1) Make sure credentials are valid before authentication
2) Authenticate
3) Rock-n-roll

Btw, I'm using Spring Security 3.1.0 RC.

Thank you in advance for your help,
Adnan

Update:
Actually I'm talking about validation: making sure that  username is in valid email format, or make sure that the passwords is at least 8 characters and so on.
Only when I'm sure that it is in "valid" format I will submit it to the Security authentication & authorization else I just want to display the login form again with error message (for example: "password must be at least 8 characters").

答:
Alright, I found a way to validate form fields using hibernate validator annotations @Email & NotNull and so on:

```<code>import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;

public class LoginForm
{
    @Email
    @Size(min = 4, max = 128)
    private String username;

    @NotBlank
    @Size(min = 4, max = 128)
    private String password;

    ...

}
</code>```

The Security part was a bit tricky because I had to manually authenticate against authenticationManager and the Security Context didn't want to update current session:

```<code>@Autowired
@Qualifier("authenticationManager")
private AuthenticationManager authenticationManager;

@RequestMapping(method = RequestMethod.POST)
public String processForm(@Valid LoginForm loginForm, BindingResult result, HttpServletRequest request, Model model)
{
    // Display errors in loginForm if not valid
    if (result.hasErrors())
        return "login";

    try
    {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginForm.getUsername(), loginForm.getPassword());
        Authentication auth = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(auth);

        // for some reason, security context is NOT setting the auth key in session
        // so I had to put it here myself!
        HttpSession session = request.getSession();
        session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());

        return "redirect:/index";
    }
    catch (AuthenticationException e)
    {
        SecurityContextHolder.getContext().setAuthentication(null);
        String errorMessage = e.getLocalizedMessage();
        model.addAttribute("errorMessage", errorMessage);
        return "loginerror";
    }
}
</code>```

Be sure to put alias for authentication-manager in order to be able to autowire it <security:authentication-manager alias="authenticationManager">

Hope that helps someone :)

Body:
Alright, I found a way to validate form fields using hibernate validator annotations @Email & NotNull and so on:

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;

public class LoginForm
{
    @Email
    @Size(min = 4, max = 128)
    private String username;

    @NotBlank
    @Size(min = 4, max = 128)
    private String password;

    ...

}

The Security part was a bit tricky because I had to manually authenticate against authenticationManager and the Security Context didn't want to update current session:

@Autowired
@Qualifier("authenticationManager")
private AuthenticationManager authenticationManager;

@RequestMapping(method = RequestMethod.POST)
public String processForm(@Valid LoginForm loginForm, BindingResult result, HttpServletRequest request, Model model)
{
    // Display errors in loginForm if not valid
    if (result.hasErrors())
        return "login";

    try
    {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginForm.getUsername(), loginForm.getPassword());
        Authentication auth = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(auth);

        // for some reason, security context is NOT setting the auth key in session
        // so I had to put it here myself!
        HttpSession session = request.getSession();
        session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());

        return "redirect:/index";
    }
    catch (AuthenticationException e)
    {
        SecurityContextHolder.getContext().setAuthentication(null);
        String errorMessage = e.getLocalizedMessage();
        model.addAttribute("errorMessage", errorMessage);
        return "loginerror";
    }
}

Be sure to put alias for authentication-manager in order to be able to autowire it <security:authentication-manager alias="authenticationManager">

Hope that helps someone :)


问:
How to make button open another fragment from within another fragment in kotlin
how to make button to open another fragment. being within a fragment. kotlin

I'm starting in kotlin and I'm having a hard time trying to open a fragment with a button, how do I?

答:
You need to use FragmentManager and FragmentTransaction to add your fragment on the fly. you can call a function similar to this in your button's onClick method. But it is recommended for the parent activity to handle each fragment's lifecycle and the fragments
are not supposed to interact each other. The following is taken from the developer docs, that can be found here.
"Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done either through a shared ViewModel or through the associated Activity. Two Fragments should never communicate directly."

```<code>fun createFragmentonTheFly(){
        var mFragmentTransaction: FragmentTransaction = getSupportFragmentManager().beginTransaction()
        mFragmentTransaction.add(R.id.fr_container,new ProductListFragment())
        mFragmentTransaction.commit()
    }
</code>```

The best way to do it would be to add an interface let say onFragmentDetachedLisetner and add one method replaceFragment() or something and make your Activity implement this interaface and had it replace as soon as the fragment is detached and make your fragment that contains your button finish itself when user clicks the button, then your activity will replace it with the one you wanted to start. And also consider reusing fragments, as that is the main purpose of fragments at the first place.

Body:
You need to use FragmentManager and FragmentTransaction to add your fragment on the fly. you can call a function similar to this in your button's onClick method. But it is recommended for the parent activity to handle each fragment's lifecycle and the fragments
are not supposed to interact each other. The following is taken from the developer docs, that can be found here.
"Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done either through a shared ViewModel or through the associated Activity. Two Fragments should never communicate directly."

fun createFragmentonTheFly(){
        var mFragmentTransaction: FragmentTransaction = getSupportFragmentManager().beginTransaction()
        mFragmentTransaction.add(R.id.fr_container,new ProductListFragment())
        mFragmentTransaction.commit()
    }

The best way to do it would be to add an interface let say onFragmentDetachedLisetner and add one method replaceFragment() or something and make your Activity implement this interaface and had it replace as soon as the fragment is detached and make your fragment that contains your button finish itself when user clicks the button, then your activity will replace it with the one you wanted to start. And also consider reusing fragments, as that is the main purpose of fragments at the first place.


问:
docker compose wont build
Using docker-compose to build against an existing dockerfile with some slight changes fails with:

```<code>Step 1/10 : FROM alpine:latest
 ---> 055936d39205
Step 2/10 : LABEL MAINTAINER="Peter Winter <peter@pwntr.com>"     Description="Simple and lightweight Samba docker container, based on Alpine Linux."     Version="1.0.2"
 ---> Using cache
 ---> e99eafd27cc6
Step 3/10 : RUN apk --no-cache upgrade && apk --no-cache add samba samba-common-tools supervisor
 ---> Running in 99c71d23252f
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz: could not connect to server (check repositories file)
WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz: could not connect to server (check repositories file)
OK: 6 MiB in 14 packages
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz: could not connect to server (check repositories file)
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz: could not connect to server (check repositories file)
ERROR: unsatisfiable constraints:
  samba (missing):
    required by: world[samba]
  samba-common-tools (missing):
    required by: world[samba-common-tools]
  supervisor (missing):
    required by: world[supervisor]
ERROR: compose.cli.main.main: Service 'samba' failed to build: The command '/bin/sh -c apk --no-cache upgrade && apk --no-cache add samba samba-common-tools supervisor' returned a non-zero code: 3
</code>```

Appears to be not using the proxy?

docker-compose.yml

```<code>version: "3.7"
services:
  samba:
    #image: pwntr/samba-alpine
    build:
      context: .
      dockerfile: Dockerfile
    container_name: samba
    volumes:
      - /some/path:/shared:ro
    restart: unless-stopped
</code>```

I have tried setting the args and environment sections with the proxy details, however makes no difference.

```<code>version: "3.7"
services:
  samba:
    #image: pwntr/samba-alpine
    build:
      context: .
      dockerfile: Dockerfile
#      args: # Environment variables available at build-time
#        - http_proxy=http://127.0.0.1:3128
#        - https_proxy=http://127.0.0.1:3128
#        - HTTP_PROXY=http://127.0.0.1:3128
#        - HTTPS_PROXY=http://127.0.0.1:3128
#    environment: # Environment variables available at container run-time
#      - http_proxy=http://127.0.0.1:3128
#      - https_proxy=http://127.0.0.1:3128
#      - HTTP_PROXY=http://127.0.0.1:3128
#      - HTTPS_PROXY=http://127.0.0.1:3128
    container_name: samba
    volumes:
      - /some/path:/shared:ro
    restart: unless-stopped
</code>```

If I use docker run  or via image everything works fine.

```<code>version: "3.7"
services:
  samba:
    image: pwntr/samba-alpine
    container_name: samba
    volumes:
      - /some/path:/shared:ro
    restart: unless-stopped
</code>```

Server/Host is running Alpine Linux with connections working fine.

```<code>docker info | grep -i proxy
HTTP Proxy: http://127.0.0.1:3128/
HTTPS Proxy: http://127.0.0.1:3128/
</code>```

答:
Try this
docker build -t localhost/smb:v1 .

You better change RUN apk --no-cache upgrade && apk --no-cache add samba samba-common-tools supervisor to RUN apk --no-cache --upgrade add samba samba-common-tools supervisor to avoid multiple network requests.

Title: docker compose wont build

Body:
Using docker-compose to build against an existing dockerfile with some slight changes fails with:

Step 1/10 : FROM alpine:latest
 ---> 055936d39205
Step 2/10 : LABEL MAINTAINER="Peter Winter <peter@pwntr.com>"     Description="Simple and lightweight Samba docker container, based on Alpine Linux."     Version="1.0.2"
 ---> Using cache
 ---> e99eafd27cc6
Step 3/10 : RUN apk --no-cache upgrade && apk --no-cache add samba samba-common-tools supervisor
 ---> Running in 99c71d23252f
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz: could not connect to server (check repositories file)
WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz: could not connect to server (check repositories file)
OK: 6 MiB in 14 packages
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz: could not connect to server (check repositories file)
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz: could not connect to server (check repositories file)
ERROR: unsatisfiable constraints:
  samba (missing):
    required by: world[samba]
  samba-common-tools (missing):
    required by: world[samba-common-tools]
  supervisor (missing):
    required by: world[supervisor]
ERROR: compose.cli.main.main: Service 'samba' failed to build: The command '/bin/sh -c apk --no-cache upgrade && apk --no-cache add samba samba-common-tools supervisor' returned a non-zero code: 3

Appears to be not using the proxy?

docker-compose.yml

version: "3.7"
services:
  samba:
    #image: pwntr/samba-alpine
    build:
      context: .
      dockerfile: Dockerfile
    container_name: samba
    volumes:
      - /some/path:/shared:ro
    restart: unless-stopped

I have tried setting the args and environment sections with the proxy details, however makes no difference.

version: "3.7"
services:
  samba:
    #image: pwntr/samba-alpine
    build:
      context: .
      dockerfile: Dockerfile
#      args: # Environment variables available at build-time
#        - http_proxy=http://127.0.0.1:3128
#        - https_proxy=http://127.0.0.1:3128
#        - HTTP_PROXY=http://127.0.0.1:3128
#        - HTTPS_PROXY=http://127.0.0.1:3128
#    environment: # Environment variables available at container run-time
#      - http_proxy=http://127.0.0.1:3128
#      - https_proxy=http://127.0.0.1:3128
#      - HTTP_PROXY=http://127.0.0.1:3128
#      - HTTPS_PROXY=http://127.0.0.1:3128
    container_name: samba
    volumes:
      - /some/path:/shared:ro
    restart: unless-stopped

If I use docker run  or via image everything works fine.

version: "3.7"
services:
  samba:
    image: pwntr/samba-alpine
    container_name: samba
    volumes:
      - /some/path:/shared:ro
    restart: unless-stopped

Server/Host is running Alpine Linux with connections working fine.

docker info | grep -i proxy
HTTP Proxy: http://127.0.0.1:3128/
HTTPS Proxy: http://127.0.0.1:3128/


问:
How to get around the ' (quote) problem when saving text using SQL
I've a textbox that I save to a SQL Database using ASP.NET C#.

The problem is using quotes, for instance with words like he's and it's.  When you save it, I get an SQL error.

From experience to get around the issue, I use to use replace command to find all occurances of quotes and replace them with another character.  Then if I was to read the database and the text that was previously saved, I'd replace again.

Is there a better of doing this? Or do you still have to use this 'old' way.

答:
Use parametrized queries.

Using replace is dangerous and can lead to unintentional SQL injection vulnerabilities.


问:
OAuth2 Configuration Issues: AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application:
Trying to get Oauth2.0 to work with APIM in my Azure space.

I have imported and setup an 2.0 Open API as the backend.  I am using the APIM developer portal as the client to call this backend API.  I have the dev portal App ID as the Client ID and using its Client Secret.  I tried using the provided redirect_uri for authorization code as the reply url and also tried using app.com/auth with same issue

When I  make a call to the API from the Developer Console, I prompted to sign in. I then sign in and get the following error:

AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.

Any help would be greatly appreciated

答:
Do follow this document to protect your API by using OAuth 2.0 with Azure Active Directory.

Note: This document applies to App registrations(Legacy). If you used App registrations, there will be something different from the document.

It seems that the reply url configured for your client app is not correct.

Click OAuth2.0->click your oauth2 service->you will find the redirect_uri.

Go you your client app and replace the reply url with this redirect_uri.


问:
Use Python to open PHP file that contains JSON Array
Needing some help on where to start. I have inherited a file called data.php which
consist of an array shaped as follows:

```<code><?php
error_reporting(0);
$items=array (
0 =>
array (
'name' => 'Ted',
'size' => 'Large',
'sleeve' => 'Short',
'color' => 'Red',
),

);
$unObiect->items = $items;
$json = json_encode($unObiect);
echo($json);
?>
</code>```

There are actually about one hundred arrays in the file. I am trying to open the file, search an element of the array
and replace a value. Not concerned about the replace part yet just trying to open the file and loop thru the array. I'm not sure how to actually open the file in Python and loop it. I have tried

```<code>with open("data.php") as raw:
    for items in raw:
        print(items)
</code>```

This opens the file but seems to be reading by line which I expected. How can it be opened and loop thru as an array,
something like

```<code>with open("data.php") as raw:
for items in raw['name']:
       print(items)
</code>```

Where I can get an element of the array without going thru every line and seeing if that line contains 'name' then splitting the line to get to the value after the '=>'.  I guess basically looking to open the file and loop the
array. I know there are other post similar to this but I guess I'm not sure if I'm actually opening a php file as a text file somebody named with php or an actual php file that has an actual json array. Hope this makes sense.

Edit:
From a comment I took suggestion to execute the php from the python. Using the following I was able to do this:

```<code>result = subprocess.run(
['php', 'data.php'],
stdout=subprocess.PIPE,
check=True
)
print(result.stdout)
</code>```

Not sure now what to do with the result.stdout, how to iterate thru it. This returns a byte-string.

答:
```<code>Python 3.6.7 (default, Oct 22 2018, 11:32:17)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import os

In [2]: with os.popen('php data.php') as p:
   ...:     s = p.read()
   ...:

In [3]: s
Out[3]: '{"items":[{"name":"Ted","size":"Large","sleeve":"Short","color":"Red"}]}'

In [4]: import json

In [5]: r = json.loads(s)

In [6]: r
Out[6]:
{'items': [{'name': 'Ted',
   'size': 'Large',
   'sleeve': 'Short',
   'color': 'Red'}]}
</code>```

Body:
Needing some help on where to start. I have inherited a file called data.php which
consist of an array shaped as follows:

<?php
error_reporting(0);
$items=array (
0 =>
array (
'name' => 'Ted',
'size' => 'Large',
'sleeve' => 'Short',
'color' => 'Red',
),

);
$unObiect->items = $items;
$json = json_encode($unObiect);
echo($json);
?>

There are actually about one hundred arrays in the file. I am trying to open the file, search an element of the array
and replace a value. Not concerned about the replace part yet just trying to open the file and loop thru the array. I'm not sure how to actually open the file in Python and loop it. I have tried

with open("data.php") as raw:
    for items in raw:
        print(items)

This opens the file but seems to be reading by line which I expected. How can it be opened and loop thru as an array,
something like

with open("data.php") as raw:
for items in raw['name']:
       print(items)

Where I can get an element of the array without going thru every line and seeing if that line contains 'name' then splitting the line to get to the value after the '=>'.  I guess basically looking to open the file and loop the
array. I know there are other post similar to this but I guess I'm not sure if I'm actually opening a php file as a text file somebody named with php or an actual php file that has an actual json array. Hope this makes sense.

Edit:
From a comment I took suggestion to execute the php from the python. Using the following I was able to do this:

result = subprocess.run(
['php', 'data.php'],
stdout=subprocess.PIPE,
check=True
)
print(result.stdout)

Not sure now what to do with the result.stdout, how to iterate thru it. This returns a byte-string.


问:
The score is not updating. Can you please tell me what is wrong with the code?
The score is not updating. Please help me make the score update.
When I click the button with the function for 'addScore', the displayed score will not change to a new one.

I have tried a lot of things. Non of which have worked

var score = 0;

function addScore(){ score ++ }

function drawScore() {
 var c = document.getElementById("myCanvas");
 var ctx = c.getContext("2d");
 ctx.font = "16px Arial";
 ctx.fillStyle = "red";
 ctx.fillText("Score: " +score, 8, 20);
}

drawScore();
```

I am expecting it to update the score, but it does not. It remains at 0.

The problem has been solved bu the text keeps increasing and over laps it.

答:
You should use a different coding approach, keeping your CSS, and JavaScript separate from your HTML.

//<![CDATA[
/* external.js */
var doc, bod, M, I, S, Q, score = 0, addScore, drawScore; // for use on other loads
addEventListener('load', function(){ // make yourself a tiny library
doc = document; bod = doc.body;
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
S = function(selector, within){
  var w = within || doc;
  return w.querySelector(selector);
}
Q = function(selector, within){
  var w = within || doc;
  return w.querySelectorAll(selector);
}
addScore = function(){
  return ++score;
}
var canvas = I('canvas'), ctx = canvas.getContext('2d'), add = I('add');
ctx.font = '16px Arial'; ctx.fillStyle = 'red';
drawScore = function(){
  ctx.clearRect(0, 0, 160, 90); ctx.fillText('Score: '+score, 8, 20);
}
add.onclick = function(){
  addScore(); drawScore();// other functions or code here
};
}); // end load
//]]>```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* external.css */
*{
  box-sizing:border-box; padding:0; margin:0;
}
html,body{
  width:100%; height:100%;
}
body{
  background:#ccc;
}
#content{
  padding:7px;
}
#canvas{
  background:#fff;
}
#add{
  display:block; padding:3px 5px;
}</code>```

<!DOCTYPE html>

    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />

    <canvas id='canvas' width='160' height='90'></canvas>
    <input id='add' type='button' value='add score' />

```

Body:
The score is not updating. Please help me make the score update.
When I click the button with the function for 'addScore', the displayed score will not change to a new one.

I have tried a lot of things. Non of which have worked

var score = 0;

function addScore(){ score ++ }

function drawScore() {
 var c = document.getElementById("myCanvas");
 var ctx = c.getContext("2d");
 ctx.font = "16px Arial";
 ctx.fillStyle = "red";
 ctx.fillText("Score: " +score, 8, 20);
}

drawScore();

I am expecting it to update the score, but it does not. It remains at 0.

The problem has been solved bu the text keeps increasing and over laps it.

Body:
You should use a different coding approach, keeping your CSS, and JavaScript separate from your HTML.

//<![CDATA[
/* external.js */
var doc, bod, M, I, S, Q, score = 0, addScore, drawScore; // for use on other loads
addEventListener('load', function(){ // make yourself a tiny library
doc = document; bod = doc.body;
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
S = function(selector, within){
  var w = within || doc;
  return w.querySelector(selector);
}
Q = function(selector, within){
  var w = within || doc;
  return w.querySelectorAll(selector);
}
addScore = function(){
  return ++score;
}
var canvas = I('canvas'), ctx = canvas.getContext('2d'), add = I('add');
ctx.font = '16px Arial'; ctx.fillStyle = 'red';
drawScore = function(){
  ctx.clearRect(0, 0, 160, 90); ctx.fillText('Score: '+score, 8, 20);
}
add.onclick = function(){
  addScore(); drawScore();// other functions or code here
};
}); // end load
//]]>

/* external.css */
*{
  box-sizing:border-box; padding:0; margin:0;
}
html,body{
  width:100%; height:100%;
}
body{
  background:#ccc;
}
#content{
  padding:7px;
}
#canvas{
  background:#fff;
}
#add{
  display:block; padding:3px 5px;
}

<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div id='content'>
    <canvas id='canvas' width='160' height='90'></canvas>
    <input id='add' type='button' value='add score' />
  </div>
</body>
</html>


问:
Dict comprehension not working like I thought it does. What am I doing wrong?
Dict comprehension with if-else condition does not seem to be using the if block at all. It always goes to the else block even when it should not.

I am trying to use dict comprehension with if condition in python to determine the number of occurrences of characters in a string. However, the if condition never seems to be satisfied (when it really should be). Only the else condition seems to be satisfied

def letter_count(input_str):
    letter_count_map = {}

    letter_count_map = {letter: letter_count_map[letter]+1 if letter in
                        letter_count_map.keys() else 1
                        for letter in input_str}
    print(letter_count_map)

letter_count("serendipity")
```

<p>Expected result:</p>

```{'s': 1, 'e': 2, 'r': 1, 'n': 1, 'd': 1, 'i': 2, 'p': 1, 't': 1, 'y': 1}
```

<p>Actual result:</p>

```{'s': 1, 'e': 1, 'r': 1, 'n': 1, 'd': 1, 'i': 1, 'p': 1, 't': 1, 'y': 1}
```

What am I doing wrong?

答:
letter_count_map isn't assigned its new value until after the dict comprehension is fully evaluated.  Before that happens, it's just the empty dict, and so nothing will be in its keys().  What you're trying to do should instead be done with a loop instead of a comprehension:

```<code>letter_count_map = {}
for letter in input_str:
    letter_count_map[letter] = letter_count_map[letter]+1 if letter in letter_count_map.keys() else 1
</code>```

Body:
Dict comprehension with if-else condition does not seem to be using the if block at all. It always goes to the else block even when it should not.

I am trying to use dict comprehension with if condition in python to determine the number of occurrences of characters in a string. However, the if condition never seems to be satisfied (when it really should be). Only the else condition seems to be satisfied

def letter_count(input_str):
    letter_count_map = {}

    letter_count_map = {letter: letter_count_map[letter]+1 if letter in
                        letter_count_map.keys() else 1
                        for letter in input_str}
    print(letter_count_map)

letter_count("serendipity")

Expected result:

{'s': 1, 'e': 2, 'r': 1, 'n': 1, 'd': 1, 'i': 2, 'p': 1, 't': 1, 'y': 1}

Actual result:

{'s': 1, 'e': 1, 'r': 1, 'n': 1, 'd': 1, 'i': 1, 'p': 1, 't': 1, 'y': 1}

What am I doing wrong?

Body:
letter_count_map isn't assigned its new value until after the dict comprehension is fully evaluated.  Before that happens, it's just the empty dict, and so nothing will be in its keys().  What you're trying to do should instead be done with a loop instead of a comprehension:

letter_count_map = {}
for letter in input_str:
    letter_count_map[letter] = letter_count_map[letter]+1 if letter in letter_count_map.keys() else 1


问:
How do I compare effectiveness of different linear regression models
I have a dataframe which contains three more or less significant correlations between target column and other columns ( LinarRegressionModel.coef_ from sklearn shows 57, 97 and 79). And I don't know what exact model to choose: should I use only most correlated column for regression or use regression with all three predictors. Is there any way to compare models effectiveness? Sorry, I'm very new to data analysis, I couldn't google any tools for this task</p>

答:
Well first at all, you must know that when we are choosing the best model to apply to new data, we are going to choose the best model to fit out of sample data, which is the kind of samples that might are not present in the training process, after all, you want to predict new probabilities or cases. In your case, predict a new number.

So, how can we do this? Well, the best is to use metrics which can help us to choose which model is better for our dataset.

There are so many kinds of metrics for regression:

MAE: Mean absolute error is the mean of the absolute value of the errors. This is the easiest of the metrics to understand since it’s just the average error.

MSE: Mean squared error is the mean of the squared error. It’s more popular than a mean absolute error because the focus is geared more towards large errors.

RMSE: Root means the squared error is the square root of the mean squared error. This is one of the most popular of the evaluation metrics because root means the squared error is interpretable in the same units as the response vector or y units, making it easy to relate its information.

RAE: Relative absolute error, also known as the residual sum of a square, where y bar is a mean value of y, takes the total absolute error and normalizes it by dividing by the total absolute error of the simple predictor.

You can work with any of these, but I highly recommend to use MSE and RMSE.


问:
Multi threading question
I'm trying to make a server program for a game, I need to run 3 extra threads in a windows form app. all the threads needs to be able to access the same variables, (thread1: is going to be pulling user commands from my database and executing them, thread2: is going to be updating all the users data and thread3: is going to be sending all the new variables back to the database.) I've looked into background threads and I'm not sure if thats going to do what i want them todo (they look like they could run my code but it looks like they would have a hard time working with the same variables for the all the threads.)

So i guess my question is, is this possible and what is best way to accomplish this, would background workers and invoke do the trick? what problems would i be looking at doing that, anyone have any better idea.

On a side note i had another question thats related ive tried a bunch of times to accomplish this using just simple threads. Now from what i understand doing all of my work on another thread should not lock up my ui, however it does. maybe im doing thread the wrong way, my code looks something like

```<code>dim newthread as new system.threading.thread(addressof runmycode)
newthread.start()`
</code>```

this code isn't exact but why would using threading like this lock up the UI? Shouldn't it be running separately?

答:
You need to create a 'new' instance of the object class to be 'threaded' and expose the function you want to call, e.g.</p>

```<code>Public Class MyNewCode
    Public Function runmycode()

        ' My code goes here '

    End Function
End Class

Public Class frmMain ' or under an onClick event or whatever.... '
    Dim s As New MyNewCode ' This is the class above '
    t = New System.Threading.Thread(AddressOf s.runmycode) ' This is the function above '
    t.start()
End Class
</code>```

Title: Multi threading question

Body:
I'm trying to make a server program for a game, I need to run 3 extra threads in a windows form app. all the threads needs to be able to access the same variables, (thread1: is going to be pulling user commands from my database and executing them, thread2: is going to be updating all the users data and thread3: is going to be sending all the new variables back to the database.) I've looked into background threads and I'm not sure if thats going to do what i want them todo (they look like they could run my code but it looks like they would have a hard time working with the same variables for the all the threads.)

So i guess my question is, is this possible and what is best way to accomplish this, would background workers and invoke do the trick? what problems would i be looking at doing that, anyone have any better idea.

On a side note i had another question thats related ive tried a bunch of times to accomplish this using just simple threads. Now from what i understand doing all of my work on another thread should not lock up my ui, however it does. maybe im doing thread the wrong way, my code looks something like

dim newthread as new system.threading.thread(addressof runmycode)
newthread.start()`

this code isn't exact but why would using threading like this lock up the UI? Shouldn't it be running separately?

Body:
You need to create a 'new' instance of the object class to be 'threaded' and expose the function you want to call, e.g.

Public Class MyNewCode
    Public Function runmycode()

        ' My code goes here '

    End Function
End Class

Public Class frmMain ' or under an onClick event or whatever.... '
    Dim s As New MyNewCode ' This is the class above '
    t = New System.Threading.Thread(AddressOf s.runmycode) ' This is the function above '
    t.start()
End Class