问:
jQuery update value with its parent in format
I have html markup like this

```<code><input type="hidden" value="" id="shortcode_selected_package" name="shortcode_selected_package">
<div class="selected-packages-wrap">
    <div class="shortcode-wrap">
        <a class="data-remove" href="#" data-id="417" data-name="Test New Packs">-</a><label>Test New Packs</label>
        <span class="checkbox-wrap">
            <span><input type="checkbox" value="5">10 GB</span>
            <span><input type="checkbox" value="26">Sony</span>
        </span>
    </div>

    <div class="shortcode-wrap">
        <a class="data-remove" href="#" data-id="220" data-name="New custom pack">-</a><label>New custom pack</label>
        <span class="checkbox-wrap">
            <span><input type="checkbox" value="5">10 GB</span>
            <span><input type="checkbox" value="25">Unlimited Calls</span>
        </span>
    </div>

    </div>
</code>```

Here you can see in the first div element there are two checkbox with value 5, 26 (10 GB and Sony). So when someone check the checkbox of first div ten its value should be added with its parent value in the shortcode_selected_package div.

So lets say when user check both 10 GB and Sony then the value of the div should be like this

```<code>417[5|26]
</code>```

if user checks the checkbox for the 2nd div then the value should be like this

```<code>417[5|26],220[5,25]
</code>```

But if user unchecks any checkbox then its value should be remove from the set value. Like if user unchecks Unlimited Calls from the 2nd div then the value should be like

```<code>417[5|26],220[5,25]
</code>```

I have tried this code but the values are not updating

```<code>$('body').on('click', '.selected-packages-wrap input[type=checkbox]', function() {
    var PackageSelected = $('input#shortcode_selected_package').val();
    var selectedVal = this.value;
    var ParentId = $(this).parents('.shortcode-wrap').find('a.data-remove').attr('data-id');

    if( this.checked ) {
      selectPackage(ParentId, selectedVal, PackageSelected);
    }
    else {
      unselectPackage(ParentId, selectedVal, PackageSelected);
    }
  });

  function selectPackage(ParentId, selectedVal, PackageSelected) {
    Packages = PackageSelected.split(',');
    var Arr = [];
    if(jQuery.inArray(ParentId, Packages) !== -1) {
      $.each( Packages, function( key, val ) {
        if( val == ParentId ) {
          Packages[key] = val.replace(val, val + '[' + selectedVal + ']');
          Arr.push(Packages);
        }
      });

      console.log(Arr[0]);
    }

  }
</code>```

答:
First, I think that you should put the data-id of the link as a checkbox attribute or better yet at each div holding the checkboxes (it will be more convienient for selection instead of doing:

```<code>.parents('.shortcode-wrap').find('a.data-remove').attr('data-id');
</code>```

)

Then what you do is every time on change or on click of any of the checkboxes you loop through the divs with class of shortcode wrap.

```<code>$('.selected-packages-wrap input[type=checkbox]').on('change', function() {
  var checkboxes_data = [];
  // Loop through the divs
  for(var divs_count = 0; divs_count < $('.shortcode-wrap').length; divs_count++) {
    checkboxes_data[divs_count] = {div_id: $('.shortcode-wrap:eq(' + divs_count + ')').attr('data-id'), checkboxes_id: [],}
    // Loop through the checkboxes
    for(var chBox_count = 0; chBox < $('.shortcode-wrap:eq(' + divs_count + ') input[type=checkbox]').length; chBox_count++) {
      var $.current_checkbox = $('.shortcode-wrap:eq(' + divs_count + ') input[type=checkbox]:eq(' + chBox_count + ')');
      // If the checkbox is checked add the value to the array
      if($.current_checkbox.is(":checked")) {
        checkboxes_data[divs_count].checkboxes_id.push($.current_checkbox.val()
      }
    }
  }

  var final_value = '';
  // Goes trough the the newly created array adds the div value followed by the corresponding checkboxes value
  checkboxes_data.forEach(function(div) {
    var checkbox_ids = div.checkbox_ids.join(", ");
    final_value += div.div_id + '[' + div.checkbox_ids + '], ';
  });

  $('#shortcode_selected_package').val(final_value);
});
</code>```

Body:
I have html markup like this

<input type="hidden" value="" id="shortcode_selected_package" name="shortcode_selected_package">

        -Test New Packs

            <input type="checkbox" value="5">10 GB
            <input type="checkbox" value="26">Sony

        -New custom pack

            <input type="checkbox" value="5">10 GB
            <input type="checkbox" value="25">Unlimited Calls

Here you can see in the first div element there are two checkbox with value 5, 26 (10 GB and Sony). So when someone check the checkbox of first div ten its value should be added with its parent value in the shortcode_selected_package div.

So lets say when user check both 10 GB and Sony then the value of the div should be like this

417[5|26]

if user checks the checkbox for the 2nd div then the value should be like this

417[5|26],220[5,25]

But if user unchecks any checkbox then its value should be remove from the set value. Like if user unchecks Unlimited Calls from the 2nd div then the value should be like

417[5|26],220[5,25]

I have tried this code but the values are not updating

$('body').on('click', '.selected-packages-wrap input[type=checkbox]', function() {
    var PackageSelected = $('input#shortcode_selected_package').val();
    var selectedVal = this.value;
    var ParentId = $(this).parents('.shortcode-wrap').find('a.data-remove').attr('data-id');

    if( this.checked ) {
      selectPackage(ParentId, selectedVal, PackageSelected);
    }
    else {
      unselectPackage(ParentId, selectedVal, PackageSelected);
    }
  });

  function selectPackage(ParentId, selectedVal, PackageSelected) {
    Packages = PackageSelected.split(',');
    var Arr = [];
    if(jQuery.inArray(ParentId, Packages) !== -1) {
      $.each( Packages, function( key, val ) {
        if( val == ParentId ) {
          Packages[key] = val.replace(val, val + '[' + selectedVal + ']');
          Arr.push(Packages);
        }
      });

      console.log(Arr[0]);
    }

  }

Body:
First, I think that you should put the data-id of the link as a checkbox attribute or better yet at each div holding the checkboxes (it will be more convienient for selection instead of doing:

.parents('.shortcode-wrap').find('a.data-remove').attr('data-id');

)

Then what you do is every time on change or on click of any of the checkboxes you loop through the divs with class of shortcode wrap.

$('.selected-packages-wrap input[type=checkbox]').on('change', function() {
  var checkboxes_data = [];
  // Loop through the divs
  for(var divs_count = 0; divs_count < $('.shortcode-wrap').length; divs_count++) {
    checkboxes_data[divs_count] = {div_id: $('.shortcode-wrap:eq(' + divs_count + ')').attr('data-id'), checkboxes_id: [],}
    // Loop through the checkboxes
    for(var chBox_count = 0; chBox < $('.shortcode-wrap:eq(' + divs_count + ') input[type=checkbox]').length; chBox_count++) {
      var $.current_checkbox = $('.shortcode-wrap:eq(' + divs_count + ') input[type=checkbox]:eq(' + chBox_count + ')');
      // If the checkbox is checked add the value to the array
      if($.current_checkbox.is(":checked")) {
        checkboxes_data[divs_count].checkboxes_id.push($.current_checkbox.val()
      }
    }
  }

  var final_value = '';
  // Goes trough the the newly created array adds the div value followed by the corresponding checkboxes value
  checkboxes_data.forEach(function(div) {
    var checkbox_ids = div.checkbox_ids.join(", ");
    final_value += div.div_id + '[' + div.checkbox_ids + '], ';
  });

  $('#shortcode_selected_package').val(final_value);
});


来源: stackexchange

问:
What technology to Process JSON data in Node.JS to compare values to MongoDB?
Good evening,

I'm having a tough time figuring out what technology I should pair with my current stack. I don't necessarily need to know how to implement it, however if you're happy to oblige, I'll be happy to accept it :).

What I'm trying to achieve?
I've got another server making HTTP post requests every second to my Node.JS server. The posts are in the form of JSON data. My ultimate goal is to grab the data and look for the value in a MongoDB. HERE is where I'm not sure how I should implement? Node.js DATATables? Just leave it in JSON and make calls every second to the DB? ClientSideDB like Loki.js? What ideas do you have?

Then, present the MongoDB data client side...But that's later.

My current stack is a MEAN stack: Mongo Database, Express, Node.js server side, and AngularJS and Bootstrap Client Side.

Here's some code even though that's not really what this is about:

```<code>var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var router = express.Router();

router.post('/', function(req, res) {
    console.log(req.body.results);     // Just returning JSON results to console for now
    res.end();
});

app.use('/api', router);

app.listen(port);
console.log('Magic happens on port ' + port);
</code>```

答:
If you want to proceed with Node.js, MongoDb then i'll suggest you should start using a backend framework like sails.js. Its build on top of Express.js and has many handy features. Its based on MVC pattern but you
can use angular for client side also.

Get started with Sails.js

Sails.js Documentation

ContentLicense: CC BY-SA 3.0

Body:
Good evening,

I'm having a tough time figuring out what technology I should pair with my current stack. I don't necessarily need to know how to implement it, however if you're happy to oblige, I'll be happy to accept it :).

What I'm trying to achieve?
I've got another server making HTTP post requests every second to my Node.JS server. The posts are in the form of JSON data. My ultimate goal is to grab the data and look for the value in a MongoDB. HERE is where I'm not sure how I should implement? Node.js DATATables? Just leave it in JSON and make calls every second to the DB? ClientSideDB like Loki.js? What ideas do you have?

Then, present the MongoDB data client side...But that's later.

My current stack is a MEAN stack: Mongo Database, Express, Node.js server side, and AngularJS and Bootstrap Client Side.

Here's some code even though that's not really what this is about:

var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var router = express.Router();

router.post('/', function(req, res) {
    console.log(req.body.results);     // Just returning JSON results to console for now
    res.end();
});

app.use('/api', router);

app.listen(port);
console.log('Magic happens on port ' + port);


问:
PHP syntax error - using elseif
This is the code that I wrote and it's not working. it's suppose to ask the user a odd number and check is it correct.

