问:
How to include a radio-button and a text field in a same if/else function?
I’m new in coding. Maybe it a basics question, but still...
I have a number field which assigns different values to another field with if / else statements, depending on the entered value (number >80 assigns 1, number between 50 and 80 assigns 2 and numbers <50 assigns 3). I have also a radio button, which, if checked, must assign a value (in my case “4”) to the same field and if the radio-button is checked it mustn’t allowed any change trough the number field (4 stays as an assigned value, no matter what number is or will be entered in number field).
Both codes worked separately, but I have a problem to merge them together.
Your help is appreciated.
V

EDIT: I edited the code after the comment from Sumeet, but this doesn’t solve my original question - how to include both in a same if/else statement?

```<code><input id="testscore" type="number" name="testscore">Test score
<br />
<input id="final" type=“text” name="final" readonly="true">Final score class
<br />
<input id="radio1" class="radio" type="radio" name="test" value="4">yes
<input id="radio2" class="radio" type="radio" name="test" value="0">no
<br />

function getFinalScore() {
  var testScore = parseFloat($("#testscore").val());
  if (testScore >80){
    $('#final').val(1);
  } else if (testScore <=80 && testScore >50){
    $('#final').val(2);
  } else {
    $('#final').val(3);
  }
}
$(document).ready(function() {
  $('#testscore').keyup(function(event) {
    getFinalScore();
  });
});

$('input').click(function(e){
  if $("#radio1").is(':checked')){
    $("#final").val(4);
  } else {
    $("#final").val(0);
  }
});
</code>```

答:
You have $(radio1).is(':checked') instead of $("#radio1").is(':checked')

function getFinalScore() {
  var testScore = parseFloat($("#testscore").val());
  if (testScore >80){
    $('#final').val(1);
  } else if (testScore <=80 && testScore >50){
    $('#final').val(2);
  } else {
    $('#final').val(3);
  }
}
$(document).ready(function() {
  $('#testscore').keyup(function(event) {
    getFinalScore();
  });
});

$('input').click(function(e){
  if ($("#radio1"). is(':checked')){
    $("#final").val(4);
    $('#testscore').prop( "disabled", true );
  } else {
    $('#testscore').prop( "disabled", false );
    $("#final").val(0);
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="testscore" type="number" name="testscore">Test score
<br />
<input id="final" type=“text” name="final" readonly="true">Final score class
<br />
<input id="radio1" class="radio" type="radio" name="test" value="4">yes
<input id="radio2" class="radio" type="radio" name="test" value="0">no
<br /></code>```

Body:
I’m new in coding. Maybe it a basics question, but still...
I have a number field which assigns different values to another field with if / else statements, depending on the entered value (number >80 assigns 1, number between 50 and 80 assigns 2 and numbers <50 assigns 3). I have also a radio button, which, if checked, must assign a value (in my case “4”) to the same field and if the radio-button is checked it mustn’t allowed any change trough the number field (4 stays as an assigned value, no matter what number is or will be entered in number field).
Both codes worked separately, but I have a problem to merge them together.
Your help is appreciated.
V

EDIT: I edited the code after the comment from Sumeet, but this doesn’t solve my original question - how to include both in a same if/else statement?

<input id="testscore" type="number" name="testscore">Test score

<input id="final" type=“text” name="final" readonly="true">Final score class

<input id="radio1" class="radio" type="radio" name="test" value="4">yes
<input id="radio2" class="radio" type="radio" name="test" value="0">no

function getFinalScore() {
  var testScore = parseFloat($("#testscore").val());
  if (testScore >80){
    $('#final').val(1);
  } else if (testScore <=80 && testScore >50){
    $('#final').val(2);
  } else {
    $('#final').val(3);
  }
}
$(document).ready(function() {
  $('#testscore').keyup(function(event) {
    getFinalScore();
  });
});

$('input').click(function(e){
  if $("#radio1").is(':checked')){
    $("#final").val(4);
  } else {
    $("#final").val(0);
  }
});

Body:
You have $(radio1).is(':checked') instead of $("#radio1").is(':checked')

function getFinalScore() {
  var testScore = parseFloat($("#testscore").val());
  if (testScore >80){
    $('#final').val(1);
  } else if (testScore <=80 && testScore >50){
    $('#final').val(2);
  } else {
    $('#final').val(3);
  }
}
$(document).ready(function() {
  $('#testscore').keyup(function(event) {
    getFinalScore();
  });
});

$('input').click(function(e){
  if ($("#radio1"). is(':checked')){
    $("#final").val(4);
    $('#testscore').prop( "disabled", true );
  } else {
    $('#testscore').prop( "disabled", false );
    $("#final").val(0);
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="testscore" type="number" name="testscore">Test score
<br />
<input id="final" type=“text” name="final" readonly="true">Final score class
<br />
<input id="radio1" class="radio" type="radio" name="test" value="4">yes
<input id="radio2" class="radio" type="radio" name="test" value="0">no
<br />


来源: stackexchange

问:
Pandas KeyError: “['value'] not in index”
I'm having some issues with the index from a Pandas data frame. What I'm trying to do is load data from a JSON file, create a Pandas data frame and then select specific fields from that data frame and send it to my database.

The following is a link to what's in the JSON file so you can see the fields actually exist:
https://pastebin.com/Bzatkg4L

```<code>import pandas as pd
from pandas.io import sql
import MySQLdb
from sqlalchemy import create_engine

# Open and read the text file where all the Tweets are
with open('US_tweets.json') as f:
    tweets = f.readlines()

# Convert the list of Tweets into a structured dataframe
df = pd.DataFrame(tweets)
# Attributes needed should be here
df = df[['created_at', 'screen_name', 'id', 'country_code', 'full_name', 'lang', 'text']]

# To create connection and write table into MySQL
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
                       .format(user="blah",
                               pw="blah",
                               db="blah"))

df.to_sql(con=engine, name='US_tweets_Table', if_exists='replace', flavor='mysql')
</code>```

Thanks for your help!

答:
Pandas doesn't map every object in the JSON file to a column in the dataframe. Your example file contains 24 columns:

```<code>with open('tweets.json') as f:
    df = pd.read_json(f, lines = True)
df.columns
</code>```

Returns:

```<code>Index(['contributors', 'coordinates', 'created_at', 'entities',
   'favorite_count', 'favorited', 'geo', 'id', 'id_str',
   'in_reply_to_screen_name', 'in_reply_to_status_id',
   'in_reply_to_status_id_str', 'in_reply_to_user_id',
   'in_reply_to_user_id_str', 'is_quote_status', 'lang', 'metadata',
   'place', 'retweet_count', 'retweeted', 'source', 'text', 'truncated',
   'user'],
  dtype='object')
</code>```

To dig deeper into the JSON data, I found this solution, but I hope a more elegant approach exists: How do I access embedded json objects in a Pandas DataFrame?

For example, df['entities'].apply(pd.Series)['urls'].apply(pd.Series)[0].apply(pd.Series)['indices'][0][0]
returns 117.

To access full_name and copy it to the df, try this:
    df['full_name'] = df['place'].apply(pd.Series)['full_name'], which returns 0    Austin, TX.

ContentLicense: CC BY-SA 3.0

Body:
I'm having some issues with the index from a Pandas data frame. What I'm trying to do is load data from a JSON file, create a Pandas data frame and then select specific fields from that data frame and send it to my database.

The following is a link to what's in the JSON file so you can see the fields actually exist:
https://pastebin.com/Bzatkg4L

import pandas as pd
from pandas.io import sql
import MySQLdb
from sqlalchemy import create_engine

# Open and read the text file where all the Tweets are
with open('US_tweets.json') as f:
    tweets = f.readlines()

# Convert the list of Tweets into a structured dataframe
df = pd.DataFrame(tweets)
# Attributes needed should be here
df = df[['created_at', 'screen_name', 'id', 'country_code', 'full_name', 'lang', 'text']]

# To create connection and write table into MySQL
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
                       .format(user="blah",
                               pw="blah",
                               db="blah"))

df.to_sql(con=engine, name='US_tweets_Table', if_exists='replace', flavor='mysql')

Thanks for your help!

Body:
Pandas doesn't map every object in the JSON file to a column in the dataframe. Your example file contains 24 columns:

with open('tweets.json') as f:
    df = pd.read_json(f, lines = True)
df.columns

Returns:

Index(['contributors', 'coordinates', 'created_at', 'entities',
   'favorite_count', 'favorited', 'geo', 'id', 'id_str',
   'in_reply_to_screen_name', 'in_reply_to_status_id',
   'in_reply_to_status_id_str', 'in_reply_to_user_id',
   'in_reply_to_user_id_str', 'is_quote_status', 'lang', 'metadata',
   'place', 'retweet_count', 'retweeted', 'source', 'text', 'truncated',
   'user'],
  dtype='object')

To dig deeper into the JSON data, I found this solution, but I hope a more elegant approach exists: How do I access embedded json objects in a Pandas DataFrame?

For example, df['entities'].apply(pd.Series)['urls'].apply(pd.Series)[0].apply(pd.Series)['indices'][0][0]
returns 117.

To access full_name and copy it to the df, try this:
    df['full_name'] = df['place'].apply(pd.Series)['full_name'], which returns 0    Austin, TX.


问:
jQuery/JavaScript to replace broken images
I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.

How do I use jQuery to get the set of images, filter it to broken images then replace the src?

--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.

答:
I got the same problem. This code works well on my case. </p>

```<code>// Replace broken images by a default img
$('img').each(function(){
    if($(this).attr('src') === ''){
      this.src = '/default_feature_image.png';
    }
});
</code>```

OwnerDisplayName: Dan

LastEditorDisplayName: Dan

Body:
I got the same problem. This code works well on my case.

// Replace broken images by a default img
$('img').each(function(){
    if($(this).attr('src') === ''){
      this.src = '/default_feature_image.png';
    }
});


问:
How to restricted the dragging of a circle on a line. JavaFX
Say I have a line shape on the pane, and I want circle shapes on it.How can I restrict the the dragging of the circle such that the circles can be only dragged left and right on the line, but no anywhere else. </p>

答:
This implementation follows the line and does not go pass the line ends.

The key to following is y = mx + b. m = slope of line and b = y-intercept.

Here is a crude implementation:

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication42 extends Application {

    @Override
    public void start(Stage primaryStage) {
        AnchorPane root = new AnchorPane();

        Line line = new Line(20, 120, 70, 170);
        line.setStrokeWidth(3);

        //When the line is clicked by the mouse add a circle
        line.setOnMouseClicked((mouseClickedEvent )->{
            Circle c1 = new Circle(mouseClickedEvent.getSceneX(), mouseClickedEvent.getSceneY(), 25, Color.BLUE);
            //When the circle is dragged follow the line
            c1.setOnMouseDragged(mouseDraggedEvent -> {
                double slope = lineSlope(line.getStartX(), line.getEndX(), line.getStartY(), line.getEndY());
                double yIntercept = yIntercept(slope, line.getStartX(), line.getStartY());
                c1.setCenterY(setCenterY(slope, mouseDraggedEvent.getSceneX(), yIntercept));
                c1.setCenterX(mouseDraggedEvent.getSceneX());

                //Bound checks to make sure circle does not go pass the line ends
                if(c1.getCenterX() > line.getEndX())
                {
                    c1.setCenterX(line.getEndX());
                }
                else if(c1.getCenterX() < line.getStartX())
                {
                    c1.setCenterX(line.getStartX());
                }

                if(c1.getCenterY() > line.getEndY())
                {
                    c1.setCenterY(line.getEndY());
                }
                else if(c1.getCenterY() < line.getStartY())
                {
                    c1.setCenterY(line.getStartY());
                }
            });
            root.getChildren().add(c1);
        });

        root.getChildren().add(line);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    double lineSlope(double x1, double x2, double y1, double y2)
    {
        if(x2 - x1 == 0)
        {
            return 0;
        }

        return (y2 - y1)/(x2 - x1);
    }

    double yIntercept(double slope, double x1, double y1)
    {
        return y1 - (slope * x1);
    }

    double setCenterY(double slope, double x, double  yIntercept)
    {
        return slope * x + yIntercept;
    }
}
</code>```

Body:
This implementation follows the line and does not go pass the line ends.

The key to following is y = mx + b. m = slope of line and b = y-intercept.

Here is a crude implementation:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication42 extends Application {

    @Override
    public void start(Stage primaryStage) {
        AnchorPane root = new AnchorPane();

        Line line = new Line(20, 120, 70, 170);
        line.setStrokeWidth(3);

        //When the line is clicked by the mouse add a circle
        line.setOnMouseClicked((mouseClickedEvent )->{
            Circle c1 = new Circle(mouseClickedEvent.getSceneX(), mouseClickedEvent.getSceneY(), 25, Color.BLUE);
            //When the circle is dragged follow the line
            c1.setOnMouseDragged(mouseDraggedEvent -> {
                double slope = lineSlope(line.getStartX(), line.getEndX(), line.getStartY(), line.getEndY());
                double yIntercept = yIntercept(slope, line.getStartX(), line.getStartY());
                c1.setCenterY(setCenterY(slope, mouseDraggedEvent.getSceneX(), yIntercept));
                c1.setCenterX(mouseDraggedEvent.getSceneX());

                //Bound checks to make sure circle does not go pass the line ends
                if(c1.getCenterX() > line.getEndX())
                {
                    c1.setCenterX(line.getEndX());
                }
                else if(c1.getCenterX() < line.getStartX())
                {
                    c1.setCenterX(line.getStartX());
                }

                if(c1.getCenterY() > line.getEndY())
                {
                    c1.setCenterY(line.getEndY());
                }
                else if(c1.getCenterY() < line.getStartY())
                {
                    c1.setCenterY(line.getStartY());
                }
            });
            root.getChildren().add(c1);
        });

        root.getChildren().add(line);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    double lineSlope(double x1, double x2, double y1, double y2)
    {
        if(x2 - x1 == 0)
        {
            return 0;
        }

        return (y2 - y1)/(x2 - x1);
    }

    double yIntercept(double slope, double x1, double y1)
    {
        return y1 - (slope * x1);
    }

    double setCenterY(double slope, double x, double  yIntercept)
    {
        return slope * x + yIntercept;
    }
}


问:
How to get the last dir from a path in a string
I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

```<code>result = test
</code>```

答:
```<code>$directory = 'Home/new_folder/test';
$path = explode('/',$directory);
$lastDir = array_pop($path);
</code>```

Body:
I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

result = test

ContentLicense: CC BY-SA 2.5


问:
JavaScript checkbox dropdown style not working
Beginner here.

My functionality is working, but at the moment it shows the checkboxes already dropped down.

I want to hit the drop down in order to see the boxes.

Help!

```<code><style>
  .multiselect {
    width: 450px;
  }

  .selectBox {
    position: relative;
  }

  .selectBox select {
    width: 100%;
    font-weight: bold;
  }

  .overSelect {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }

  #checkboxes {
    display: none;
    border: 1px #dadada solid;
  }

  #checkboxes label {
    display: block;
  }

  #checkboxes label:hover {
    background-color: #1e90ff;
  }
</style>
</code>```

And here is the second part, I'm not sure what I'm doing wrong any help would be highly appreciated.
This is the HTML.

```<code><div class="multiselect">
  <div class="selectBox" onclick="showCheckboxes(0)">
    <select>
      <option>Select an option</option>
    </select>
    <div class="overSelect"></div>
  </div>
  <div id="checkboxes-0">
    <input type="checkbox" name="at0[]" id="one" value="red" />red
    <input type="checkbox" name="at0[]" id="two" value="blue" />blue
    <input type="checkbox" name="at0[]" id="three" value="green" />green

<script>
  var cbOneExpanded = false;
  var cbTwoExpanded = false;

  function showCheckboxes(id) {
    var checkboxes = document.getElementById('checkboxes-' + id);

    if (id > 0) {
      if (!cbTwoExpanded) {
        checkboxes.style.display = 'block';
        cbTwoExpanded = true;
      } else {
        checkboxes.style.display = 'none';
        cbTwoExpanded = false;
      }
    } else {
      if (!cbOneExpanded) {
        checkboxes.style.display = 'block';
        cbOneExpanded = true;
      } else {
        checkboxes.style.display = 'none';
        cbOneExpanded = false;
      }
    }
  }
</script>
</code>```

Thanks again.

答:
Check this.I don't know if it's what you are looking for but it's working.</p>

```<code> <script>
  $(document).ready(function(){

    $("#checkboxes-0").css("display","none");

    flag = true;

    $(".selectBox").on("click",function(){
       if(flag){
        $("#checkboxes-0").css("display","block");
        flag = false;
       }else{
        $("#checkboxes-0").css("display","none");
        flag = true;
       }

    });

  });
</script>

</head>
<body>

<style>
  .multiselect {
    width: 450px;
  }

  .selectBox {
    position: relative;
  }

  .selectBox select {
    width: 100%;
    font-weight: bold;
  }

  .overSelect {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }

  #checkboxes {
    display: none;
    border: 1px #dadada solid;
  }

  #checkboxes label {
    display: block;
  }

  #checkboxes label:hover {
    background-color: #1e90ff;
  }
</style>

<div class="multiselect">
  <div class="selectBox">
    <select>
      <option>Select an option</option>
    </select>
    <div class="overSelect"></div>
  </div>
  <div id="checkboxes-0">
     <input type="checkbox" name="at0[]" id="one" value="red" />red
     <input type="checkbox" name="at0[]" id="two" value="blue" />blue
     <input type="checkbox" name="at0[]" id="three" value="green" />green
    </div>
</code>```

Body:
Beginner here.

My functionality is working, but at the moment it shows the checkboxes already dropped down.

I want to hit the drop down in order to see the boxes.

Help!

And here is the second part, I'm not sure what I'm doing wrong any help would be highly appreciated.
This is the HTML.

    <select>
      <option>Select an option</option>
    </select>

    <input type="checkbox" name="at0[]" id="one" value="red" />red
    <input type="checkbox" name="at0[]" id="two" value="blue" />blue
    <input type="checkbox" name="at0[]" id="three" value="green" />green

Thanks again.

Body:
Check this.I don't know if it's what you are looking for but it's working.

 <script>
  $(document).ready(function(){

    $("#checkboxes-0").css("display","none");

    flag = true;

    $(".selectBox").on("click",function(){
       if(flag){
        $("#checkboxes-0").css("display","block");
        flag = false;
       }else{
        $("#checkboxes-0").css("display","none");
        flag = true;
       }

    });

  });
</script>

</head>
<body>

<style>
  .multiselect {
    width: 450px;
  }

  .selectBox {
    position: relative;
  }

  .selectBox select {
    width: 100%;
    font-weight: bold;
  }

  .overSelect {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }

  #checkboxes {
    display: none;
    border: 1px #dadada solid;
  }

  #checkboxes label {
    display: block;
  }

  #checkboxes label:hover {
    background-color: #1e90ff;
  }