Code:

```<code>$guess = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit)){
        if ($guess/2 %0){
                echo "the number you are guessing is not odd";
        }elseif{

         ($guess<$rand)
                echo "Your Guess is Smaller than the secret number";
        }elseif{
                ($guess>$rand)
                         echo "Your Guess is bigger than the secret number";
        }else{
                          ($guess==$rand)
        echo "you guessed currectly. now try anouthe number!";}

else
        header("Location: index.php");
                exit();}

?>
</code>```

答:
Can you try this?

You placed the '()' in your elseif wrong.

```<code><?php
$rand = rand(1, 99);

$guess  = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit))
{
    if($guess / 2 % 0)
    {
        echo "the number you are guessing is not odd";
    }
    elseif($guess < $rand)
    {
        echo "Your Guess is Smaller than the secret number";
    }
    elseif($guess > $rand)
    {
        echo "Your Guess is bigger than the secret number";
    }
    elseif($guess == $rand)
    {
        echo "you guessed currectly. now try anouthe number!";
    }
}
else
{
    header("Location: index.php");
    exit();
}

?>
</code>```

I have not tested this code, so i need your feedback. Edit: You've confirmed this worked.

I'd like to provide you the manual about elseif:
http://php.net/manual/en/control-structures.elseif.php

Please consider easier/cleaner coding. Personally I like to use ':' instead of '{}', it's less code and easier to read when you use HTML mixed with PHP like:

```<code><?php
$rand = rand(1, 99);

$guess  = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit)):
    if($guess / 2 % 0):
        echo "the number you are guessing is not odd";
    elseif($guess < $rand):
        echo "Your Guess is Smaller than the secret number";
    elseif($guess > $rand):
        echo "Your Guess is bigger than the secret number";
    elseif($guess == $rand):
        echo "you guessed currectly. now try anouthe number!";
else:
    header("Location: index.php");
    exit();
endif;
?>
</code>```

And don't forget to check the $_POST data.

Same goes for array, but thats a side note:

```<code>$arr = array(1 => 'hi', 2 => 'hello'); // old
$arr = [1 => 'hi', 2 => 'hello']; // new
</code>```

Title: PHP syntax error - using elseif

Body:
This is the code that I wrote and it's not working. it's suppose to ask the user a odd number and check is it correct.

Code:

$guess = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit)){
        if ($guess/2 %0){
                echo "the number you are guessing is not odd";
        }elseif{

         ($guess<$rand)
                echo "Your Guess is Smaller than the secret number";
        }elseif{
                ($guess>$rand)
                         echo "Your Guess is bigger than the secret number";
        }else{
                          ($guess==$rand)
        echo "you guessed currectly. now try anouthe number!";}

else
        header("Location: index.php");
                exit();}

?>

Body:
Can you try this?

You placed the '()' in your elseif wrong.

<?php
$rand = rand(1, 99);

$guess  = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit))
{
    if($guess / 2 % 0)
    {
        echo "the number you are guessing is not odd";
    }
    elseif($guess < $rand)
    {
        echo "Your Guess is Smaller than the secret number";
    }
    elseif($guess > $rand)
    {
        echo "Your Guess is bigger than the secret number";
    }
    elseif($guess == $rand)
    {
        echo "you guessed currectly. now try anouthe number!";
    }
}
else
{
    header("Location: index.php");
    exit();
}

?>

I have not tested this code, so i need your feedback. Edit: You've confirmed this worked.

I'd like to provide you the manual about elseif:
http://php.net/manual/en/control-structures.elseif.php

Please consider easier/cleaner coding. Personally I like to use ':' instead of '{}', it's less code and easier to read when you use HTML mixed with PHP like:

<?php
$rand = rand(1, 99);

$guess  = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit)):
    if($guess / 2 % 0):
        echo "the number you are guessing is not odd";
    elseif($guess < $rand):
        echo "Your Guess is Smaller than the secret number";
    elseif($guess > $rand):
        echo "Your Guess is bigger than the secret number";
    elseif($guess == $rand):
        echo "you guessed currectly. now try anouthe number!";
else:
    header("Location: index.php");
    exit();
endif;
?>

And don't forget to check the $_POST data.

Same goes for array, but thats a side note:

$arr = array(1 => 'hi', 2 => 'hello'); // old
$arr = [1 => 'hi', 2 => 'hello']; // new


问:
 element adding a random space after word
I'm using Angular4 and I'm noticing this really weird issue where one of my span elements adds an extra space to the end of a word like this:

The only CSS properties being set are font-family, -webkit-font-smoothing, line-height and box-sizing.

I tried changing the word-spacing and white-space properties but that did not work either. I've never encountered this issue before so any advice would be helpful

答:
in your css, just put display:inline-block to span elements</p>

```<code>.key-ingredients span{
    display:inline-block;
}
</code>```

Title: <span> element adding a random space after word

Body:
in your css, just put display:inline-block to span elements

.key-ingredients span{
    display:inline-block;
}


问:
How do I change the color of a specific printed letter in python?
I am trying to make a short quiz and I want to display Incorrect Answer in red.
Welcome to my Quiz!
Would you like to begin?: yes
Goodluck
What is the capital of France?:  france # random answer
Incorrect Answer # i am trying to display it in red.

My code is:

```<code>print ("Welcome to my Quiz!")
begin = input("Would you like to begin?: ")
if begin == ("yes")  or begin == ("Yes"):
print ("Goodluck")
Q1 = input("What is the capital of France?:  ")
if Q1 == ("Paris") or Q1 == ("paris"):
    print ("Correct Answer!")
    print (" ")
else:
    print ("Incorrect Answer")
    print (" ")

Q2 = input("What is the capital of India?:  ")
if Q2 == ("New Delhi") or Q2 == ("new delhi"):
    print ("Correct Answer!")
    print (" ")
else:
    print ("Incorrect Answer")
    print (" ")

else:
    print ("Goodbye :)")
</code>```

Body:
I am trying to make a short quiz and I want to display Incorrect Answer in red.
Welcome to my Quiz!
Would you like to begin?: yes
Goodluck
What is the capital of France?:  france # random answer
Incorrect Answer # i am trying to display it in red.

My code is:

print ("Welcome to my Quiz!")
begin = input("Would you like to begin?: ")
if begin == ("yes")  or begin == ("Yes"):
print ("Goodluck")
Q1 = input("What is the capital of France?:  ")
if Q1 == ("Paris") or Q1 == ("paris"):
    print ("Correct Answer!")
    print (" ")
else:
    print ("Incorrect Answer")
    print (" ")

Q2 = input("What is the capital of India?:  ")
if Q2 == ("New Delhi") or Q2 == ("new delhi"):
    print ("Correct Answer!")
    print (" ")
else:
    print ("Incorrect Answer")
    print (" ")

else:
    print ("Goodbye :)")

Body:
Yeah, thats possible:

print('\033[31m' + "Incorrect Answer" +'\033[0m')

Here some more colors:

# Regular Colors
Black="\[\033[0;30m\]"        # Black
Red="\[\033[0;31m\]"          # Red
Green="\[\033[0;32m\]"        # Green
Yellow="\[\033[0;33m\]"       # Yellow
Blue="\[\033[0;34m\]"         # Blue
Purple="\[\033[0;35m\]"       # Purple
Cyan="\[\033[0;36m\]"         # Cyan
White="\[\033[0;37m\]"        # White

# Bold
BBlack="\[\033[1;30m\]"       # Black
BRed="\[\033[1;31m\]"         # Red
BGreen="\[\033[1;32m\]"       # Green
BYellow="\[\033[1;33m\]"      # Yellow
BBlue="\[\033[1;34m\]"        # Blue
BPurple="\[\033[1;35m\]"      # Purple
BCyan="\[\033[1;36m\]"        # Cyan
BWhite="\[\033[1;37m\]"       # White

# Underline
UBlack="\[\033[4;30m\]"       # Black
URed="\[\033[4;31m\]"         # Red
UGreen="\[\033[4;32m\]"       # Green
UYellow="\[\033[4;33m\]"      # Yellow
UBlue="\[\033[4;34m\]"        # Blue
UPurple="\[\033[4;35m\]"      # Purple
UCyan="\[\033[4;36m\]"        # Cyan
UWhite="\[\033[4;37m\]"       # White

# Background
On_Black="\[\033[40m\]"       # Black
On_Red="\[\033[41m\]"         # Red
On_Green="\[\033[42m\]"       # Green
On_Yellow="\[\033[43m\]"      # Yellow
On_Blue="\[\033[44m\]"        # Blue
On_Purple="\[\033[45m\]"      # Purple
On_Cyan="\[\033[46m\]"        # Cyan
On_White="\[\033[47m\]"       # White

# High Intensty
IBlack="\[\033[0;90m\]"       # Black
IRed="\[\033[0;91m\]"         # Red
IGreen="\[\033[0;92m\]"       # Green
IYellow="\[\033[0;93m\]"      # Yellow
IBlue="\[\033[0;94m\]"        # Blue
IPurple="\[\033[0;95m\]"      # Purple
ICyan="\[\033[0;96m\]"        # Cyan
IWhite="\[\033[0;97m\]"       # White

# Bold High Intensty
BIBlack="\[\033[1;90m\]"      # Black
BIRed="\[\033[1;91m\]"        # Red
BIGreen="\[\033[1;92m\]"      # Green
BIYellow="\[\033[1;93m\]"     # Yellow
BIBlue="\[\033[1;94m\]"       # Blue
BIPurple="\[\033[1;95m\]"     # Purple
BICyan="\[\033[1;96m\]"       # Cyan
BIWhite="\[\033[1;97m\]"      # White

# High Intensty backgrounds
On_IBlack="\[\033[0;100m\]"   # Black
On_IRed="\[\033[0;101m\]"     # Red
On_IGreen="\[\033[0;102m\]"   # Green
On_IYellow="\[\033[0;103m\]"  # Yellow
On_IBlue="\[\033[0;104m\]"    # Blue
On_IPurple="\[\033[10;95m\]"  # Purple
On_ICyan="\[\033[0;106m\]"    # Cyan
On_IWhite="\[\033[0;107m\]"   # White