</style>

<div class="multiselect">
  <div class="selectBox">
    <select>
      <option>Select an option</option>
    </select>
    <div class="overSelect"></div>
  </div>
  <div id="checkboxes-0">
     <input type="checkbox" name="at0[]" id="one" value="red" />red
     <input type="checkbox" name="at0[]" id="two" value="blue" />blue
     <input type="checkbox" name="at0[]" id="three" value="green" />green
    </div>


问:
How to check if a variable has characters that are not allowed in?
I am writing a password program where it will display a score if certain requirements are met. But I am stuck on how to check if some characters are not allowed. If they are not allowed it should notify the reader.
Here is my code:

```<code>user_password = input("\nEnter your password:")
user_score = 0
user_length = len(user_password)
symbols = "$%^&*()_-+="

if len(user_password)>24:
    print("Your password is too long! It must be between 6 and 24")
elif len(user_password)<6:
    print("Your password is too short! It must be between 6 and 24")
elif len(user_password) >=6 and len(user_password) <= 24:
    lower = sum([int(c.islower()) for c in user_password])
    if lower > 0:
            user_score = user_score + 5
    upper = sum([int(c.isupper()) for c in user_password])
    if upper > 0:
            user_score = user_score + 5
    integer = sum([int(c.isdigit()) for c  in user_password])
    if integer > 0:
            user_score = user_score + 5
    for c in symbols:
            if c in user_password:
                    user_score = user_score + 5
    for c in user_password:
            if c not in symbols:
                    print("Some symbols you entered are not allowed")
                    break
</code>```

I want it so that the program will end if a symbol is wrongly entered it. However when a wrong symbol is entered it displays the message the amount of times the symbol is entered. Any help will be appreciated.

答:
You need to change the last for-loop so that it fails if c in symbols, you had a not in there that was throwing the program off...

```<code>for c in user_password:
            if c in symbols:
                    print("Some symbols you entered are not allowed")
                    break
</code>```

A shorter way to do this with just 2``lines would be to use any:

```<code>if any(c in symbols for c in user_password):
            print("Some symbols you entered are not allowed")
</code>```

As a final note, you should try to keep your indentation width to a constant 4 spaces for readablility. I haven't done this in these snippets as you will be able to test them with your existing code, but ideally you should change them.

Body:
I am writing a password program where it will display a score if certain requirements are met. But I am stuck on how to check if some characters are not allowed. If they are not allowed it should notify the reader.
Here is my code:

user_password = input("\nEnter your password:")
user_score = 0
user_length = len(user_password)
symbols = "$%^&*()_-+="

if len(user_password)>24:
    print("Your password is too long! It must be between 6 and 24")
elif len(user_password)<6:
    print("Your password is too short! It must be between 6 and 24")
elif len(user_password) >=6 and len(user_password) <= 24:
    lower = sum([int(c.islower()) for c in user_password])
    if lower > 0:
            user_score = user_score + 5
    upper = sum([int(c.isupper()) for c in user_password])
    if upper > 0:
            user_score = user_score + 5
    integer = sum([int(c.isdigit()) for c  in user_password])
    if integer > 0:
            user_score = user_score + 5
    for c in symbols:
            if c in user_password:
                    user_score = user_score + 5
    for c in user_password:
            if c not in symbols:
                    print("Some symbols you entered are not allowed")
                    break

I want it so that the program will end if a symbol is wrongly entered it. However when a wrong symbol is entered it displays the message the amount of times the symbol is entered. Any help will be appreciated.

Body:
You need to change the last for-loop so that it fails if c in symbols, you had a not in there that was throwing the program off...

for c in user_password:
            if c in symbols:
                    print("Some symbols you entered are not allowed")
                    break

A shorter way to do this with just 2``lines would be to use any:

if any(c in symbols for c in user_password):
            print("Some symbols you entered are not allowed")

As a final note, you should try to keep your indentation width to a constant 4 spaces for readablility. I haven't done this in these snippets as you will be able to test them with your existing code, but ideally you should change them.


问:
Flexbox align center
I have a side nav-bar. I want the items to be evenly spaced so that it fills out the whole 'bar'.

I've tried making my 'container' have justify-content: space-between. However, it's not taking the flex attribute.

I'll post my code as it'll show what I mean.

I also would like it that it stays 'fixed' but doing so cuts the 'container' to about 50% height.

https://codepen.io/azhorabai/pen/MOOwrJ

* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  font-family: "Dosis", sans-serif;
}

body {
  display: flex;
  min-height: 100vh;
  flex-flow: row wrap;
  margin: auto;
  background-color: black;
}

.side-menu {
  background-color: lightcoral;
  font-size: 2em;
  text-transform: uppercase;
  justify-content: space-between;
}

.side-menu ol {
  list-style-type: none;
  max-width: 100%;
  padding: 0px 30px;
}

.side-menu li {
  line-height: 5em;
}

#projects {}