source: https://gist.github.com/vratiu/9780109

note: in the additional list, colors are formated for another language. To is on python "[" and "[\" have to be removed from the start and the end.


问:
Android calculating Velocity wtih Accelerometer data
Due to the power consuming GPS data, I would like to calculate the device speed with only the accelerometer x,y and z data. I have read a lot of questions about this topic and I tried many set-ups to find a satisfactory solution to calculate the speed when my device is in my car.
It seems so simple but nothing works, which drives me crazy.
Been trying the Sensor.TYPE_LINEAR_ACCELERATION and the Sensor.TYPE_ACCELEROMETER with removed gravity. Tried a Low Pass Filter on the Linear acceleration data. Unfortunately all with no succes.
Looks like the calculated  speed is correct but testing in my car the calculated speed doesn't get higher then about 2 m/s.

below a code snip

```<code>mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);

public void onSensorChanged(SensorEvent event) {
    if (event.sensor == mAccelerometer) {

        if (timestamp != 0) {
            final float dT = (event.timestamp - timestamp) * NS2S;

            lax = event.values[0];
            lay = event.values[1];
            laz = event.values[2];

            vx = vxo + lax * dT ;
            vy = vyo + lay * dT ;
            vz = vzo + laz * dT ;

            speed = (float) (Math.sqrt(vx*vx + vy*vy + vz*vz)) ;
            if (speed < 0.01) {speed = 0 ; }
            tv_speed.setText(String.valueOf(speed));

        }
        timestamp = event.timestamp;
    }
}
</code>```

Hope someone can help, thanks a lot.

答:
Although at the developer.android.com site it is stated clearly that

you could use the linear accelerometer to see how fast your car is going"

But I did not find anything (in testing or in examples or code) that showed this is really true.

Now, unfortunately, I am convinced that it is not possible to calculate the speed of a car with the linear accelerometer.

Body:
Due to the power consuming GPS data, I would like to calculate the device speed with only the accelerometer x,y and z data. I have read a lot of questions about this topic and I tried many set-ups to find a satisfactory solution to calculate the speed when my device is in my car.
It seems so simple but nothing works, which drives me crazy.
Been trying the Sensor.TYPE_LINEAR_ACCELERATION and the Sensor.TYPE_ACCELEROMETER with removed gravity. Tried a Low Pass Filter on the Linear acceleration data. Unfortunately all with no succes.
Looks like the calculated  speed is correct but testing in my car the calculated speed doesn't get higher then about 2 m/s.

below a code snip

mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);

public void onSensorChanged(SensorEvent event) {
    if (event.sensor == mAccelerometer) {

        if (timestamp != 0) {
            final float dT = (event.timestamp - timestamp) * NS2S;

            lax = event.values[0];
            lay = event.values[1];
            laz = event.values[2];

            vx = vxo + lax * dT ;
            vy = vyo + lay * dT ;
            vz = vzo + laz * dT ;

            speed = (float) (Math.sqrt(vx*vx + vy*vy + vz*vz)) ;
            if (speed < 0.01) {speed = 0 ; }
            tv_speed.setText(String.valueOf(speed));

        }
        timestamp = event.timestamp;
    }
}

Hope someone can help, thanks a lot.


问:
canonical problems list
Does anyone known of a a good reference for canonical CS problems?

I'm thinking of things like "the sorting problem", "the bin packing problem", "the travailing salesman problem" and what not.

edit: websites preferred

答:
You definitely want to look at NIST's Dictionary of Algorithms and Data Structures. It's got the traveling salesman problem, the Byzantine generals problem, the dining philosophers' problem, the knapsack problem (= your "bin packing problem", I think), the cutting stock problem, the eight queens problem, the knight's tour problem, the busy beaver problem, the halting problem, etc. etc.

It doesn't have the firing squad synchronization problem (I'm surprised about that omission) or the Jeep problem (more logistics than computer science).

Interestingly enough there's a blog on codinghorror.com which talks about some of these in puzzle form. (I can't remember whether I've read Smullyan's book cited in the blog, but he is a good compiler of puzzles & philosophical musings. Martin Gardner and Douglas Hofstadter and H.E. Dudeney are others.)

Also maybe check out the Stony Brook Algorithm Repository.

(Or look up "combinatorial problems" on google, or search for "problem" in Wolfram Mathworld or look at Hilbert's problems, but in all these links many of them are more pure-mathematics than computer science.)

OwnerDisplayName: BCS

ContentLicense: CC BY-SA 2.5

Title: canonical problems list

LastEditorDisplayName: Hank Gay

OwnerDisplayName: Jason S


问:
REST API for Azure SQL DB on Linux Machine
Question. I would like to create a REST API for the data stored in an Azure SQL DB that will allow me to do GET and POST operation using Python. Currently I managed to print the results of my query on the terminal but how do I convert it to JSON format and allow it to run 24/7 on linux (perhaps change port?)? Below is my script:

```<code>import pyodbc
from flask import Flask, jsonify, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class Energy(Resource):
    def get(self):
        server = 'testserver.database.windows.net'
        database = 'testdb'
        username = 'admin'
        password = '735t'
        driver= '{ODBC Driver 13 for SQL Server}'
        connexion = pyodbc.connect('DRIVER='+driver+';PORT=1433;SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
        cursor = connexion.cursor()
        cursor.execute("SELECT TOP (100) * FROM [dbo].[Power_Meter]")
        row = cursor.fetchone()
        while row:
           GeneratedCode = str(row[0])
           ReportedDate = str(row[1])
           print (str(row[0]) + " " + str(row[1]))
           row = cursor.fetchone()

        rest_row = jsonify(row)
        return rest_row

api.add_resource(Energy, '/DPM')

if __name__ == '__main__':
    app.run(debug=True)
</code>```

and this is the output result on localhost:5000/DPM

```<code>null
</code>```

Can anyone suggest me how to go about solving this issue? Thanks

答:
If you want to run your script 24/7 on Linux, you could execute it as a background task. Using nohup python sql.py>> test.log &

```<code>man nohup

nohup - run a command immune to hangups, with output to a non-tty

& to the command line to run in the background:
</code>```

If you want to change port, just change like below:

```<code>app.run(host='0.0.0.0',port=5000)
</code>```

I suggest you could store output to a file. Then you could parse  data to json format.

Body:
Question. I would like to create a REST API for the data stored in an Azure SQL DB that will allow me to do GET and POST operation using Python. Currently I managed to print the results of my query on the terminal but how do I convert it to JSON format and allow it to run 24/7 on linux (perhaps change port?)? Below is my script:

import pyodbc
from flask import Flask, jsonify, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class Energy(Resource):
    def get(self):
        server = 'testserver.database.windows.net'
        database = 'testdb'
        username = 'admin'
        password = '735t'
        driver= '{ODBC Driver 13 for SQL Server}'
        connexion = pyodbc.connect('DRIVER='+driver+';PORT=1433;SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
        cursor = connexion.cursor()
        cursor.execute("SELECT TOP (100) * FROM [dbo].[Power_Meter]")
        row = cursor.fetchone()
        while row:
           GeneratedCode = str(row[0])
           ReportedDate = str(row[1])
           print (str(row[0]) + " " + str(row[1]))
           row = cursor.fetchone()

        rest_row = jsonify(row)
        return rest_row

api.add_resource(Energy, '/DPM')

if __name__ == '__main__':
    app.run(debug=True)

and this is the output result on localhost:5000/DPM

null

Can anyone suggest me how to go about solving this issue? Thanks

Body:
If you want to run your script 24/7 on Linux, you could execute it as a background task. Using nohup python sql.py>> test.log &

man nohup

nohup - run a command immune to hangups, with output to a non-tty

& to the command line to run in the background:

If you want to change port, just change like below:

app.run(host='0.0.0.0',port=5000)

I suggest you could store output to a file. Then you could parse  data to json format.


问:
conditionally show/hide the icon in angular

Hi,

The below code shows the bootstrap bell notification icon and a red circle in the template.

```<code><a href dropdownToggle (click)="false">
        <i class="glyphicon glyphicon-bell notification-icon">
         {{cookieData.search_unread_count}}
        </i>
</a>
</code>```

This code {{cookieData.search_unread_count}} will get the count from the component and add the count to the bell icon's above red circular icon. Here the challenge is i want to hide the icon based on if the count is 0 then i want to hide the red circle above the bell and if count is greater than 0 then i have to show the red circle above the bell icon.

So conditionally how to add this?

答:
You're looking for *ngIf, please see below

```<code><a href dropdownToggle (click)="false" *ngIf="cookieData.search_unread_count > 0">
    <i class="glyphicon glyphicon-bell notification-icon">
        {{cookieData.search_unread_count}}
    </i>
</a>
</code>```

This will only display the icon when the count is greater than 0.

It is better to use *ngIf apposed to [hidden] as *ngIf actually removes the html and does not just add a display: none; to the element.

Body:
Hi,

The below code shows the bootstrap bell notification icon and a red circle in the template.

         {{cookieData.search_unread_count}}

This code {{cookieData.search_unread_count}} will get the count from the component and add the count to the bell icon's above red circular icon. Here the challenge is i want to hide the icon based on if the count is 0 then i want to hide the red circle above the bell and if count is greater than 0 then i have to show the red circle above the bell icon.

So conditionally how to add this?

Body:
You're looking for *ngIf, please see below

<a href dropdownToggle (click)="false" *ngIf="cookieData.search_unread_count > 0">
    <i class="glyphicon glyphicon-bell notification-icon">
        {{cookieData.search_unread_count}}
    </i>
</a>

This will only display the icon when the count is greater than 0.

It is better to use *ngIf apposed to [hidden] as *ngIf actually removes the html and does not just add a display: none; to the element.


问:
Swift optional binding with check for several types
I have model for my class that may be instance of 2 different classes. Now i check that model is class i need with following:

```<code> guard let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as myClassOne? else {
                assertionFailure("Wrong model for RetailSalesVC")
                return
            }
</code>```

Now i want to check if model is class one OR model is class two. Is that possible to achieve?

Now i ended up with this (but without optional binding):

```<code>   guard (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassOne?) != nil)) ||
            (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassTwo?) != nil)) else {
                assertionFailure("Wrong model for \(self)")
                return
        }
</code>```

答:
```<code>    if unwrappedModel is ClassOne{
        print("this model is of type ClassOne")
    }
    else if unwrappedModel is ClassTwo{
        print("this model is of type ClassTwo")
    }
</code>```

Body:
I have model for my class that may be instance of 2 different classes. Now i check that model is class i need with following:

 guard let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as myClassOne? else {
                assertionFailure("Wrong model for RetailSalesVC")
                return
            }

Now i want to check if model is class one OR model is class two. Is that possible to achieve?

Now i ended up with this (but without optional binding):

   guard (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassOne?) != nil)) ||
            (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassTwo?) != nil)) else {
                assertionFailure("Wrong model for \(self)")
                return
        }