.top-header {
  background-color: lightgreen;
  height: 20vh;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">
</head>

<body>
  <title>X. Quisite</title>
  <nav class="side-menu">
    <ol>
      <li class="about-me">About</li>
      <li class="projects">Projects
        <li>
          <li class="skills">Services</li>
          <li class="contact">Contact</li>
    </ol>
  </nav>
</body>

</html></code>```

答:
When applying flex rules like justify-content: space-between; you need to apply them to an element with the rule display: flex declared.

These flex rules will apply to direct descendant nested elements only, so you should declare them to the unordered list item (ol), then specify the flex-direction: column so that you can justify the content vertically. In addition, you can declare align-items: center; to horizontally align the list items (these rules typically work in reverse if the direction has been specified horizontal, or row, e.g: flex-direction: row).

Lastly, your fixed navigation will occupy the full height of the viewport if you declare top: 0 and bottom: 0 properties.

*{
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    font-family: 'Dosis', sans-serif;
}
body{
    display: flex;
    min-height: 100vh;
    flex-flow: row wrap;
    margin: auto;
    background-color: black;
}

.side-menu {
    background-color: lightcoral;
    font-size: 2em;
    text-transform: uppercase;
    position: fixed;
    top: 0;
    bottom: 0;
}

.side-menu ol {
    list-style-type: none;
    max-width: 100%;
    padding: 0px 30px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin: 0;
    height: 100%;
    align-items: center;
}

.side-menu li{
    /*line-height: 5em;*/ /* unset for code snippet preview */
}

#projects{
}
.top-header{
    background-color: lightgreen;
    height: 20vh;
    box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
    <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">
</head>
<body>
    <title>X. Quisite</title>
        <nav class="side-menu">
            <ol>
                <li class="about-me">About</li>
                <li class="projects">Projects</li>
                <li class="skills">Services</li>
                <li class="contact">Contact</li>
            </ol>
        </nav>
    </body>
</html></code>```

Title: Flexbox align center

Body:
I have a side nav-bar. I want the items to be evenly spaced so that it fills out the whole 'bar'.

I've tried making my 'container' have justify-content: space-between. However, it's not taking the flex attribute.

I'll post my code as it'll show what I mean.

I also would like it that it stays 'fixed' but doing so cuts the 'container' to about 50% height.

https://codepen.io/azhorabai/pen/MOOwrJ

* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  font-family: "Dosis", sans-serif;
}

body {
  display: flex;
  min-height: 100vh;
  flex-flow: row wrap;
  margin: auto;
  background-color: black;
}

.side-menu {
  background-color: lightcoral;
  font-size: 2em;
  text-transform: uppercase;
  justify-content: space-between;
}

.side-menu ol {
  list-style-type: none;
  max-width: 100%;
  padding: 0px 30px;
}

.side-menu li {
  line-height: 5em;
}

#projects {}

.top-header {
  background-color: lightgreen;
  height: 20vh;
  box-sizing: border-box;
}

  <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">

  <title>X. Quisite</title>

About

Projects

Services

Contact

Body:
When applying flex rules like justify-content: space-between; you need to apply them to an element with the rule display: flex declared.

These flex rules will apply to direct descendant nested elements only, so you should declare them to the unordered list item (ol), then specify the flex-direction: column so that you can justify the content vertically. In addition, you can declare align-items: center; to horizontally align the list items (these rules typically work in reverse if the direction has been specified horizontal, or row, e.g: flex-direction: row).

Lastly, your fixed navigation will occupy the full height of the viewport if you declare top: 0 and bottom: 0 properties.

*{
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    font-family: 'Dosis', sans-serif;
}
body{
    display: flex;
    min-height: 100vh;
    flex-flow: row wrap;
    margin: auto;
    background-color: black;
}

.side-menu {
    background-color: lightcoral;
    font-size: 2em;
    text-transform: uppercase;
    position: fixed;
    top: 0;
    bottom: 0;
}

.side-menu ol {
    list-style-type: none;
    max-width: 100%;
    padding: 0px 30px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin: 0;
    height: 100%;
    align-items: center;
}

.side-menu li{
    /*line-height: 5em;*/ /* unset for code snippet preview */
}

#projects{
}
.top-header{
    background-color: lightgreen;
    height: 20vh;
    box-sizing: border-box;
}

<html>
<head>
    <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">
</head>
<body>
    <title>X. Quisite</title>
        <nav class="side-menu">
            <ol>
                <li class="about-me">About</li>
                <li class="projects">Projects</li>
                <li class="skills">Services</li>
                <li class="contact">Contact</li>
            </ol>
        </nav>
    </body>
</html>


问:
How to upload files in a bucket on Google Cloud Storage using python snippets.py?
I am trying to learn how to upload files in a bucket on Google Cloud Storage.
I found this code: https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/storage/cloud-client
This can do a bunch of operations like create-bucket, delete-bucket, list, upload and download …

But, I am unable to run the code.

I tried:

```<code>python snippets.py [-h] scene.appspot.com list
</code>```

Error:

error: argument command: invalid choice: 'scene-maker.appspot.com'
  (choose from 'create-bucket', 'delete-bucket', 'get-bucket-labels',
  'add-bucket-label', 'remove-bucket-label', 'list', 'list-with-prefix',
  'upload', 'download', 'delete', 'metadata', 'make-public',
  'signed-url', 'rename', 'copy')

I tried:

```<code>python snippets.py [-h] list scene.appspot.com
python snippets.py [-h] list gs://scene.appspot.com
python snippets.py [-h] list "gs://scene.appspot.com"
python snippets.py [-h] list bucket_name
</code>```

Error:

```<code>error: unrecognized arguments: scene.appspot.com
error: unrecognized arguments: gs://scene.appspot.com
</code>```

I tried:

```<code>python snippets.py list [-h] scene.appspot.com
</code>```

Error:

error: argument command: invalid choice: '[-h]' (choose from
  'create-bucket', 'delete-bucket', 'get-bucket-labels',
  'add-bucket-label', 'remove-bucket-label', 'list', 'list-with-prefix',
  'upload', 'download', 'delete', 'metadata', 'make-public',
  'signed-url', 'rename', 'copy')

I tried:

```<code>python snippets.py [-h] list
</code>```

Error:

```<code>Traceback (most recent call last):
  File "snippets.py", line 322, in <module>
    list_blobs(args.bucket_name)
  File "snippets.py", line 88, in list_blobs
    bucket = storage_client.get_bucket(bucket_name)
  File "C:\Anaconda2\lib\site-packages\google\cloud\storage\client.py", line 172, in get_bucket
    bucket = Bucket(self, name=bucket_name)
  File "C:\Anaconda2\lib\site-packages\google\cloud\storage\bucket.py", line 113, in __init__
    name = _validate_name(name)
  File "C:\Anaconda2\lib\site-packages\google\cloud\storage\_helpers.py", line 39, in _validate_name
    'Bucket names must start and end with a number or letter.')
ValueError: Bucket names must start and end with a number or letter.
</code>```

When I run: gsutil ls
I get:

```<code>gs://scene.appspot.com/
gs://staging.scene.appspot.com/
</code>```

How to use python snippets.py command?
Ultimately, I want users to be able to upload files form a web browser to Cloud Storage.

答:
You're having trouble invoking the correct command syntax.

error: argument command: invalid choice: '[-h]'

You shouldn't literally have [-h] in the command. The square brackets are just a standard notation to indicate optional arguments. So you either use -h in the command (which will indicate that you request the command's help/usage screen instead of actually attempting execution of the command) or leave it out completely.

From the page you referenced:

To run this sample:

```<code>$ python snippets.py

usage: snippets.py [-h]
                   bucket_name
                   {create-bucket,delete-bucket,get-bucket-labels,add-bucket-label,remove-bucket-label,list,list-with-prefix,upload,download,delete,metadata,make-public,signed-url,rename,copy}
                   ...
</code>```

So the command expects the first argument (after snippets.py) to be the bucket name, followed by a specific operation to be performed. Depending on the operation other arguments may follow.

The [-h] you used is interpreted as an argument and throws the parser off:

in the 1st attempt [-h] is interpreted as the bucket name and
scene.appspot.com as the operation. But that operation is not a valid one - hence the error.