问:
Cannot kill Postgres process
I keep trying to kill a PostgreSQL process that is running on port 5432 to no avail. Whenever I type sudo lsof -i :5432, I see something like the below:

```<code>COMMAND  PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
postgres 587 postgres    4u  IPv6 0x218f97e9af5d0303      0t0  TCP *:postgresql (LISTEN)
postgres 587 postgres    5u  IPv4 0x218f97e9ae0f6c63      0t0  TCP *:postgresql (LISTEN)
</code>```

I then try to kill the process 587 in this example with sudo kill -9 587, but then another process automatically restarts on the same port! I have tried killing it on activity monitor as well to no avail. Please help?

Thanks,
Laura

答:
I have 9.5 and 9.6 installed, so

sudo su - postgres

/Library/PostgreSQL/9.6/bin/pg_ctl -D /Library/PostgreSQL/9.6/data stop

9.5 started ...

/Library/PostgreSQL/9.5/bin/pg_ctl -D /Library/PostgreSQL/9.5/data stop

Title: Cannot kill Postgres process

Body:
I keep trying to kill a PostgreSQL process that is running on port 5432 to no avail. Whenever I type sudo lsof -i :5432, I see something like the below:

COMMAND  PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
postgres 587 postgres    4u  IPv6 0x218f97e9af5d0303      0t0  TCP *:postgresql (LISTEN)
postgres 587 postgres    5u  IPv4 0x218f97e9ae0f6c63      0t0  TCP *:postgresql (LISTEN)

I then try to kill the process 587 in this example with sudo kill -9 587, but then another process automatically restarts on the same port! I have tried killing it on activity monitor as well to no avail. Please help?

Thanks,
Laura


问:
How do I retrieve a value from a property using Active Directory?
I'm trying to write a code that retrieves a user's email from the LDAP server. The user's email is in the 'mail' property, however, everytime I run it, the email returns "System.DirectoryServices.ResultPropertyValueCollection" instead of the user's email. Here is my code:

```<code>using (HostingEnvironment.Impersonate())
        {
            string server = "hello.world.com:389";
            string email = null;

            DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + server + "/DC=hello,DC=world,DC=com");
            DirectorySearcher dSearch = new DirectorySearcher(dEntry);
            dSearch.SearchScope = SearchScope.Subtree;
            dSearch.Filter = "(&(objectClass=users)(cn=" + lanID + "))";
            dSearch.PropertiesToLoad.Add("mail");

            SearchResult result = dSearch.FindOne();

            if (result != null)
            {
                email = result.Properties["mail"].ToString();
                return email;
            }
            else return email = null;
        }
</code>```

The code takes a user's employee id (lanID) and returns that userID's email (the value under 'mail' property). How should I do so I don't get System.DirectoryServices.ResultPropertyValueCollection but an actual email?

答:
You need to use SearchResult.GetDirectoryEntry() Method to get the directory entry which corresponds to this SearchResult.

Retrieves the DirectoryEntry that corresponds to the SearchResult from
  the Active Directory Domain Services hierarchy. Use GetDirectoryEntry when you want to look at the live entry instead of the entry that was returned through DirectorySearcher, or when you want to invoke a method on the object that was returned.

  --emphasis mine.

Use the below code:

```<code>DirectoryEntry user = result.GetDirectoryEntry();
string distinguishedName = user.Properties["mail"].Value.ToString();
</code>```

Body:
I'm trying to write a code that retrieves a user's email from the LDAP server. The user's email is in the 'mail' property, however, everytime I run it, the email returns "System.DirectoryServices.ResultPropertyValueCollection" instead of the user's email. Here is my code:

using (HostingEnvironment.Impersonate())
        {
            string server = "hello.world.com:389";
            string email = null;

            DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + server + "/DC=hello,DC=world,DC=com");
            DirectorySearcher dSearch = new DirectorySearcher(dEntry);
            dSearch.SearchScope = SearchScope.Subtree;
            dSearch.Filter = "(&(objectClass=users)(cn=" + lanID + "))";
            dSearch.PropertiesToLoad.Add("mail");

            SearchResult result = dSearch.FindOne();

            if (result != null)
            {
                email = result.Properties["mail"].ToString();
                return email;
            }
            else return email = null;
        }

The code takes a user's employee id (lanID) and returns that userID's email (the value under 'mail' property). How should I do so I don't get System.DirectoryServices.ResultPropertyValueCollection but an actual email?

Body:
You need to use SearchResult.GetDirectoryEntry() Method to get the directory entry which corresponds to this SearchResult.

Retrieves the DirectoryEntry that corresponds to the SearchResult from
  the Active Directory Domain Services hierarchy. Use GetDirectoryEntry when you want to look at the live entry instead of the entry that was returned through DirectorySearcher, or when you want to invoke a method on the object that was returned.

  --emphasis mine.

Use the below code:

DirectoryEntry user = result.GetDirectoryEntry();
string distinguishedName = user.Properties["mail"].Value.ToString();


问:
How to make a folder dynamically with PHP
I want to allow the user to add something, and get a folder:

```<code>example.com/foo
</code>```

But I DONT want the folder to actually be there, I want it to be made instantaneously, so that I can still use the directory foo for private files (If I wanted to).

The name of the folder will be stored in a mySQL database, so all that remains is to map it. But how?

答:
Maybe this is what you're looking for. Instead of doing example.com/foo, use example.com/something/foo. Then use an .htaccess rewrite rule:

```<code>RewriteEngine on
RewriteRule ^/?something/(\w+)$ fake.php?file=$1
</code>```

Then you could have fake.php do everything that you need it to.

Body:
I want to allow the user to add something, and get a folder:

example.com/foo

But I DONT want the folder to actually be there, I want it to be made instantaneously, so that I can still use the directory foo for private files (If I wanted to).

The name of the folder will be stored in a mySQL database, so all that remains is to map it. But how?

Body:
Maybe this is what you're looking for. Instead of doing example.com/foo, use example.com/something/foo. Then use an .htaccess rewrite rule:

RewriteEngine on
RewriteRule ^/?something/(\w+)$ fake.php?file=$1

Then you could have fake.php do everything that you need it to.


答:
try like this :

```<code><i class="glyphicon glyphicon-bell" [ngClass]="cookieData.search_unread_count != 0 ? 'notification-icon': ' '"></i>
</code>```

Updated Answer :

```<code><i class="glyphicon glyphicon-bell" [ngClass]="cookieData.search_unread_count != 0 ? 'notification-icon': ' '">
    <span *ngIf="cookieData.search_unread_count != 0">
        {{cookieData.search_unread_count}}
    </span>
</i>
</code>```

Title: conditionally show/hide the icon in angular

Body:
try like this :

<i class="glyphicon glyphicon-bell" [ngClass]="cookieData.search_unread_count != 0 ? 'notification-icon': ' '"></i>

Updated Answer :

<i class="glyphicon glyphicon-bell" [ngClass]="cookieData.search_unread_count != 0 ? 'notification-icon': ' '">
    <span *ngIf="cookieData.search_unread_count != 0">
        {{cookieData.search_unread_count}}
    </span>
</i>


问:
Convert for loop to recursive function in python3
Is it possible to convert the following loop:

```<code>c = 0
for a in find:
    c += 1
return c
</code>```

Where find is a list like [a,b,c,d] to a function that uses recursion without using external libraries?

答:
```<code>def count(ls):
    if not ls:  # empty
        return 0
    return count(ls[1:]) + 1
</code>```

Use it like this:

```<code>>>> find = [a, b, c, d]
>>> count(find)
4
</code>```

Body:
Is it possible to convert the following loop:

c = 0
for a in find:
    c += 1
return c

Where find is a list like [a,b,c,d] to a function that uses recursion without using external libraries?

Body:
def count(ls):
    if not ls:  # empty
        return 0
    return count(ls[1:]) + 1

Use it like this:

>>> find = [a, b, c, d]
>>> count(find)
4


问:
why `componentWillReceiveProps` is not necessary in React's "Lifting state up" example?
I am developing a web page using React, and have some questions about the "Lifting Stat Up" example (and I paste the link for complete code of it here for quick reference), which is inconsistent with what I encountered in my own project.

My question is about this part:

```<code>    <TemperatureInput
      scale="c"
      temperature={celsius}
      onTemperatureChange={this.handleCelsiusChange} />
</code>```

while user input new values, the celsius will be re-calculated (triggered by a callback function in TemperatureInput which calls handleCelsiusChange, and then render is triggered), and passed as one of props to TemperatureInput. But inside the definition of TemperatureInput, why componentWillReceiveProps is not defined? In my practice, if the props is assigned in constructor only, it will not be updated automatically if value changed. As the document said, it will not create a new element but just update the existing one for performance. If there is no new instance is created, the constructor would not be invoked, so the this.props will not be updated without a componentWillReceiveProps function.

All these above is consistent to my practice, but not to the example. Why componentWillReceiveProps is not required in the example to make this.props updated?

答:
The constructor in this case is not doing anything special with the props, it is just calling the React.Component constructor with super() which is what it would do anyway. If it was setting some state from props for example, then you would need a componentWillReceiveProps, as you would need to update the state when the props change.

When the component gets new props, the constructor is not invoked again, as it is already an instance, instead react updates the props on the component instance, and calls the render() again, so the props in render() will be the updated props. If you had a componentWillReceiveProps defined, it will be called before the call to render();

Body:
I am developing a web page using React, and have some questions about the "Lifting Stat Up" example (and I paste the link for complete code of it here for quick reference), which is inconsistent with what I encountered in my own project.

My question is about this part:

    <TemperatureInput
      scale="c"
      temperature={celsius}
      onTemperatureChange={this.handleCelsiusChange} />

while user input new values, the celsius will be re-calculated (triggered by a callback function in TemperatureInput which calls handleCelsiusChange, and then render is triggered), and passed as one of props to TemperatureInput. But inside the definition of TemperatureInput, why componentWillReceiveProps is not defined? In my practice, if the props is assigned in constructor only, it will not be updated automatically if value changed. As the document said, it will not create a new element but just update the existing one for performance. If there is no new instance is created, the constructor would not be invoked, so the this.props will not be updated without a componentWillReceiveProps function.

All these above is consistent to my practice, but not to the example. Why componentWillReceiveProps is not required in the example to make this.props updated?


问:
Can I catch the value by using bourne shell script?
When I type some command in openwrt, the result is like this.

```<code>Security  Signal(%)     Mode
WPA2      86            on
WPA2      42            on
</code>```

In this result, I want to catch the signal value(86) in first column.
How can i catch the value by using bourne shell script?

Plus, luci.sys.call function is only used in cbi file for making Luci, isn't it?

答:
The following should do:

```<code>HereYourCommand | head -2 | tail -1 | tr -s ' ' | cut -d' ' -f2
</code>```

Replace HereYourCommand with your call to openwrt.

The explanation:

head -2: pick up just the first two lines.

tail -1: from this two lines, pick up the last line.

tr -s ' ': replace multiple spaces with a single one.

cut -d' ' -f2: pick up the 2nd field from the remaining line.

Body:
When I type some command in openwrt, the result is like this.

Security  Signal(%)     Mode
WPA2      86            on
WPA2      42            on

In this result, I want to catch the signal value(86) in first column.
How can i catch the value by using bourne shell script?

Plus, luci.sys.call function is only used in cbi file for making Luci, isn't it?

Body:
The following should do:

HereYourCommand | head -2 | tail -1 | tr -s ' ' | cut -d' ' -f2

Replace HereYourCommand with your call to openwrt.

The explanation:

head -2: pick up just the first two lines.

tail -1: from this two lines, pick up the last line.

tr -s ' ': replace multiple spaces with a single one.

cut -d' ' -f2: pick up the 2nd field from the remaining line.


问:
How to define [bigint] in powershell windows7?
We are unable to define data type [bigint] in powershell version 2 in OS win7, also we use [System.Numerics.BigInteger] again not work,

Is there a way to do this?

答:
Unfortunately PowerShell version 2 doesn't support this. But in 3.O and later versions you can achieve this.

```<code>[bigint]1e20
</code>```

It will give following output:

```<code>100000000000000000000
</code>```

Body:
Unfortunately PowerShell version 2 doesn't support this. But in 3.O and later versions you can achieve this.

[bigint]1e20

It will give following output:

100000000000000000000


问:
Handling File Upload Exception - Laravel
This is how i upload a file into my database but i am not able to handle my exception when the file uploaded is an invalid format or type.

I am able to handle exception when no file is uploaded but not when the file type is invalid or does not meet the standard.

How do i get this done please?

Controller

```<code> public function import($id, Request $request)
    {

       $country= Country::all()->where('id',$id)->first();

           if($request->file('imported-file'))
           {
                     $path = $request->file('imported-file')->getRealPath();
                     $data = Excel::load($path, function($reader)
               {
                     })->get();

               if(!empty($data) && $data->count())
               {
                 foreach ($data->toArray() as $row)
                 {
                   if(!empty($row))
                   {
                     $dataArray[] =
                     [
                       'name' => $row['name'],

                     ];
                   }
    else {
            return redirect('admin')->with('error','File format Error');

         }
               }

               if(!empty($dataArray))
               {
                $country->teams()->createMany($dataArray);
                 return redirect('admin')->with('status','Countries successfully added');

                }
              }
            }
else {
            return redirect('admin')->with('error','No file was uploaded');

         }

        }
</code>```

答:
I have uploading excel files in one of my project. Hope this will helps you:-

```<code>$file = Input::file('imported-file');
Excel::load($file ,function($reader){
                    $reader->each(function($sheet){
                        YourMOdelName::firstOrCreate($sheet->toArray());
                    });
                });
</code>```

YourModelName is your table name suppose if table is users so you have to define User in that case.....
From this way you can get the extenstion of your uploading file:-

```<code>$ext= Input::file('imported-file')->getClientOriginalExtension();
echo $ext; //print the extension here
</code>```

Hope it willl help!

Body:
This is how i upload a file into my database but i am not able to handle my exception when the file uploaded is an invalid format or type.

I am able to handle exception when no file is uploaded but not when the file type is invalid or does not meet the standard.

How do i get this done please?

Controller

 public function import($id, Request $request)
    {

       $country= Country::all()->where('id',$id)->first();

           if($request->file('imported-file'))
           {
                     $path = $request->file('imported-file')->getRealPath();
                     $data = Excel::load($path, function($reader)
               {
                     })->get();

               if(!empty($data) && $data->count())
               {
                 foreach ($data->toArray() as $row)
                 {
                   if(!empty($row))
                   {
                     $dataArray[] =
                     [
                       'name' => $row['name'],

                     ];
                   }
    else {
            return redirect('admin')->with('error','File format Error');

         }
               }

               if(!empty($dataArray))
               {
                $country->teams()->createMany($dataArray);
                 return redirect('admin')->with('status','Countries successfully added');

                }
              }
            }
else {
            return redirect('admin')->with('error','No file was uploaded');

         }

        }

Body:
I have uploading excel files in one of my project. Hope this will helps you:-

$file = Input::file('imported-file');
Excel::load($file ,function($reader){
                    $reader->each(function($sheet){
                        YourMOdelName::firstOrCreate($sheet->toArray());
                    });
                });

YourModelName is your table name suppose if table is users so you have to define User in that case.....
From this way you can get the extenstion of your uploading file:-

$ext= Input::file('imported-file')->getClientOriginalExtension();
echo $ext; //print the extension here

Hope it willl help!


问:
Why are my @BeforeTest methods sometimes reported as the last element of previous test?
I have a testNG suite, executing some selenium code. I am testing navigation between pages in a webapp I have. There are four different user levels, which gives access to restricted pages, based on user type. I also need to test this in both Chrome and IE.

I have followed a Mkyong.com tutorial for my testng.xml setup.

I have chosen to collect all navigation tests for all users, and both browsers, in a single testng.xml. It gives a total of 8 test classes, where 4 and 4 have the same configuration class executed before tests are run.

testng.xml:

```<code><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Releaseboard Local tests" parallel="none">

    <test name="user1 chrome">
        <classes>
            <class name="testsuite.ChromeConfig" />
            <class name="testcase.User1NavigationTests" />
        </classes>
    </test>
    <test name="user2 chrome">
        <classes>
            <class name="testsuite.ChromeConfig" />
            <class name="testcase.User2NavigationTests" />
        </classes>
    </test>
    <test name="user3 chrome">
        <classes>
            <class name="testsuite.ChromeConfig" />
            <class name="testcase.User3NavigationTests" />
        </classes>
    </test>
    <test name="user4 chrome">
        <classes>
            <class name="testsuite.ChromeConfig" />
            <class name="testcase.User4NavigationTests" />
        </classes>
    </test>

    <test name="user1 ie">
        <classes>
            <class name="testsuite.IeConfig" />
            <class name="testcase.User1NavigationTests" />
        </classes>
    </test>
    <test name="user2 ie">
        <classes>
            <class name="testsuite.IeConfig" />
            <class name="testcase.User2NavigationTests" />
        </classes>
    </test>
    <test name="user3 ie">
        <classes>
            <class name="testsuite.IeConfig" />
            <class name="testcase.User3NavigationTests" />
        </classes>
    </test>
    <test name="user4 ie">
        <classes>
            <class name="testsuite.IeConfig" />
            <class name="testcase.User4NavigationTests" />
        </classes>
    </test>
</suite>
</code>```

Now, when I run these tests, I expect this output for all 8 test classes:

It does not matter if they are red or green, but I expect all test tags from the xml to start two levels up, and always at the same level. There is also a level above the three shown, but it does not matter at this point.

The output I get however, is that sometimes the next level 2, shows up inside the previous level 1. It then fails the @BeforeTest annotated method. That would not be so bad in itself, because it actually also runs the test at level 1 after failing inside the previous test. However, if a test has shown up inside the previous, it always fails @BeforeTest at level 1 as well, and all level 3 test methods are automatically skipped. See image below:

All of the lines with time at the end are actual lines from the screenshot. The rest has been edited for anonymity.

Note how my @BeforeTest, and @AfterTest methods, setup and tearDown, are now listed as tests for some reason. Both inside the wrong test, without any real test methods, and inside the next, suddenly with the actual test methods. These errors appear completely random every time. There is no specific test that always contains the next one. Sometimes there are three of them, sometimes only one. The only thing consistent is that it is never two in a row. I really really do not understand what is going on here. I'd love to explain better, or do more research, but I'm having a really hard time boiling this problem down to a searchable term. I have a feeling this might go unanswered until i can put bounty on it.

I will post any other code examples anyone can think of wanting to see, but for now I would not know where to start.

答: It seems like the answer to my question, is that this is what happens when a @BeforeTest annotated method fails. In other words, the fact that the setup and teardown shows up inside the previous tests hierarchical structure, is likely just minor reporting error on testNG's side. It is not the cause of any error. The cause of the error, and the skipped tests, are in my case the result of an unstable setup method. The fact that it worked sometimes, and sometimes not, was due to sensitive small conditional elements on my pages, which were some times found/loaded in time, and some times not. </p>