in the 2nd group of attempts [-h] is interpreted as the bucket name, 'list' as the operation (a valid one this time), but then you have another argument (your attempts to specify the bucket name) which is unexpected for the list operation - hence the errors.

in the 3rd attempt list is interpreted as the bucket name and [-h] as the operation - again an invalid one - hence the error.

in the 4th attempt [-h] is interpreted as the bucket name, 'list' as the operation (valid). This time the number of arguments and the operation appear correct and the code proceeds further to validate the bucket name, which fails as [-h] is not a valid one - hence the error.

So I'd try (I'm unsure about the actual expected format for the bucket name):

```<code>python snippets.py scene.appspot.com list
python snippets.py gs://scene.appspot.com list
</code>```

To upload file to the bucket (use the correct bucket name format determine from the previous attempt, I'll assume it's scene.appspot.com from now on), it's probably something starting with:

```<code>python snippets.py scene.appspot.com upload
</code>```

To see the expected syntax for this operation add the -h option:

```<code>python snippets.py -h scene.appspot.com upload
</code>```

Note: this whole method is command-driven, uploading files from a web browser to Cloud Storage is a different story altogether. I'd ask that as a separate question, with lots of details, as there can be many answers to it.

Body:
I am trying to learn how to upload files in a bucket on Google Cloud Storage.
I found this code: https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/storage/cloud-client
This can do a bunch of operations like create-bucket, delete-bucket, list, upload and download …

But, I am unable to run the code.

I tried:

python snippets.py [-h] scene.appspot.com list

Error:

error: argument command: invalid choice: 'scene-maker.appspot.com'
  (choose from 'create-bucket', 'delete-bucket', 'get-bucket-labels',
  'add-bucket-label', 'remove-bucket-label', 'list', 'list-with-prefix',
  'upload', 'download', 'delete', 'metadata', 'make-public',
  'signed-url', 'rename', 'copy')

I tried:

python snippets.py [-h] list scene.appspot.com
python snippets.py [-h] list gs://scene.appspot.com
python snippets.py [-h] list "gs://scene.appspot.com"
python snippets.py [-h] list bucket_name

Error:

error: unrecognized arguments: scene.appspot.com
error: unrecognized arguments: gs://scene.appspot.com

I tried:

python snippets.py list [-h] scene.appspot.com

Error:

error: argument command: invalid choice: '[-h]' (choose from
  'create-bucket', 'delete-bucket', 'get-bucket-labels',
  'add-bucket-label', 'remove-bucket-label', 'list', 'list-with-prefix',
  'upload', 'download', 'delete', 'metadata', 'make-public',
  'signed-url', 'rename', 'copy')

I tried:

python snippets.py [-h] list

Error:

Traceback (most recent call last):
  File "snippets.py", line 322, in <module>
    list_blobs(args.bucket_name)
  File "snippets.py", line 88, in list_blobs
    bucket = storage_client.get_bucket(bucket_name)
  File "C:\Anaconda2\lib\site-packages\google\cloud\storage\client.py", line 172, in get_bucket
    bucket = Bucket(self, name=bucket_name)
  File "C:\Anaconda2\lib\site-packages\google\cloud\storage\bucket.py", line 113, in __init__
    name = _validate_name(name)
  File "C:\Anaconda2\lib\site-packages\google\cloud\storage\_helpers.py", line 39, in _validate_name
    'Bucket names must start and end with a number or letter.')
ValueError: Bucket names must start and end with a number or letter.

When I run: gsutil ls
I get:

gs://scene.appspot.com/
gs://staging.scene.appspot.com/

How to use python snippets.py command?
Ultimately, I want users to be able to upload files form a web browser to Cloud Storage.

Body:
You're having trouble invoking the correct command syntax.

error: argument command: invalid choice: '[-h]'

You shouldn't literally have [-h] in the command. The square brackets are just a standard notation to indicate optional arguments. So you either use -h in the command (which will indicate that you request the command's help/usage screen instead of actually attempting execution of the command) or leave it out completely.

From the page you referenced:

To run this sample:

$ python snippets.py

usage: snippets.py [-h]
                   bucket_name
                   {create-bucket,delete-bucket,get-bucket-labels,add-bucket-label,remove-bucket-label,list,list-with-prefix,upload,download,delete,metadata,make-public,signed-url,rename,copy}
                   ...

So the command expects the first argument (after snippets.py) to be the bucket name, followed by a specific operation to be performed. Depending on the operation other arguments may follow.

The [-h] you used is interpreted as an argument and throws the parser off:

in the 1st attempt [-h] is interpreted as the bucket name and
scene.appspot.com as the operation. But that operation is not a valid one - hence the error.

in the 2nd group of attempts [-h] is interpreted as the bucket name, 'list' as the operation (a valid one this time), but then you have another argument (your attempts to specify the bucket name) which is unexpected for the list operation - hence the errors.

in the 3rd attempt list is interpreted as the bucket name and [-h] as the operation - again an invalid one - hence the error.

in the 4th attempt [-h] is interpreted as the bucket name, 'list' as the operation (valid). This time the number of arguments and the operation appear correct and the code proceeds further to validate the bucket name, which fails as [-h] is not a valid one - hence the error.

So I'd try (I'm unsure about the actual expected format for the bucket name):

python snippets.py scene.appspot.com list
python snippets.py gs://scene.appspot.com list

To upload file to the bucket (use the correct bucket name format determine from the previous attempt, I'll assume it's scene.appspot.com from now on), it's probably something starting with:

python snippets.py scene.appspot.com upload

To see the expected syntax for this operation add the -h option:

python snippets.py -h scene.appspot.com upload

Note: this whole method is command-driven, uploading files from a web browser to Cloud Storage is a different story altogether. I'd ask that as a separate question, with lots of details, as there can be many answers to it.


问:
$watch binded variable in parent and nested controller
I have a question about $watch and the scope in nested controller.

I have an input binded with a ng-model.  For example, in my html

```<code>    <input ng-model='searchString' />
</code>```

This is within the child(nested) controller, but I defined ng-model in parent controller.  So I tried to $watch in parent controller.  It doesn't work.

```<code>    app.controller('mainCtrl', ['$scope', function($scope){
        $scope.searchString = '';
        $scope.$watch('searchString', function(){
            console.log("changed in parent");
        })
    }]);
    app.controller("nestedCtrl", ["$scope", function($scope){
    }])
</code>```

However, if I put $watch in child controller it would work.

```<code>    app.controller("nestedCtrl", ["$scope", function($scope){
        $scope.$watch('searchString', function(){
            console.log("changed in child");
        })
    }])
</code>```

Why I defined the scope in parent controller but can only watch in child controller?
Any ways could let parent controller detect the changes? Because I need to do something out of child controller but based on this scope variable, but I couldn't.

答:
The quickest and dirtiest will be the following:

You can add a method to parent $scope and then call it from child watcher through $scope.$parent.method().

But it's not a good approach. You should avoid that. Usually to resolve such problems you should create service and inject it in both child and parent controller and communicate through it.

Body:
I have a question about $watch and the scope in nested controller.

I have an input binded with a ng-model.  For example, in my html

    <input ng-model='searchString' />

This is within the child(nested) controller, but I defined ng-model in parent controller.  So I tried to $watch in parent controller.  It doesn't work.

    app.controller('mainCtrl', ['$scope', function($scope){
        $scope.searchString = '';
        $scope.$watch('searchString', function(){
            console.log("changed in parent");
        })
    }]);
    app.controller("nestedCtrl", ["$scope", function($scope){
    }])

However, if I put $watch in child controller it would work.

    app.controller("nestedCtrl", ["$scope", function($scope){
        $scope.$watch('searchString', function(){
            console.log("changed in child");
        })
    }])

Why I defined the scope in parent controller but can only watch in child controller?
Any ways could let parent controller detect the changes? Because I need to do something out of child controller but based on this scope variable, but I couldn't.


问:
How to speed up REGEXP LEVEL query on Oracle SQLDeveloper
I have an INSERT INTO SELECT statement that populates a table with values parsed by a ; in the source table:

```<code>INSERT INTO PC_MATERIALS_BRIDGE (MATERIAL_BRIDGE_ID, VARIABLE_ID, MATERIAL_NAME)
   SELECT PC_VAR_MATERIALS_BRIDGE_SEQ.NEXTVAL, VARIABLE_ID, MATERIAL_NAME FROM (SELECT DISTINCT E.VARIABLE_ID, LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) MATERIAL_NAME
        FROM (SELECT VARIABLE_ID, MATERIALS FROM SRC_VARS_OCEAN_ALL WHERE MATERIALS IS NOT NULL AND MATERIALS != 'N/A) e
        CONNECT BY LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) IS NOT NULL);
</code>```

So, data in the source table

```<code>ID     MATERIAL_NAME
1      paper
2      paper; plastic
</code>```

will appear as

```<code>MATERIAL_BRIDGE_ID     MATERIAL_NAME
1                      paper
2                      paper
3                      plastic
</code>```

in the target table.

The script runs fine; however, it is very expensive because the source table has nearly 40,000 records and some have three values, e.g., paper; plastic; rubber. I know LEVEL is expensive. I have MATERIAL_NAME set to VARCHAR2(255 BYTE). Not sure how to improve other than writing another type of query (e.g., recursive but it's probably difficult). Is DISTINCT also causing it to slow down? The DISTINCT may not be necessary anymore because e.VARIABLE_ID is the primary key now.

答:
This is a very inefficient method. You can observe why it causes problems when you remove DISTINCT in the below simple demo:

```<code>create table SRC_VARS_OCEAN_ALL(
  VARIABLE_ID int,
  MATERIALS varchar2(200)
);

insert into SRC_VARS_OCEAN_ALL values( 1, 'ala;ma;kota' );
insert into SRC_VARS_OCEAN_ALL values( 2, 'as;to;pies' );
insert into SRC_VARS_OCEAN_ALL values( 3, 'baba;jaga' );
insert into SRC_VARS_OCEAN_ALL values( 4, 'zupa;obiad' );
</code>```

and:

```<code>SELECT  E.VARIABLE_ID, level,
        LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) MATERIAL_NAME
FROM (
    SELECT VARIABLE_ID, MATERIALS
    FROM SRC_VARS_OCEAN_ALL
    WHERE MATERIALS IS NOT NULL
    AND MATERIALS != 'N/A'
) e
CONNECT BY LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) IS NOT NULL
order by 1,2;

VARIABLE_ID      LEVEL MATERIAL_NAME
----------- ---------- -----------------
          1          1 ala
          1          2 ma
          1          2 ma
          1          2 ma
          1          2 ma
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          2          1 as
          2          2 to
          2          2 to
          2          2 to
          2          2 to
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          3          1 baba
          3          2 jaga
          3          2 jaga
          3          2 jaga
          3          2 jaga
          4          1 zupa
          4          2 obiad
          4          2 obiad
          4          2 obiad
          4          2 obiad

52 rows selected.
</code>```

This query generates 52 output records for only 4 input rows with 10 values. You can guess how many will be for 40 thousand.

 The query generates hundreds of thausands or even millions of rows, then DISTINCT sorts this huge resultset in order to eliminate duplicates.

The below query should perform much better because it generates only 10 records, no more or less, just as much as needed to do this task:

```<code>SELECT  a.VARIABLE_ID, b.lev_el,
       trim( regexp_substr( a.MATERIALS, '[^;]+', 1, b.lev_el )) as MATERIAL_NAME
FROM SRC_VARS_OCEAN_ALL a
JOIN (
  SELECT level as lev_el
  FROM dual CONNECT BY level <= 100
) b
ON b.lev_el <= regexp_count( a.MATERIALS, ';' ) + 1

VARIABLE_ID     LEV_EL MATERIAL_NAME
----------- ---------- --------------
          1          1 ala
          2          1 as
          3          1 baba
          4          1 zupa
          1          2 ma
          2          2 to
          3          2 jaga
          4          2 obiad
          1          3 kota
          2          3 pies

10 rows selected.
</code>```

I am assumming that there is no more than 100 values in each list (each individual row has a list with no more than 100 values in it), so there is FROM dual CONNECT BY level <= 100 clause.

Body:
I have an INSERT INTO SELECT statement that populates a table with values parsed by a ; in the source table:

INSERT INTO PC_MATERIALS_BRIDGE (MATERIAL_BRIDGE_ID, VARIABLE_ID, MATERIAL_NAME)
   SELECT PC_VAR_MATERIALS_BRIDGE_SEQ.NEXTVAL, VARIABLE_ID, MATERIAL_NAME FROM (SELECT DISTINCT E.VARIABLE_ID, LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) MATERIAL_NAME
        FROM (SELECT VARIABLE_ID, MATERIALS FROM SRC_VARS_OCEAN_ALL WHERE MATERIALS IS NOT NULL AND MATERIALS != 'N/A) e
        CONNECT BY LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) IS NOT NULL);

So, data in the source table

ID     MATERIAL_NAME
1      paper
2      paper; plastic

will appear as

MATERIAL_BRIDGE_ID     MATERIAL_NAME
1                      paper
2                      paper
3                      plastic

in the target table.

The script runs fine; however, it is very expensive because the source table has nearly 40,000 records and some have three values, e.g., paper; plastic; rubber. I know LEVEL is expensive. I have MATERIAL_NAME set to VARCHAR2(255 BYTE). Not sure how to improve other than writing another type of query (e.g., recursive but it's probably difficult). Is DISTINCT also causing it to slow down? The DISTINCT may not be necessary anymore because e.VARIABLE_ID is the primary key now.

Body:
This is a very inefficient method. You can observe why it causes problems when you remove DISTINCT in the below simple demo:

create table SRC_VARS_OCEAN_ALL(
  VARIABLE_ID int,
  MATERIALS varchar2(200)
);

insert into SRC_VARS_OCEAN_ALL values( 1, 'ala;ma;kota' );
insert into SRC_VARS_OCEAN_ALL values( 2, 'as;to;pies' );
insert into SRC_VARS_OCEAN_ALL values( 3, 'baba;jaga' );
insert into SRC_VARS_OCEAN_ALL values( 4, 'zupa;obiad' );

and:

SELECT  E.VARIABLE_ID, level,
        LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) MATERIAL_NAME
FROM (
    SELECT VARIABLE_ID, MATERIALS
    FROM SRC_VARS_OCEAN_ALL
    WHERE MATERIALS IS NOT NULL
    AND MATERIALS != 'N/A'
) e
CONNECT BY LOWER(TRIM(REGEXP_SUBSTR(e.MATERIALS, '[^;]+', 1, LEVEL))) IS NOT NULL
order by 1,2;

VARIABLE_ID      LEVEL MATERIAL_NAME
----------- ---------- -----------------
          1          1 ala
          1          2 ma
          1          2 ma
          1          2 ma
          1          2 ma
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          1          3 kota
          2          1 as
          2          2 to
          2          2 to
          2          2 to
          2          2 to
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          2          3 pies
          3          1 baba
          3          2 jaga
          3          2 jaga
          3          2 jaga
          3          2 jaga
          4          1 zupa
          4          2 obiad
          4          2 obiad
          4          2 obiad
          4          2 obiad

52 rows selected.

This query generates 52 output records for only 4 input rows with 10 values. You can guess how many will be for 40 thousand.

 The query generates hundreds of thausands or even millions of rows, then DISTINCT sorts this huge resultset in order to eliminate duplicates.

The below query should perform much better because it generates only 10 records, no more or less, just as much as needed to do this task:

SELECT  a.VARIABLE_ID, b.lev_el,
       trim( regexp_substr( a.MATERIALS, '[^;]+', 1, b.lev_el )) as MATERIAL_NAME
FROM SRC_VARS_OCEAN_ALL a
JOIN (
  SELECT level as lev_el
  FROM dual CONNECT BY level <= 100
) b
ON b.lev_el <= regexp_count( a.MATERIALS, ';' ) + 1

VARIABLE_ID     LEV_EL MATERIAL_NAME
----------- ---------- --------------
          1          1 ala
          2          1 as
          3          1 baba
          4          1 zupa
          1          2 ma
          2          2 to
          3          2 jaga
          4          2 obiad
          1          3 kota
          2          3 pies