Body:
I have a testNG suite, executing some selenium code. I am testing navigation between pages in a webapp I have. There are four different user levels, which gives access to restricted pages, based on user type. I also need to test this in both Chrome and IE.

I have followed a Mkyong.com tutorial for my testng.xml setup.

I have chosen to collect all navigation tests for all users, and both browsers, in a single testng.xml. It gives a total of 8 test classes, where 4 and 4 have the same configuration class executed before tests are run.

testng.xml:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Releaseboard Local tests" parallel="none">

    <test name="user1 chrome">
        <classes>
            <class name="testsuite.ChromeConfig" />
            <class name="testcase.User1NavigationTests" />
        </classes>
    </test>
    <test name="user2 chrome">
        <classes>
            <class name="testsuite.ChromeConfig" />
            <class name="testcase.User2NavigationTests" />
        </classes>
    </test>
    <test name="user3 chrome">
        <classes>
            <class name="testsuite.ChromeConfig" />
            <class name="testcase.User3NavigationTests" />
        </classes>
    </test>
    <test name="user4 chrome">
        <classes>
            <class name="testsuite.ChromeConfig" />
            <class name="testcase.User4NavigationTests" />
        </classes>
    </test>

    <test name="user1 ie">
        <classes>
            <class name="testsuite.IeConfig" />
            <class name="testcase.User1NavigationTests" />
        </classes>
    </test>
    <test name="user2 ie">
        <classes>
            <class name="testsuite.IeConfig" />
            <class name="testcase.User2NavigationTests" />
        </classes>
    </test>
    <test name="user3 ie">
        <classes>
            <class name="testsuite.IeConfig" />
            <class name="testcase.User3NavigationTests" />
        </classes>
    </test>
    <test name="user4 ie">
        <classes>
            <class name="testsuite.IeConfig" />
            <class name="testcase.User4NavigationTests" />
        </classes>
    </test>
</suite>

Now, when I run these tests, I expect this output for all 8 test classes:

It does not matter if they are red or green, but I expect all test tags from the xml to start two levels up, and always at the same level. There is also a level above the three shown, but it does not matter at this point.

The output I get however, is that sometimes the next level 2, shows up inside the previous level 1. It then fails the @BeforeTest annotated method. That would not be so bad in itself, because it actually also runs the test at level 1 after failing inside the previous test. However, if a test has shown up inside the previous, it always fails @BeforeTest at level 1 as well, and all level 3 test methods are automatically skipped. See image below:

All of the lines with time at the end are actual lines from the screenshot. The rest has been edited for anonymity.

Note how my @BeforeTest, and @AfterTest methods, setup and tearDown, are now listed as tests for some reason. Both inside the wrong test, without any real test methods, and inside the next, suddenly with the actual test methods. These errors appear completely random every time. There is no specific test that always contains the next one. Sometimes there are three of them, sometimes only one. The only thing consistent is that it is never two in a row. I really really do not understand what is going on here. I'd love to explain better, or do more research, but I'm having a really hard time boiling this problem down to a searchable term. I have a feeling this might go unanswered until i can put bounty on it.

I will post any other code examples anyone can think of wanting to see, but for now I would not know where to start.


问:
Modifying specific array elements in Python 3.1
I have two arrays: array and least_common (filter array)

The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.

```<code> for i in range (len(array)):
        for j in range(len(least_common)):
            if array[i] is least_common[j][0]:
                new_array.append ((array[i]) + (array[i] * (mod[1]/100)))
</code>```

However, if the element in array does not match any of the elements in least_common I wan't to append it to new_array, then iterate to the next element in array to begin the checking process again.

答:
Keep track of whether you found a match using a boolean, which you set to False before each inner loop and set to True within your if. After each iteration, if it's still False it means you found no matches and should then do your appending.

You should also follow what @Andrew says and iterate over lists using for a in array:. If you need the index, use for i, a in enumerate(array):. And be aware that is is not the same as ==.

```<code>new_array = []
for array_item in array:
    found = False
    for least_common_item in least_common:
        if array_item is least_common_item:
            found = True
    if not found:
        new_array.append (array_item * (1 + mod[1]/100))
</code>```

You can also greatly shorten this code using in if you meant to use == instead of is:

```<code>for array_item in array:
    if array_item not in least_common:
        new_array.append (array_item * (1 + mod[1]/100))
</code>```

Body:
I have two arrays: array and least_common (filter array)

The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.

 for i in range (len(array)):
        for j in range(len(least_common)):
            if array[i] is least_common[j][0]:
                new_array.append ((array[i]) + (array[i] * (mod[1]/100)))

However, if the element in array does not match any of the elements in least_common I wan't to append it to new_array, then iterate to the next element in array to begin the checking process again.

Body:
Keep track of whether you found a match using a boolean, which you set to False before each inner loop and set to True within your if. After each iteration, if it's still False it means you found no matches and should then do your appending.

You should also follow what @Andrew says and iterate over lists using for a in array:. If you need the index, use for i, a in enumerate(array):. And be aware that is is not the same as ==.

new_array = []
for array_item in array:
    found = False
    for least_common_item in least_common:
        if array_item is least_common_item:
            found = True
    if not found:
        new_array.append (array_item * (1 + mod[1]/100))

You can also greatly shorten this code using in if you meant to use == instead of is:

for array_item in array:
    if array_item not in least_common:
        new_array.append (array_item * (1 + mod[1]/100))


问:
Can Apache solr stores actual files which are uploaded on it?
This is my first time on Stack Overflow. Thanks to all for providing valuable information and helping one another.

I am currently working on Apache Solr 7. There is a POC I need to complete as I have less time so putting this question here. I have setup SOLR on my windows machine. I have created core and uploaded a PDF document using /update/extract from Admin UI. After uploading, I can see the metadata of the file if I query from the Admin UI using query button. I was wondering if I can get the actusl content of the PDF as well. I can see there is one tlog file gets generated under /data/tlog/tlog000... with raw PDF data but not the actual file.

So the question are,
1. Can I get the PDF content?
2. does Solr stores the actual file somewhere?
     a. If it stores then where it does?
     b. If it does not store then, is there a way to store THE FILE?

Regards,
Munish Arora

答:
Solr will not sore the actual file anywhere.
Depending on your config it can store the binary content though.
Using the extract request handler Apache Solr relies on Apache Tika[1] to extract the content from the document[2].

So you can search and return the content of the pdf and a lot of other metadata if you like.

[1] https://tika.apache.org/

[2] https://lucene.apache.org/solr/guide/6_6/uploading-data-with-solr-cell-using-apache-tika.html


问:
calling a method on LoadingCache refresh
I have a client who provides access to their apis  through tokens. They are not OAuth tokens. Just a simple http get request to get the token. This token does expire and we can refresh before that to get a new token. I was thinking of implementing this using Google LoadingCache, get the  token if not null, else  post as request to the client to get the token. But this happens when the value is null. ( in my case first time ) Afterwards, I just need to refresh periodically before it expires.Does using Loading cache make sense here ? or are there any other ways of achieving this?
Also if it does this is the approach I am thinking --- I would like it to call  a function/method to refresh the token. I am not sure if overloading the load method will be called only if its null or everytime it has to refresh/expire. Will the cache emptied  when it expires/refreshes? I can refresh the token using the previous token. So I need the value in the cache to send the request. Here is what I am thinking

```<code>     private static LoadingCache<String, Optional<String>> cache = CacheBuilder.newBuilder()
        .build(new CacheLoader<String, Optional<String>>() {
            @Override
            public Optional<String> load(String key) throws Exception {
                return Optional.fromNullable(refreshToken(key));
            }
        });
</code>```

I think I need to know if the same load method will be called when the cache expires?

答:
Yes, if you call LoadingCache.get() it will invoke your load() method. However cached values do not automatically expire - you must either manually remove them (e.g. via Cache.invalidate()) or configure the desired eviction semantics via CacheBuilder.

For example if you know tokens expire after 10 minute you could use expireAfterWrite(9, TimeUnit.MINUTES) (9 minutes gives you some buffer time, you could pick a different amount of time).

On the other hand if you only find out that a token has expired by making a request and having it be rejected you'd likely want to manually invalidate the entry after the request fails. Then the next call to .get() will invoke .load() and then return a new token.

Body:
I have a client who provides access to their apis  through tokens. They are not OAuth tokens. Just a simple http get request to get the token. This token does expire and we can refresh before that to get a new token. I was thinking of implementing this using Google LoadingCache, get the  token if not null, else  post as request to the client to get the token. But this happens when the value is null. ( in my case first time ) Afterwards, I just need to refresh periodically before it expires.Does using Loading cache make sense here ? or are there any other ways of achieving this?
Also if it does this is the approach I am thinking --- I would like it to call  a function/method to refresh the token. I am not sure if overloading the load method will be called only if its null or everytime it has to refresh/expire. Will the cache emptied  when it expires/refreshes? I can refresh the token using the previous token. So I need the value in the cache to send the request. Here is what I am thinking

     private static LoadingCache<String, Optional<String>> cache = CacheBuilder.newBuilder()
        .build(new CacheLoader<String, Optional<String>>() {
            @Override
            public Optional<String> load(String key) throws Exception {
                return Optional.fromNullable(refreshToken(key));
            }
        });

I think I need to know if the same load method will be called when the cache expires?


问:
React Dynamic Html Tags
Lets say i have this react component refering to a TextInput.
I want this component to be a

<input type="text"> and a <textarea> as well, but with no ifs on it, as being passed throw props, however my renderer got extra stuff on the element as follows:

```<code>   render() {
      return (
            <label>
            <strong>{this.props.name}</strong>
               <input type="text" ref={ component => { this.input = component; } } name={this.props.name} onChange={this.handleChange} value={this.state.value} />
            </label>
      )
   }
</code>```

My original idea was doing something like this

```<code>myInputProps = { type: (<input type="text"/>) }
</code>```

So in my element i woul render this simply as

```<code>  {this.props.type}
</code>```

However how could i pass all those extra stuff to the element such as the ref, name, onchange etc ? What would be a good aproach on this problem ? I could do some ifs and check what should i render depending on the component state etc, but i`m not sure that would be the best.

答:
```<code>render() {
  return (
        <label>
        <strong>{this.props.name}</strong>
           {this.props.children}
        </label>
  )}