10 rows selected.

I am assumming that there is no more than 100 values in each list (each individual row has a list with no more than 100 values in it), so there is FROM dual CONNECT BY level <= 100 clause.


问:
Does it matter where I initialize my integer?
I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.

However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?

Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.

```<code>#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;

int main() {

    int value = 0; // where I input
    cin >> value;
    // if you put int result above cin program changes.
    int result = value % 2;

    if (result == 0) {
        cout << "Even number." << endl;
    }
    else {
        cout << "Odd number." << endl;
    }

    return 0;
}
</code>```

答:
C++ read the code top to bottom , line by line. So you will have to int your variable first.I made  a much more simpler version of the program if you want to read it:</p>

```<code>#include <iostream>

using namespace std;

int main() {
int a;
cout << "a=";
cin >> a ;

if(a%2==0)
    {cout<<"a is even";}
else
    {cout<<"a is uneven";}
}
</code>```

Body:
I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.

However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?

Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.

#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;

int main() {

    int value = 0; // where I input
    cin >> value;
    // if you put int result above cin program changes.
    int result = value % 2;

    if (result == 0) {
        cout << "Even number." << endl;
    }
    else {
        cout << "Odd number." << endl;
    }

    return 0;
}

Body:
C++ read the code top to bottom , line by line. So you will have to int your variable first.I made  a much more simpler version of the program if you want to read it:

#include <iostream>

using namespace std;

int main() {
int a;
cout << "a=";
cin >> a ;

if(a%2==0)
    {cout<<"a is even";}
else
    {cout<<"a is uneven";}
}


问:
Supporting multiple languages in a Winforms application
I've almost finished my C# application; the only thing left to do is to implement multiple language support.

I've already created resource files which hold strings for a few languages for all the text displayed on screen.

Example of my English Resource file:

```<code>Name                    |  Value                       | Comment
------------------------------------------------------------------------------
lblName                 |   Name:                      |  Name EN
</code>```

Example of my Dutch Resource file:

```<code>Name                    |  Value                       | Comment
------------------------------------------------------------------------------
lblName                 |  Naam:                       | Name NL
</code>```

How can I bind the field Value to the Text property of my Label (lblName)?

I'm using .NET Framework 3.5.

答:
I know this question have been ask a long time ago but since there was no answer here's what I suggest:

To access a resource file in C# you can use a ResourceManager.
First create your resource manager depending on the curent language.
You have two options for this. You can use a switch or if statement (if the language is determined by a menu) or use localization to use the current culture of the computer. Finally, with both ways you can then call the GetString() method providing the key which I believe in your case is lblName.

N.B: In the example bellow I use the first method which is retrieving the language from a menu.

```<code>string selectedLanguage = comboBoxLang.Text; // Comes from a menu option
string resourceFile = string.Empty;

/***/
Logic to retrieve the proper resourceFile depending on the selectedLanguage.
/***/

ResourceManager rm = new ResourceManager(resourceFile, Assembly.GetExecutingAssembly());

// Set your label text.
lblName.Text = rm.GetString("lblName");
</code>```

Body:
I've almost finished my C# application; the only thing left to do is to implement multiple language support.

I've already created resource files which hold strings for a few languages for all the text displayed on screen.

Example of my English Resource file:

Name                    |  Value                       | Comment
------------------------------------------------------------------------------
lblName                 |   Name:                      |  Name EN

Example of my Dutch Resource file:

Name                    |  Value                       | Comment
------------------------------------------------------------------------------
lblName                 |  Naam:                       | Name NL

How can I bind the field Value to the Text property of my Label (lblName)?

I'm using .NET Framework 3.5.

Body:
I know this question have been ask a long time ago but since there was no answer here's what I suggest:

To access a resource file in C# you can use a ResourceManager.
First create your resource manager depending on the curent language.
You have two options for this. You can use a switch or if statement (if the language is determined by a menu) or use localization to use the current culture of the computer. Finally, with both ways you can then call the GetString() method providing the key which I believe in your case is lblName.

N.B: In the example bellow I use the first method which is retrieving the language from a menu.

string selectedLanguage = comboBoxLang.Text; // Comes from a menu option
string resourceFile = string.Empty;

/***/
Logic to retrieve the proper resourceFile depending on the selectedLanguage.
/***/

ResourceManager rm = new ResourceManager(resourceFile, Assembly.GetExecutingAssembly());

// Set your label text.
lblName.Text = rm.GetString("lblName");


问:
Express Routing: multiple URLs to the same route
I'm trying to make the multiple URLs work on a single express route. How can I make the following URLs all route to the same page?

https://example.com/page-slug-name

https://example.com/page-slug-name/amp

https://example.com

https://example.com/amp

It seems like this should work but it's not:

```<code>router.get("/:slug?(/amp)?", function(req, res, next) {

  if (!req.params.slug) {
    req.params.slug = 'home'
  }

  getData(slug, function(err, data){

    res.render('index', data)

  });

});
</code>```

答:
Instead of using an anonymous function as the route's controller, you can give it a name and pass the name to router.get. You can then have several router.gets that points to the same function.

```<code>function slugController(req, res, next) {

  if (!req.params.slug) {
    req.params.slug = 'home'
  }

  getData(slug, function(err, data){

    res.render('index', data)

  });

});

router.get("/page-slug-name", slugController);
router.get("/page-slug-name/amp", slugController);
router.get("/", slugController);
router.get("/amp", slugController);
</code>```

This works best if there only are a couple of routes.

If you have a ton of routes you have to use the regex stuff that's mentioned in the manual. I don't see any pattern in your URLs though, so it's a bit hard to come up with a good solution using regex.

Body:
I'm trying to make the multiple URLs work on a single express route. How can I make the following URLs all route to the same page?

https://example.com/page-slug-name

https://example.com/page-slug-name/amp

https://example.com

https://example.com/amp

It seems like this should work but it's not:

router.get("/:slug?(/amp)?", function(req, res, next) {

  if (!req.params.slug) {
    req.params.slug = 'home'
  }

  getData(slug, function(err, data){

    res.render('index', data)

  });

});

Body:
Instead of using an anonymous function as the route's controller, you can give it a name and pass the name to router.get. You can then have several router.gets that points to the same function.

function slugController(req, res, next) {

  if (!req.params.slug) {
    req.params.slug = 'home'
  }

  getData(slug, function(err, data){

    res.render('index', data)

  });

});

router.get("/page-slug-name", slugController);
router.get("/page-slug-name/amp", slugController);
router.get("/", slugController);
router.get("/amp", slugController);

This works best if there only are a couple of routes.

If you have a ton of routes you have to use the regex stuff that's mentioned in the manual. I don't see any pattern in your URLs though, so it's a bit hard to come up with a good solution using regex.


问:
Difference between unit type and 'a in ocaml
What's the difference between unit -> unit and 'a -> 'a in OCaml?

For example:

```<code># let f g a = if (g a > a) then a ;;
val f : (unit -> unit) -> unit -> unit = <fun>

# let f g a = if (g a > a ) then a else a;;
val f : ('a -> 'a) -> 'a -> 'a = <fun>
</code>```

Why does the first one give unit -> unit and the second 'a -> 'a?

答:
The if expression in the first variant has no else clause, so the true branch of the if expression must have type unit.  This means that the type of a must be unit as well, and g must have type unit -> unit.

In the second variant, due to the else clause, the only requirement is that the true and false branches of the if expression have the same type, so the type generalizes, and so does the type of g.

Body:
What's the difference between unit -> unit and 'a -> 'a in OCaml?

For example:

# let f g a = if (g a > a) then a ;;
val f : (unit -> unit) -> unit -> unit = <fun>

# let f g a = if (g a > a ) then a else a;;
val f : ('a -> 'a) -> 'a -> 'a = <fun>

Why does the first one give unit -> unit and the second 'a -> 'a?


问:
How do we properly set LoadFactor & concurrency level of our concurrenthashmap?
Am trying to use a concurrent hashmap as a cache for my application, so that it will load all the data from the database at the start.My question is how do I determine the best base configuration of the properties of my concurrent hash map.How do I determine best load factor and concurrency level for my CHM? And this is confusing me because, since we don't know how many threads will try to access my CHM( It all depends on the currently logged in users).

ConcurrentHashMap m = new ConcurrentHashMap(200 , ??, ??);

Concurrent requests could be 100,000 or 1M or 5M, it all depends on logged in users?

答:
First, what you are doing is made complicated by the fact that you must load the values from a database. This assumes that a database connection is available before you start this process.

Second, do you intend to modify the values in the cache once they are loaded? Concurrency still adds some overhead, even if it is less than using synchronize.

If not, look at using some sort of immutable Map, such as ImmutableMap implemented by Google. Load your map in the class static initializer. This method must complete before any access to the Map is allowed. Therefore, you don't have any concurrency issues.


问:
Is the Google Pixel 2 XL phone compatible with AR Core
Could someone having access to the latest Google Pixel 2 (XL) phone please confirm whether the phone is compatible with AR Core?

EDIT

At the time I asked the question there was no information on whether or not Pixel 2 supported ARCore but since then they updated the website with the following information:

Google Pixel, Pixel XL, Pixel 2, Pixel 2 XL

And I got a Pixel 2 in my hand and can confirm I got it working.

答:
There's a list of supported devices here updated regularly
Supported Devices</p>


答:
Note that in OCaml, if is an expression: it returns a value.

The key to understand your problem is that

```<code>if condition then a
</code>```

is equivalent to

```<code>if condition then a else ()
</code>```

The typing rules for if are the following:

the condition should have type bool

both branches should have the same type

the whole if expression has the same type as the branches

In other words, in if cond then a, a should have type unit.

Title: Difference between unit type and 'a in ocaml

Body:
Note that in OCaml, if is an expression: it returns a value.

The key to understand your problem is that

if condition then a

is equivalent to

if condition then a else ()

The typing rules for if are the following:

the condition should have type bool

both branches should have the same type

the whole if expression has the same type as the branches

In other words, in if cond then a, a should have type unit.


问:
ArrayFormula Google Sheets - remove high and low from average
I'm trying to use an arrayformula to calculate the average across 7 columns while removing the max and min number from those columns. The tricky part is there is no preset limit on how may cell will be filled, each time its different.

I have the formula to calculate the average complete:

=ARRAYFORMULA(IF(ISBLANK($A$2:$A),"",IF($J$2:$J="Granted",($AO$2:$AO+$AP$2:$AP+$AQ$2:$AQ+$AR$2:$AR+$AS$2:$AS+AT2:AT)/6,0)))

I've tried using the Trimmean function but it isn't working with the array formula, =Trimmean(AO2:AU2,0.33) any suggestions on how to get it to work?

答:
Assuming the values in the cells that you want to ignore are empty, you want :

```<code>Average of all cells that are filled and not maximum or minimum
</code>```

Which is

```<code>Sum of all cells that are filled and not maximum or minimum / (number of filled cells - 2)
</code>```

Thus

```<code>=(sum(YourRange)-max(YourRange)-min(YourRange))/(count(YourRange)-2)
</code>```

should give you what you want

Body:
Assuming the values in the cells that you want to ignore are empty, you want :

Average of all cells that are filled and not maximum or minimum

Which is

Sum of all cells that are filled and not maximum or minimum / (number of filled cells - 2)

Thus

=(sum(YourRange)-max(YourRange)-min(YourRange))/(count(YourRange)-2)

should give you what you want


问:
Max distance through BFS implementation?
I realize you can find the diameter or the max distance of a undirected unweighted graph by using BFS twice, my question is about the specifics of this algorithm.

If I were to implement this would I literally just do BFS twice and it would return the max distance? or do I have to set throughout the BFS algorithm the distance and weight values for each node and calculate if the new max is greater than the old max, etc? Because I have heard if you use BFS then the last visited value will be the max distance from your original node, which means I wouldn't need to do all that stuff, right?

答:
You have to run BFS n times, once from each node. Distances must be calculated from scratch every time: distances from some node u have no sense when you run bfs from some other node v, so you have to recalculate them entirely.

Now, for each node v you store the maximum distance to any other node. The diameter of the graph is maximum of these maximums.

However, as I understood from your comment, you are solving the problem on for a tree rather than a general graph. In case of the tree, it is simpler. Run BFS from any node v. Find any of the farthest nodes from v; let it be d1. Now run BFS again from node d1 and find any of the farthest nodes from it; let it be d2. Then, a path from d1 to d2 is a diameter of the tree (one of them). There is a proof in the answer to this question.

Note that these two BFS's still compute all distances from scratch. So yes, you just have to run BFS twice.


问:
Create a static library with Swift and xCode9 beta4
I have a static library that compiles some C and ObjC code using the command line tools.

I'd like to start using Swift in this static library as it helps to simplify/shorten the code. (and well, it's the future right?)

I already searched and understood that it wasn't possible to include Swift files in a static library until I saw a post that said it was now possible with xCode 9 beta 4. (Static Library and Swift)

My questions are:

Is this actually true?

If it now works, can someone explain me how one should process to include Swift into a static library?

Is this feature extended to the command line tools, I mean can I do the same in command line?

If possible, then how should I do that? Or is there someone that can provide links on how to do it?

Note: I already explored the questions about how to call Swift from Objective-C from C. I know about the need of a Bridging Header and the generation of a project-Swift.h header file (along with some settings).

答:
As far as using this feature in the command line tools I think it can be done but there are certain flags to be set. I have not done it personally but I found some good answers and info in this article.

As mentioned, Apple does allow Swift in static libraries as of Xcode 9 Beta 4.

We attempted to do this on an existing project with an Objective-C-based target and "child" static library projects and kept running into a linking error

```<code>ld: library not found for -lswiftSwiftOnoneSupport for architecture x86_64
</code>```

also

```<code>ld: library not found for -lswiftDispatch for architecture x86_64
</code>```

This is because the main target (app) is trying to build solely against Objective-C and isn't told by the static library that it needs to include Swift libraries. This was because there weren't any Swift files in the Compile Sources section of our Build Phases for the app target.

So basically all you have to do is add at least one .swift file to that compile list and it will include the Swift libraries for you. It doesn't have even have any code or values in it, it can be an empty file.

Then you can start adding Swift files to your "child" static library project. I would let it generate the bridging header for you at first then you can move it around and change what gets imported (make sure the project points to the right file in the build settings if you move it).

You should still keep in mind that using Swift and Objective-C within the same static library may have issues of its own. I suggest reading the Apple developer doc "Swift and Objective-C in the Same Project" on how to address importing Objective-C into Swift (using a bridging header) and how to use the Swift files in your Objective-C code (importing the generated -Swift.h for your library).

Body:
As far as using this feature in the command line tools I think it can be done but there are certain flags to be set. I have not done it personally but I found some good answers and info in this article.

As mentioned, Apple does allow Swift in static libraries as of Xcode 9 Beta 4.

We attempted to do this on an existing project with an Objective-C-based target and "child" static library projects and kept running into a linking error

ld: library not found for -lswiftSwiftOnoneSupport for architecture x86_64

also

ld: library not found for -lswiftDispatch for architecture x86_64

This is because the main target (app) is trying to build solely against Objective-C and isn't told by the static library that it needs to include Swift libraries. This was because there weren't any Swift files in the Compile Sources section of our Build Phases for the app target.

So basically all you have to do is add at least one .swift file to that compile list and it will include the Swift libraries for you. It doesn't have even have any code or values in it, it can be an empty file.

Then you can start adding Swift files to your "child" static library project. I would let it generate the bridging header for you at first then you can move it around and change what gets imported (make sure the project points to the right file in the build settings if you move it).

You should still keep in mind that using Swift and Objective-C within the same static library may have issues of its own. I suggest reading the Apple developer doc "Swift and Objective-C in the Same Project" on how to address importing Objective-C into Swift (using a bridging header) and how to use the Swift files in your Objective-C code (importing the generated -Swift.h for your library).