</code>```

Title: React Dynamic Html Tags

Body:
Lets say i have this react component refering to a TextInput.
I want this component to be a

<input type="text"> and a <textarea> as well, but with no ifs on it, as being passed throw props, however my renderer got extra stuff on the element as follows:

   render() {
      return (

            {this.props.name}
               <input type="text" ref={ component => { this.input = component; } } name={this.props.name} onChange={this.handleChange} value={this.state.value} />

      )
   }

My original idea was doing something like this

myInputProps = { type: (<input type="text"/>) }

So in my element i woul render this simply as

  {this.props.type}

However how could i pass all those extra stuff to the element such as the ref, name, onchange etc ? What would be a good aproach on this problem ? I could do some ifs and check what should i render depending on the component state etc, but i`m not sure that would be the best.


问:
PHP syntax error - using elseif
This is the code that I wrote and it's not working. it's suppose to ask the user a odd number and check is it correct.

Code:

```<code>$guess = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit)){
        if ($guess/2 %0){
                echo "the number you are guessing is not odd";
        }elseif{

         ($guess<$rand)
                echo "Your Guess is Smaller than the secret number";
        }elseif{
                ($guess>$rand)
                         echo "Your Guess is bigger than the secret number";
        }else{
                          ($guess==$rand)
        echo "you guessed currectly. now try anouthe number!";}

else
        header("Location: index.php");
                exit();}

?>
</code>```

答:
That's not the correct syntax for an if-else construct in php.

The elseif part needs to have a condition right after it (before the opening brace), while else doesn't expect a condition at all.

```<code>if ($guess/2 %0){
        echo "the number you are guessing is not odd";
} elseif ($guess<$rand) {
    // ....
} else {
    echo "you guessed currectly. now try anouthe number!";
}
</code>```

Of course, before your else you have to be sure that the if and elseifs match all the "wrong" cases.

Title: PHP syntax error - using elseif

Body:
This is the code that I wrote and it's not working. it's suppose to ask the user a odd number and check is it correct.

Code:

$guess = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit)){
        if ($guess/2 %0){
                echo "the number you are guessing is not odd";
        }elseif{

         ($guess<$rand)
                echo "Your Guess is Smaller than the secret number";
        }elseif{
                ($guess>$rand)
                         echo "Your Guess is bigger than the secret number";
        }else{
                          ($guess==$rand)
        echo "you guessed currectly. now try anouthe number!";}

else
        header("Location: index.php");
                exit();}

?>

Body:
That's not the correct syntax for an if-else construct in php.

The elseif part needs to have a condition right after it (before the opening brace), while else doesn't expect a condition at all.

if ($guess/2 %0){
        echo "the number you are guessing is not odd";
} elseif ($guess<$rand) {
    // ....
} else {
    echo "you guessed currectly. now try anouthe number!";
}

Of course, before your else you have to be sure that the if and elseifs match all the "wrong" cases.


问:
Web page download progress with percentage
i saw that flash website can be develop to show percentage of loading page. when web page is downloading in client machine then a percentage is shown and show much content is downloading in client machine. so i just want to know the same effect can be achieve in asp.net website where we will show the percentage of the page content is downloading in client machine with the help of JQuery when page will be requested by user.

please discuss how to achieve it. thanks.

答:
GMail uses a loading bar as well. Here is a blog posting on how to make one for your own website, might be handy:

http://yensdesign.com/2008/11/how-to-create-a-stylish-loading-bar-as-gmail-in-javascript/


问:
Typescript declaration: Merge a class and an interface
I have two models Model and its subclass ClientModel an ambient module. Now I want to declare a set of attributes of ClientModel from an interface so called Client. How can I do it? I can imagine something like this:

```<code>interface Client {
    name: string;
    email: string;
}

declare class ClientModel extends Model implements Client {
    // with name and email here without redeclare them
}
</code>```

答:
You can use declaration merging. If the class and the interface are declared in the same namespace/module and have the same name, they will be merged into a single class type.

```<code>interface ClientModel {
    name: string;
    email: string;
}

class ClientModel extends Model  {
    m() {
        this.email //Valid
    }
}
</code>```

If you cannot change the interface or is declared in another namespace and you can't move it you can inherit from it in the merged interface:

```<code>interface Client {
    name: string;
    email: string;
}

interface ClientModel extends Client {}
class ClientModel extends Model  {
    m() {
        this.email //Valid
    }
}
</code>```

Body:
I have two models Model and its subclass ClientModel an ambient module. Now I want to declare a set of attributes of ClientModel from an interface so called Client. How can I do it? I can imagine something like this:

interface Client {
    name: string;
    email: string;
}

declare class ClientModel extends Model implements Client {
    // with name and email here without redeclare them
}

Body:
You can use declaration merging. If the class and the interface are declared in the same namespace/module and have the same name, they will be merged into a single class type.

interface ClientModel {
    name: string;
    email: string;
}

class ClientModel extends Model  {
    m() {
        this.email //Valid
    }
}

If you cannot change the interface or is declared in another namespace and you can't move it you can inherit from it in the merged interface:

interface Client {
    name: string;
    email: string;
}

interface ClientModel extends Client {}
class ClientModel extends Model  {
    m() {
        this.email //Valid
    }
}


问:
How to open external pdf in Android with Ionic
I am working on an application, and I am facing a problem with Ionic1 , and it concerns opening a .PDF from an external URL in Android with Ionic.
I tried many solutions given in this site and other sites but in vain.
this is an example of what I have tried:

in .html file:

```<code><a class="item" href="#" onclick="window.open('http://www.xxx.pdf', '_system', 'location=yes')">
</code>```

in .js file:

```<code>var ref = window.open('http://www.xxx.pdf', '_blank', 'location=yes');
</code>```

can you suggest other solutions please?

答:
You could use the cordova inapp browser plugin.

you can replace all window.open by inappBrowser;

```<code>window.open = cordova.InAppBrowser.open;
</code>```

or you can just use:

```<code>cordova.InAppBrowser.open('http://linktopdf.pdf', '_blank', 'location=yes');
</code>```

or if you use ngCordova, you can use $cordovaInAppBrowser,

```<code>$cordovaInAppBrowser.open('http://www.xxx.pdf', '_blank', options)
</code>```

take a look here: http://ngcordova.com/docs/plugins/inAppBrowser/

Body:
I am working on an application, and I am facing a problem with Ionic1 , and it concerns opening a .PDF from an external URL in Android with Ionic.
I tried many solutions given in this site and other sites but in vain.
this is an example of what I have tried:

in .html file:

in .js file:

var ref = window.open('http://www.xxx.pdf', '_blank', 'location=yes');

can you suggest other solutions please?

Body:
You could use the cordova inapp browser plugin.

you can replace all window.open by inappBrowser;

window.open = cordova.InAppBrowser.open;

or you can just use:

cordova.InAppBrowser.open('http://linktopdf.pdf', '_blank', 'location=yes');

or if you use ngCordova, you can use $cordovaInAppBrowser,

$cordovaInAppBrowser.open('http://www.xxx.pdf', '_blank', options)

take a look here: http://ngcordova.com/docs/plugins/inAppBrowser/


问:
laravel 5 : Class 'input' not found
In my routes.php file I have :

```<code>Route::get('/', function () {

    return view('login');
});

Route::get('/index', function(){
    return view('index');
});

Route::get('/register', function(){
    return view('register');
});
Route::post('/register',function(){

    $user = new \App\User;
    $user->username = input::get('username');
    $user->email  = input::get('email');
    $user->password = Hash::make(input::get('username'));
    $user->designation = input::get('designation');
    $user->save();

});
</code>```

I have a form for users registration. I am also taking the form inputs value in the routes.php.

But the error comes up when I register a user .
Error:

```<code>FatalErrorException in routes.php line 61:
Class 'input' not found
</code>```

答:
Add this in config/app.php under aliases:-</p>

```<code>'Input' => Illuminate\Support\Facades\Input::class,
</code>```

Title: laravel 5 : Class 'input' not found

Body:
In my routes.php file I have :

Route::get('/', function () {

    return view('login');
});

Route::get('/index', function(){
    return view('index');
});

Route::get('/register', function(){
    return view('register');
});
Route::post('/register',function(){

    $user = new \App\User;
    $user->username = input::get('username');
    $user->email  = input::get('email');
    $user->password = Hash::make(input::get('username'));
    $user->designation = input::get('designation');
    $user->save();

});

I have a form for users registration. I am also taking the form inputs value in the routes.php.

But the error comes up when I register a user .
Error:

FatalErrorException in routes.php line 61:
Class 'input' not found

Body:
Add this in config/app.php under aliases:-

'Input' => Illuminate\Support\Facades\Input::class,


问:
Deadlock in script for sending emails
I have a script for sending emails in the background. The script runs in parallel to send out multiple emails simultaneously. It works basically like this, with a mixture of MySQL and PHP:

/* TransmissionId is a PRIMARY KEY */
/* StatusId is a FOREIGN KEY */
/* Token is UNIQUE */

/* Pick a queued (StatusId=1) transmission and set it to pending (StatusId=2) */
/* This is a trick to both update a row and store its id for later retrieval in one query */
SET @Ids = 0;
UPDATE transmission
SET StatusId=IF(@Ids := TransmissionId,2,2), LatestStatusChangeDate=NOW()
WHERE StatusId = 1
ORDER BY TransmissionId ASC
LIMIT 1;

/* Fetch the id of the picked transmission */
$Id = SELECT @Ids;

try {
    /* Fetch the email and try to send it */
    $Email = FetchEmail($Id);
    $Email->Send();

    /* Set the status to sent (StatusId=3) */
    $StatusId = 3;
} catch(Exception $E) {
    /* The email could not be sent, set the status to failed (StatusId=4) */
    $StatusId = 4;
} finally {
    /* Save the new transmission status */
    UPDATE transmission
    SET StatusId=$StatusId, LatestStatusChangeDate=NOW(), Token='foobar'
    WHERE TransmissionId = $Id;
}
```

<p>The issue is that I sometimes get a deadlock: <code>SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction</code>. This has happened when executing the last query. I've not seen it happen when executing the first query. Can anyone understand how a deadlock can happen in this case? Could it be that the first query and the last query lock <code>StatusId</code> and <code>TransmissionId</code> in opposite order? But I don't think the first query needs to lock <code>TransmissionId</code>, nor do I think the last query needs to lock <code>StatusId</code>. How can I find this out, and how can I fix it?</p>

<h1>Edit</h1>

<p>There is another query that might also play a role. Whenever someone opens the email, this query is run:</p>

<pre class="lang-sql prettyprint-override"><code>/* Selector is UNIQUE */
UPDATE transmission SET
OpenCount=OpenCount+1
WHERE Selector = 'barfoo'
</code>```

答: InnoDB uses automatic row-level locking. You can get deadlocks even in the case of transactions that just insert or delete a single row. That is because these operations are not really “atomic”; they automatically set locks on the (possibly several) index records of the row inserted or deleted. dev.mysql.com/doc/refman/5.7/en/innodb-deadlocks-handling.html</p>

Title: Deadlock in script for sending emails

Body:
I have a script for sending emails in the background. The script runs in parallel to send out multiple emails simultaneously. It works basically like this, with a mixture of MySQL and PHP:

/* TransmissionId is a PRIMARY KEY */
/* StatusId is a FOREIGN KEY */
/* Token is UNIQUE */

/* Pick a queued (StatusId=1) transmission and set it to pending (StatusId=2) */
/* This is a trick to both update a row and store its id for later retrieval in one query */
SET @Ids = 0;
UPDATE transmission
SET StatusId=IF(@Ids := TransmissionId,2,2), LatestStatusChangeDate=NOW()
WHERE StatusId = 1
ORDER BY TransmissionId ASC
LIMIT 1;

/* Fetch the id of the picked transmission */
$Id = SELECT @Ids;

try {
    /* Fetch the email and try to send it */
    $Email = FetchEmail($Id);
    $Email->Send();

    /* Set the status to sent (StatusId=3) */
    $StatusId = 3;
} catch(Exception $E) {
    /* The email could not be sent, set the status to failed (StatusId=4) */
    $StatusId = 4;
} finally {
    /* Save the new transmission status */
    UPDATE transmission
    SET StatusId=$StatusId, LatestStatusChangeDate=NOW(), Token='foobar'
    WHERE TransmissionId = $Id;
}

The issue is that I sometimes get a deadlock: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction. This has happened when executing the last query. I've not seen it happen when executing the first query. Can anyone understand how a deadlock can happen in this case? Could it be that the first query and the last query lock StatusId and TransmissionId in opposite order? But I don't think the first query needs to lock TransmissionId, nor do I think the last query needs to lock StatusId. How can I find this out, and how can I fix it?

Edit

There is another query that might also play a role. Whenever someone opens the email, this query is run:

/* Selector is UNIQUE */
UPDATE transmission SET
OpenCount=OpenCount+1
WHERE Selector = 'barfoo'


问:
event when user check some checkbox
I want to make event when user check some checkbox.

I wrote the code below but nothing happened -

I added "alert", but it doesn't shown

HTML

```<code><td id='checkbox_val_to_reveal'>

    <div class="form-group">
        <label>Status</label>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply</label></div>
    </div>

</td>

<div class='reveal_div_by_checkbox_val'>
    <p><label class="title">Ticket Cause</label><br />
</div>
</code>```

JS

```<code><script>
//  $("#checkbox_val_to_reveal .flat").change(function() {

    $("#checkbox_val_to_reveal input[type='checkbox']").change(function() {
        alert("RRR");

    if ($(this).val() === "3" && $(this).is(":checked")) {
        $(".reveal_div_by_checkbox_val").show();
    } else {
        $(".reveal_div_by_checkbox_val").hide();
    }
    });
</script>
</code>```

答:
You have to just put your td into table tag and add your script into anonymous function. see the below code.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Title</title>
    <script>
        //  $("#checkbox_val_to_reveal .flat").change(function() {
        $(function(){
            $("#checkbox_val_to_reveal input[type='checkbox']").change(function() {
                alert("RRR");
                if ($(this).val() === "3" && $(this).is(":checked")) {
                    $(".reveal_div_by_checkbox_val").show();
                } else {
                    $(".reveal_div_by_checkbox_val").hide();
                }
            });
        });
</script>
</head>
<body>
<table>
    <td id='checkbox_val_to_reveal'>
        <div class="form-group">
            <label>Status</label>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply</label></div>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply</label></div>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved</label></div>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA</label></div>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply</label></div>
        </div>
    </td>
</table>
<div class='reveal_div_by_checkbox_val'>
    <p><label class="title">Ticket Cause</label><br />
</div>
</body>
</html>
</code>```

Title: event when user check some checkbox

Body:
I want to make event when user check some checkbox.

I wrote the code below but nothing happened -

I added "alert", but it doesn't shown

HTML

        Status

<input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved

<input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA

<input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply

Ticket Cause

JS

Body:
You have to just put your td into table tag and add your script into anonymous function. see the below code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Title</title>
    <script>
        //  $("#checkbox_val_to_reveal .flat").change(function() {
        $(function(){
            $("#checkbox_val_to_reveal input[type='checkbox']").change(function() {
                alert("RRR");
                if ($(this).val() === "3" && $(this).is(":checked")) {
                    $(".reveal_div_by_checkbox_val").show();
                } else {
                    $(".reveal_div_by_checkbox_val").hide();
                }
            });
        });
</script>
</head>
<body>
<table>
    <td id='checkbox_val_to_reveal'>
        <div class="form-group">
            <label>Status</label>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply</label></div>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply</label></div>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved</label></div>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA</label></div>
            <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply</label></div>
        </div>
    </td>
</table>
<div class='reveal_div_by_checkbox_val'>
    <p><label class="title">Ticket Cause</label><br />
</div>
</body>
</html>


答:
This code is a bit wonky to me -- I think you want to start with something more like:</p>

```<code>lookup = set([x[0] for x in least_common])
new_array = []
for elem in array:
    if elem in lookup:
        new_array.append(elem + (elem * (mod[1]/100)))
    else:
        new_array.append(elem)
</code>```

Title: Modifying specific array elements in Python 3.1

Body:
This code is a bit wonky to me -- I think you want to start with something more like:

lookup = set([x[0] for x in least_common])
new_array = []
for elem in array:
    if elem in lookup:
        new_array.append(elem + (elem * (mod[1]/100)))
    else:
        new_array.append(elem)


问:
Getting Data Lineage Out from Spark Logs
I am exploring option to get data lineage information out from Spark Logs for Spark programs.

I am looking for information like which kafka topics or Tables Spark program reads or writes into, so that we can get that information run time and to build end to end flow of data movement. Has anyone explored such framework.

When I have Info log level setup, I can get information regarding input kafka read and table which data is written , however, I dont get information if data is sent out to Kafka Topic or Input table read.

Any help appreciated.

Thanks & Regards.

答:
I did analysis that by enabling Logging level at Debug of Spark Program. You can get detailed stack trace of events.

You can track

Input read of Kafka Topic Name

Which DB tables it is reading from

Which DB tables it is writing to

Regards:


问:
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()'

When I call this method sometimes it's shows exception

```<code>public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}
</code>```

My error :

```<code>Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
       at java.util.Calendar.setTime(Calendar.java:1197)
       at com.utils.Utils.getTimestampFromDate(SourceFile:105)
       at com.fragment.MyProfileFragment.onViewClicked(SourceFile:768)
       at com.fragment.MyProfileFragment_ViewBinding$4.doClick(SourceFile:79)
       at butterknife.internal.DebouncingOnClickListener.onClick(SourceFile:22)
       at android.view.View.performClick(View.java:5205)
       at android.view.View$PerformClick.run(View.java:21162)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5453)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
</code>```

Date format :

```<code>public static String SLASH_MM_DD_YYYY = "dd-MMM-yyyy";
</code>```

Any solutions for this?

答:
This will happen when your date is not in desire formate . ParseException will thrown.You can handle it in catch

```<code> try {
    d = formatter.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
   // ParseException will thrown
}
</code>```

You should use your method as.

```<code> public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 1);
        return calendar.getTimeInMillis();
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    // return the default value here
    // Can be System.currentTimeMillis();
   return 0;
}
</code>```

Body:
When I call this method sometimes it's shows exception

public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}

My error :

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
       at java.util.Calendar.setTime(Calendar.java:1197)
       at com.utils.Utils.getTimestampFromDate(SourceFile:105)
       at com.fragment.MyProfileFragment.onViewClicked(SourceFile:768)
       at com.fragment.MyProfileFragment_ViewBinding$4.doClick(SourceFile:79)
       at butterknife.internal.DebouncingOnClickListener.onClick(SourceFile:22)
       at android.view.View.performClick(View.java:5205)
       at android.view.View$PerformClick.run(View.java:21162)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5453)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)

Date format :

public static String SLASH_MM_DD_YYYY = "dd-MMM-yyyy";

Any solutions for this?

Body:
This will happen when your date is not in desire formate . ParseException will thrown.You can handle it in catch

 try {
    d = formatter.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
   // ParseException will thrown
}

You should use your method as.

 public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 1);
        return calendar.getTimeInMillis();
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    // return the default value here
    // Can be System.currentTimeMillis();
   return 0;
}


问:
Checking for EOF using shell script
I have a project that involves extracting data from a database into a text file, and then ingesting it into Hadoop. So i want to create a shell script that NiFi can run to automatically to check if a text file is extracted and ingest it, but I need to make sure that the whole data has been extracted first before ingesting it. Meaning I would need to check that the text file has an EOF, how do I do that?

Don't have any code as of yet, I have very little knowledge writing shell scripts.

答: While creating the file, use a different name. Rename it to the expected name once the extraction is done. Then, the other process can start its work once the file exists.</p>

Title: Checking for EOF using shell script