问:
adding classes through generic mouse over event
I have four background images on main page each parent of the background image has the width of 25% so that they can take up to full screen,now i have to do something like when  one of them is hovered i need to add the class width-37  which means i am increasing the width of that specific div, by increasing the width of that specific i then need to decrease the width of other divs so that they may remain on the same line for that i will be adding the class width-27 to the divs other than the current div which has the width-37
here's my current code

Html:-

```<code><div class="index-rel" id="index-height">
  <div class="width-25">
    <div class="img img1"></div>
  </div>
  <div class="width-25">
    <div class="img img2"></div>
  </div>
  <div class="width-25">
    <div class="img img3"></div>
  </div>
  <div class="width-25">
    <div class="img img4"></div>
  </div>

  <div class="index-abs">

  </div>
</div>
</code>```

CSS:-

```<code>.index-rel {
  position: relative;
}

.index-rel .width-25 {
  width: 25%;
  display: inline-block;
  float: left;
  height: 100%;
  transition: all 0.5s ease;
}

.index-rel .width-37 {
  width: 37%;
}

.index-rel .width-21 {
  width: 21%;
}

.index-rel .img {
  background-size: cover;
  height: 100%;
  background-repeat: no-repeat;
  background-position: 53% center;

  }

.index-rel .img1 {
  background-image: url("../images/index (3).jpg");
}

.index-rel .img2 {
  background-image: url("../images/index (4).jpg");
}

.index-rel .img3 {
  background-image: url("../images/index (1).jpg");
}

.index-rel .img4 {
  background-image: url("../images/index (2).jpg");
}
</code>```

jQuery:-

```<code>$("#index-height").height($(window).height());

$(document).ready(function() {
  $(".index-rel .width-25").mouseover(function() {
    $(this).addClass("width-37");
  });
  $(".index-rel .width-25").mouseout(function() {
    $(this).removeClass("width-37");
    $(this).removeClass("width-21");
  });
});
</code>```

now the problem is i couldnt really make the logic in Jquery that on mouse over add width-37 to the current div and add width-21 to the other divs! any help?

Jsbin

答:
Need to do like below:-

```<code>$("#index-height").height($(window).height());

$(document).ready(function(){
    $(".width-25").mouseover(function(){
        $(this).addClass("width-37");
        $('.index-rel').children().not($(this)).addClass('width-21');
    });
    $(".width-25").mouseout(function(){
        $('.index-rel').children().removeClass('width-21');
        $('.index-rel').children().removeClass('width-37');
    });
});
</code>```

Working example:- https://jsfiddle.net/5gcLq089/

Body:
I have four background images on main page each parent of the background image has the width of 25% so that they can take up to full screen,now i have to do something like when  one of them is hovered i need to add the class width-37  which means i am increasing the width of that specific div, by increasing the width of that specific i then need to decrease the width of other divs so that they may remain on the same line for that i will be adding the class width-27 to the divs other than the current div which has the width-37
here's my current code

Html:-

CSS:-

.index-rel {
  position: relative;
}

.index-rel .width-25 {
  width: 25%;
  display: inline-block;
  float: left;
  height: 100%;
  transition: all 0.5s ease;
}

.index-rel .width-37 {
  width: 37%;
}

.index-rel .width-21 {
  width: 21%;
}

.index-rel .img {
  background-size: cover;
  height: 100%;
  background-repeat: no-repeat;
  background-position: 53% center;

  }

.index-rel .img1 {
  background-image: url("../images/index (3).jpg");
}

.index-rel .img2 {
  background-image: url("../images/index (4).jpg");
}

.index-rel .img3 {
  background-image: url("../images/index (1).jpg");
}

.index-rel .img4 {
  background-image: url("../images/index (2).jpg");
}

jQuery:-

$("#index-height").height($(window).height());

$(document).ready(function() {
  $(".index-rel .width-25").mouseover(function() {
    $(this).addClass("width-37");
  });
  $(".index-rel .width-25").mouseout(function() {
    $(this).removeClass("width-37");
    $(this).removeClass("width-21");
  });
});

now the problem is i couldnt really make the logic in Jquery that on mouse over add width-37 to the current div and add width-21 to the other divs! any help?

Jsbin

Body:
Need to do like below:-

$("#index-height").height($(window).height());

$(document).ready(function(){
    $(".width-25").mouseover(function(){
        $(this).addClass("width-37");
        $('.index-rel').children().not($(this)).addClass('width-21');
    });
    $(".width-25").mouseout(function(){
        $('.index-rel').children().removeClass('width-21');
        $('.index-rel').children().removeClass('width-37');
    });
});

Working example:- https://jsfiddle.net/5gcLq089/


来源: stackexchange

问:
Rails URI::regexp match with no scheme
I need to validate URL with URI::regexp but some URLs have no scheme.

I tried using,

```<code>URI::regexp(["http", "http])
URI::regexp(%w(http https tel)
</code>```

but they cannot validate empty scheme such as "www.google.com" "google.com".

How can I include/validate such URLs?

答:
Try URI::DEFAULT_PARSER.regexp[:ABS_URI] from the source itself. It also fails in specific conditions as mentioned in "How to check if a URL is valid", but if you are ok with it, it's good to go:

```<code>def valid?(url)
  !!(url =~ URI::ABS_URI || url =~ URI::REL_URI)
end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rails URI::regexp match with no scheme

Body:
I need to validate URL with URI::regexp but some URLs have no scheme.

I tried using,

URI::regexp(["http", "http])
URI::regexp(%w(http https tel)

but they cannot validate empty scheme such as "www.google.com" "google.com".

How can I include/validate such URLs?

Body:
Try URI::DEFAULT_PARSER.regexp[:ABS_URI] from the source itself. It also fails in specific conditions as mentioned in "How to check if a URL is valid", but if you are ok with it, it's good to go:

def valid?(url)
  !!(url =~ URI::ABS_URI || url =~ URI::REL_URI)
end


问:
Display an error message next to the input field if input field is blank
I am new to JavaScript and am a bit stuck...

I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.

Unfortunately is doesn't do anything...
Thanks for your help!!

My HTML:

```<code><form name="user_details" method="post" onsubmit="return checkform()">
    <table id="form_table">
        <tr>
            <td class="form_cell"><label for="first_name">First Name:</label></td>
            <td class="form_cell"><input type="text" id="first_name">*</td>
            <td id="error_first_name">The first name field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="surname">Surname:</label></td>
            <td class="form_cell"><input type="text" id="surname">*</td>
            <td id="error_surname">The surname field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="address">Address:</label></td>
            <td class="form_cell"><input type="text" id="address">*</td>
            <td id="error_address">The address field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="city">City:</label></td>
            <td class="form_cell"><input type="text" id="city">*</td>
            <td id="error_city">The city field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="post_code">Post Code:</label></td>
            <td class="form_cell"><input type="text" id="post_code">*</td>
            <td id="error_post_code">The post code field needs to contain a number.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="email">Email:</label></td>
            <td class="form_cell"><input type="email" id="email">*</td>
            <td id="error_email">The email field needs to contain an email address.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="phone_number">Phone Number:</label></td>
            <td class="form_cell"><input type="text" id="phone_number"></td>
        </tr>
    </table>
        <input type="submit"><input type=reset>
    </form>
</code>```

My JavaScript:

```<code>function checkform() {
var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
}

else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
}

else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
}

else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
}

else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
}

else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
}

else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
}

else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else {
    return ok;
}
</code>```

}

My CSS:

```<code>#error_first_name {
display: none;
}

#error_surname {
display: none;
}

#error_address {
display: none;
}

#error_city {
display: none;
}

#error_post_code {
display: none;
}

#error_email {
display: none;
}
</code>```

答:
Apply the return ok in end of the function also

function checkform() {
  var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

  if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
  } else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
  } else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
  } else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
  } else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
  } else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
  } else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
  } else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
  } else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
  } else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
  } else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
  } else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
  } else {
    return ok;
  }
   return ok;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#error_first_name {
  display: none;
}

#error_surname {
  display: none;
}

#error_address {
  display: none;
}

#error_city {
  display: none;
}

#error_post_code {
  display: none;
}

#error_email {
  display: none;
}</code>```

<form name="user_details" method="post" onsubmit="return checkform()">

      First Name:
      <input type="text" id="first_name">*
      The first name field needs to contain at least one character.

      Surname:
      <input type="text" id="surname">*
      The surname field needs to contain at least one character.

      Address:
      <input type="text" id="address">*
      The address field needs to contain at least one character.

      City:
      <input type="text" id="city">*
      The city field needs to contain at least one character.

      Post Code:
      <input type="text" id="post_code">*
      The post code field needs to contain a number.

      Email:
      <input type="email" id="email">*
      The email field needs to contain an email address.

      Phone Number:
      <input type="text" id="phone_number">

  <input type="submit"><input type=reset>
</form>```

Body:
I am new to JavaScript and am a bit stuck...

I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.

Unfortunately is doesn't do anything...
Thanks for your help!!

My HTML:

<form name="user_details" method="post" onsubmit="return checkform()">

            First Name:
            <input type="text" id="first_name">*
            The first name field needs to contain at least one character.

            Surname:
            <input type="text" id="surname">*
            The surname field needs to contain at least one character.

            Address:
            <input type="text" id="address">*
            The address field needs to contain at least one character.

            City:
            <input type="text" id="city">*
            The city field needs to contain at least one character.

            Post Code:
            <input type="text" id="post_code">*
            The post code field needs to contain a number.

            Email:
            <input type="email" id="email">*
            The email field needs to contain an email address.

            Phone Number:
            <input type="text" id="phone_number">

        <input type="submit"><input type=reset>
    </form>

My JavaScript:

function checkform() {
var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
}

else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
}

else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
}

else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
}

else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
}

else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
}

else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
}

else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else {
    return ok;
}

}

My CSS:

#error_first_name {
display: none;
}

#error_surname {
display: none;
}

#error_address {
display: none;
}

#error_city {
display: none;
}

#error_post_code {
display: none;
}

#error_email {
display: none;
}

Body:
Apply the return ok in end of the function also

function checkform() {
  var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

  if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
  } else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
  } else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
  } else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
  } else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
  } else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
  } else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
  } else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
  } else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
  } else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
  } else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
  } else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
  } else {
    return ok;
  }
   return ok;
}

#error_first_name {
  display: none;
}

#error_surname {
  display: none;
}

#error_address {
  display: none;
}

#error_city {
  display: none;
}

#error_post_code {
  display: none;
}

#error_email {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="user_details" method="post" onsubmit="return checkform()">
  <table id="form_table">
    <tr>
      <td class="form_cell"><label for="first_name">First Name:</label></td>
      <td class="form_cell"><input type="text" id="first_name">*</td>
      <td id="error_first_name">The first name field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="surname">Surname:</label></td>
      <td class="form_cell"><input type="text" id="surname">*</td>
      <td id="error_surname">The surname field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="address">Address:</label></td>
      <td class="form_cell"><input type="text" id="address">*</td>
      <td id="error_address">The address field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="city">City:</label></td>
      <td class="form_cell"><input type="text" id="city">*</td>
      <td id="error_city">The city field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="post_code">Post Code:</label></td>
      <td class="form_cell"><input type="text" id="post_code">*</td>
      <td id="error_post_code">The post code field needs to contain a number.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="email">Email:</label></td>
      <td class="form_cell"><input type="email" id="email">*</td>
      <td id="error_email">The email field needs to contain an email address.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="phone_number">Phone Number:</label></td>
      <td class="form_cell"><input type="text" id="phone_number"></td>
    </tr>
  </table>
  <input type="submit"><input type=reset>
</form>


问:
How Can I Set Video Splash Screen in react native android
I am Developing Sample Application, But i want a video splash (in this Video Duration is 8 sec.) , Actually I  am Setting Splash page,But now i want to set to  Video Splash.

splashPage.js file

This is My Code.
import Video from 'react-native-video';

```<code>//import Main from './main';
import LoginScreen from './App/Components/login.js';
class SplashPage extends Component {

componentWillMount () {
        var navigator = this.props.navigator;
        setTimeout (() => {

          navigator.replace({
                component: LoginScreen,
                 // <-- This is the View you go to
            });
        }, 5000);     //<-- Time until it jumps to "MainView"
    }
    render () {
        return (
            <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>

               <View>{StatusBar.setBackgroundColor('black', true)}</View>
               <Video source={require('./images/splashVideo.mp4')}
                     style={{position: 'absolute',
                             top: 0,
                             left: 0,
                             right: 0,
                             bottom: 0,
                             opacity: 0.3}}
                             muted={true}
                             repeat={true}
                             resizeMode="cover"
     />
               {/*<Image style={{ width: windowSize.width, height: windowSize.height}} source={require('./images/splash.png')}></Image>*/}
            </View>
        );
    }
}
</code>```

Thanks In Advance,

答:
Let's integrate video component into your splash screen:

1) Install the node module:

```<code>npm install react-native-video --save or yarn add react-native-video --save
</code>```

2) Import the video component in your splash screen component:

```<code>`import Video from 'react-native-video'
</code>```

3) Inside the splash screen's render() function put video component

```<code><Video source={require('path of video')}
                     style={{position: 'absolute',
                             top: 0,
                             left: 0,
                             right: 0,
                             bottom: 0,
                             opacity: 0.3}}
                             muted={true}
                             repeat={true}
                             resizeMode="cover"

          />
</code>```

Edits:

```<code>import LoginScreen from './App/Components/login.js';
import Video from 'react-native-video'

class SplashPage extends Component {

componentWillMount () {
        var navigator = this.props.navigator;
        setTimeout (() => {

          navigator.replace({
                component: LoginScreen,
                 // <-- This is the View you go to
            });
        }, 5000);     //<-- Time until it jumps to "MainView"
    }
    render () {
        return (
            <View style={{flex: 1, alignItems: 'center', justifyContent: 'center',width:null,height:null}}>
               <Video source={require('./images/splashVideo.mp4')}
                     style={{position: 'absolute',
                             top: 0,
                             left: 0,
                             right: 0,
                             bottom: 0,
                             opacity: 0.3}}
                             muted={true}
                             repeat={true}
                             resizeMode="cover"
     />
               <View>{StatusBar.setBackgroundColor('black', true)}</View>
               {/*<Image style={{ width: windowSize.width, height: windowSize.height}} source={require('./images/splash.png')}></Image>*/}
            </View>
        );
    }
}
</code>```

Back button integration:

```<code>BackAndroid.addEventListener('hardwareBackPress', () => {
            const { navigator } = this.props
            var routes = navigator.getCurrentRoutes()

            if(routes[routes.length - 1].id == 'main' || routes[routes.length - 1].id == 'login') {
                return false;
            }
            else {
                this.popRoute();
                return true;
            }
        });
</code>```

Cheers:)

Body:
I am Developing Sample Application, But i want a video splash (in this Video Duration is 8 sec.) , Actually I  am Setting Splash page,But now i want to set to  Video Splash.

splashPage.js file

This is My Code.
import Video from 'react-native-video';

//import Main from './main';
import LoginScreen from './App/Components/login.js';
class SplashPage extends Component {

componentWillMount () {
        var navigator = this.props.navigator;
        setTimeout (() => {

          navigator.replace({
                component: LoginScreen,
                 // <-- This is the View you go to
            });
        }, 5000);     //<-- Time until it jumps to "MainView"
    }
    render () {
        return (
            <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>

               <View>{StatusBar.setBackgroundColor('black', true)}</View>
               <Video source={require('./images/splashVideo.mp4')}
                     style={{position: 'absolute',
                             top: 0,
                             left: 0,
                             right: 0,
                             bottom: 0,
                             opacity: 0.3}}
                             muted={true}
                             repeat={true}
                             resizeMode="cover"
     />
               {/*<Image style={{ width: windowSize.width, height: windowSize.height}} source={require('./images/splash.png')}></Image>*/}
            </View>
        );
    }
}

Thanks In Advance,

Body:
Let's integrate video component into your splash screen:

1) Install the node module:

npm install react-native-video --save or yarn add react-native-video --save

2) Import the video component in your splash screen component:

`import Video from 'react-native-video'

3) Inside the splash screen's render() function put video component

<Video source={require('path of video')}
                     style={{position: 'absolute',
                             top: 0,
                             left: 0,
                             right: 0,
                             bottom: 0,
                             opacity: 0.3}}
                             muted={true}
                             repeat={true}
                             resizeMode="cover"

          />

Edits:

import LoginScreen from './App/Components/login.js';
import Video from 'react-native-video'

class SplashPage extends Component {

componentWillMount () {
        var navigator = this.props.navigator;
        setTimeout (() => {

          navigator.replace({
                component: LoginScreen,
                 // <-- This is the View you go to
            });
        }, 5000);     //<-- Time until it jumps to "MainView"
    }
    render () {
        return (
            <View style={{flex: 1, alignItems: 'center', justifyContent: 'center',width:null,height:null}}>
               <Video source={require('./images/splashVideo.mp4')}
                     style={{position: 'absolute',
                             top: 0,
                             left: 0,
                             right: 0,
                             bottom: 0,
                             opacity: 0.3}}
                             muted={true}
                             repeat={true}
                             resizeMode="cover"
     />
               <View>{StatusBar.setBackgroundColor('black', true)}</View>
               {/*<Image style={{ width: windowSize.width, height: windowSize.height}} source={require('./images/splash.png')}></Image>*/}
            </View>
        );
    }
}

Back button integration:

BackAndroid.addEventListener('hardwareBackPress', () => {
            const { navigator } = this.props
            var routes = navigator.getCurrentRoutes()

            if(routes[routes.length - 1].id == 'main' || routes[routes.length - 1].id == 'login') {
                return false;
            }
            else {
                this.popRoute();
                return true;
            }
        });

Cheers:)


问:
How to decide whether to split up a VB.Net application and, if so, how to split it up?
I have 2 1/2 years experience of VB.Net, mostly self taught, so please bear with me if I seem rather noobish still and do not know some of the basics. I would recommend you grab a cup of tea before starting on this, as it appears to have got quite long...

I currently have a rather large application (VB.Net website) of over 15000 lines of code at the last count. It does not do retail or anything particularly complex like that - it is literally just a wholesale viewing website with admin frontend, catalogue / catalogue management system and pageview system.

I don't really know much about how .Net applications work in the background - whether they are all loaded on the same thread or if each has its own thread... I just know how to code them, or at least like to think I do... :-)

Basically my application is set up as follows:

There are two different areas - the customer area and the administration frontend.

The main part of the customer frontend is the Catalogue. The MasterPage will load a list of products but that's all, and this is common to all the customer frontend pages.

I tend to work on only one or several parts of the application at a time before uploading the changes. So, for example, I may alter the hierarchy of the Catalogue and change the Catalogue page to match the hierarchy change whilst leaving everything else alone.

The pageview database is getting really quite large and so it is getting rather slow when the application is first requested due to the way it works.

The application timeout is set to 5 minutes - don't know how to change it, I have even tried asking this question on here and seem to remember the solution was quite complex and I was recommended not to change it, but if a customer requests the application 5 minutes after the last page view then it will reload the application from scratch. This means there is a very slow page load whenever it exceeds 5 minutes of inactivity.

I am not sure if this needs consideration to determine how best to split the application up, if at all, but each part of the catalogue system is set up as follows:

A Manager class at the top level, which is used by the admin frontend to add, edit and remove items of the specified type and the customer frontend to retrieve a list of items of the specified type. For example the "RangeManager" will contain a list of product "Ranges" and will be used to interact with these from the customer frontend.

An Item class, for example Range, which contains a list of Attributes. For example Name, Description, Visible, Created, CreatedBy and so on. The form for adding / editing loops through these to display relevant controls for the administrator. For example a Checkbox for BooleanAttribute.

An Attribute class, which can be of type StringAttribute, BooleanAttribute, IntegerAttribute and so on. There are also custom Attributes (not just datatypes) such as RangeAttribute, UserAttribute and so on. These are given a data field which is used to get a piece of data specific to the item it is contained in when it is first requested. Basically the Item is given a DataRow which is stored and accessed by Attributes only when they are first requested.

When one item is requested from a specific manager is requested, the manager will loop through all the items in the database and create a new instance of the item class. For example when a Range is requested from the RangeManager, the RangeManager will loop through all of the DataRows in the Ranges table and create a new instance of Range for each one. As stated above it simply creates a new instance with the DataRow, rather than loading all the data into it there and then. The Attributes themselves fetch the relevant data from the DataRow as and when they're first requested.

It just seems a tad stupid, in my mind, to recompile and upload the entire application every time I fix a minor bug or a spelling mistake for a word which is in the code behind (for example if I set the text of a Label dynamically). A fix / change to the Catalogue page, the way it is now, may mean a customer trying to view the Contact page, which is in no way related to the Catalogue page apart from by having the same MasterPage, cannot do so because the DLL is being uploaded.

Basically my question is, given my current situation, how would people suggest I change the architecture of the application by way of splitting it into multiple applications? I mean would it be just customer / admin, or customer / admin and pageviews, or some other way? Or not at all? Are there any other alternatives which I have not mentioned here? Could web services come in handy here? Like split the catalogue itself into a different application and just have the masterpage for all the other pages use a web service to get the names of the products to list on the left hand side? Am I just way WAY over-complicating things? Judging by the length of this question I probably am, and it wouldn't be the first time... I have tried to keep it short, but I always fail... :-)

Many thanks in advance, and sorry if I have just totally confused you!

Regards,

Richard

答:
Start by reading:

Application Architecture Guide

ContentLicense: CC BY-SA 2.5


问:
Format date by provided time zone in java
I need to format date time in java for provided time zone. E.g. mm/dd/yyyy for US and dd/mm/yyyy for DE. I have time zone and i can get zoneId, can someone help me. Many thanks.</p>

答:
Use the modern Java date and time classes for everything that has got to do with dates or times.

```<code>    DateTimeFormatter usFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.US);
    System.out.println(date.format(usFormatter));
    DateTimeFormatter deFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.GERMANY);
    System.out.println(date.format(deFormatter));
</code>```

This will print something like

```<code>6/27/17
27.06.17
</code>```

It’s not exactly the formats you asked for, but it’s the formats Java thinks are appropriate for those two locales. I’d try them, and if the users complaint, build my own DateTimeFormatter from a pattern string (like MM/dd/uuuu, for example).

I used a LocalDate for the date in the code, but the same code should work with a LocalDateTime, OffsetDateTime or ZonedDateTime.

If you meant to deduce the locale from the time zone in a ZonedDateTime, I don’t think you can do that reliably. There are often many countries in a time zone, each country having its own locale and its own way of formatting dates. Germany, for example, shares its time zone with Norway, Sweden, Denmark, Poland, France, Switzerland, Austria and Italy, Spain, Serbia and many others.

And if you meant to deduce it from the time zone in an oldfashioned Date object, you certainly cannot simply because a Date does not hold a time zone in it.

Body:
Use the modern Java date and time classes for everything that has got to do with dates or times.

    DateTimeFormatter usFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.US);
    System.out.println(date.format(usFormatter));
    DateTimeFormatter deFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.GERMANY);
    System.out.println(date.format(deFormatter));

This will print something like

6/27/17
27.06.17

It’s not exactly the formats you asked for, but it’s the formats Java thinks are appropriate for those two locales. I’d try them, and if the users complaint, build my own DateTimeFormatter from a pattern string (like MM/dd/uuuu, for example).

I used a LocalDate for the date in the code, but the same code should work with a LocalDateTime, OffsetDateTime or ZonedDateTime.

If you meant to deduce the locale from the time zone in a ZonedDateTime, I don’t think you can do that reliably. There are often many countries in a time zone, each country having its own locale and its own way of formatting dates. Germany, for example, shares its time zone with Norway, Sweden, Denmark, Poland, France, Switzerland, Austria and Italy, Spain, Serbia and many others.

And if you meant to deduce it from the time zone in an oldfashioned Date object, you certainly cannot simply because a Date does not hold a time zone in it.


问:
Check if value in object is null or empty javascript
That's my problem: I could have this array of objects:

```<code>[{
    "name": "Alex",
    "code": "05422180283",
    "pIva": "05422180283",
    "subCode": null
}, {
    "name": "John",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}, {
    "name": "Billy",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}, {
    "name": "Tom",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}]
</code>```

This json is used in a form by an ng-repeat and the null field should be  filled. When the submit button is pressed the system should be check if there are still empty field. So the situation could be this one now:

```<code>[{
    "name": "Alex",
    "code": "05422180283",
    "pIva": "05422180283",
    "subCode": null
}, {
    "name": "John",
    "code": "88985556",
    "pIva": "1919ASVVV",
    "subCode": "9991VVVV"
}, {
    "name": "Billy",
    "code": "89952366555",
    "pIva": "BB588918989",
    "subCode": "ASA234434"
}, {
    "name": "Tom",
    "code": null,
    "pIva": "541198198",
    "subCode": "ACEVV9999"
}]
</code>```

As you can see there are 2 null fields. In this situation the system should be advise the user that there are 2 empty fields. (with an alert or something like that). Otherwise the user can submit the form without any problem. This is what i've done so far:

```<code>angular.forEach($scope.myArray, function(items){
                if(_.chain(items).find(_.isNull).isNull().value()) {
                    //console.log('Found one');
                    formHasEmptyFields = true;
                } else {
                    //console.log('Did not find one');
                    formHasEmptyFields = false;
                }
                if(_(items).find(_.isNull) === null) {
                    //console.log('Found one');
                    formHasEmptyFields = true;
                } else {
                    //console.log('Did not find one');
                    formHasEmptyFields = false;
                }
            });
            if(formHasEmptyFields == true) {
                alert('There are empty fields');
            } else {
                submitFunction($scope.myArray);
            }
</code>```

But it doesn't work because seems that it check only the last object. In fact, if I fill the last object in the form it doesn't show me the alert. Any idea? $scope.myArray is my array of objects of course

答:
The problem is that although formHasEmptyFields does get set to true when there is a null, it gets overwritten with false again in the next iteration.

So, to solve this, only set formHasEmptyFields = false; once, before the loop, and inside the loop, only keep the code that sets it to true.

Having said that, a some or every method is more useful for this scenario than a forEach loop. You may want to use that instead.

Body:
That's my problem: I could have this array of objects:

[{
    "name": "Alex",
    "code": "05422180283",
    "pIva": "05422180283",
    "subCode": null
}, {
    "name": "John",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}, {
    "name": "Billy",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}, {
    "name": "Tom",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}]

This json is used in a form by an ng-repeat and the null field should be  filled. When the submit button is pressed the system should be check if there are still empty field. So the situation could be this one now:

[{
    "name": "Alex",
    "code": "05422180283",
    "pIva": "05422180283",
    "subCode": null
}, {
    "name": "John",
    "code": "88985556",
    "pIva": "1919ASVVV",
    "subCode": "9991VVVV"
}, {
    "name": "Billy",
    "code": "89952366555",
    "pIva": "BB588918989",
    "subCode": "ASA234434"
}, {
    "name": "Tom",
    "code": null,
    "pIva": "541198198",
    "subCode": "ACEVV9999"
}]

As you can see there are 2 null fields. In this situation the system should be advise the user that there are 2 empty fields. (with an alert or something like that). Otherwise the user can submit the form without any problem. This is what i've done so far:

angular.forEach($scope.myArray, function(items){
                if(_.chain(items).find(_.isNull).isNull().value()) {
                    //console.log('Found one');
                    formHasEmptyFields = true;
                } else {
                    //console.log('Did not find one');
                    formHasEmptyFields = false;
                }
                if(_(items).find(_.isNull) === null) {
                    //console.log('Found one');
                    formHasEmptyFields = true;
                } else {
                    //console.log('Did not find one');
                    formHasEmptyFields = false;
                }
            });
            if(formHasEmptyFields == true) {
                alert('There are empty fields');
            } else {
                submitFunction($scope.myArray);
            }

But it doesn't work because seems that it check only the last object. In fact, if I fill the last object in the form it doesn't show me the alert. Any idea? $scope.myArray is my array of objects of course


问:
Multiple queries with Entity Framework in C#
I am using C# and EF to work with a SQL Server database.

I need to do several queries at a time. For now I'm doing all the operations together and in the end I'm calling the DbContext.SaveChanges function to apply all the changes at once.

My problem is that if one of the queries has an error, all the queries are cancelled.

Do I need to call the DbContext.SaveChanges for every query for this?

Thanks

答: if you don't need transaction then you need to call the DbContext.SaveChanges for every query.</p>


问:
How to define a function inside a loop
Why is this not working ?

```<code>u = {}
for me in ['foo', 'bar']:
   def callback():
       return 'I am %s' % me
   u[me] = callback
</code>```

The output I get is:

```<code>>>> u['foo']()
'I am bar'
</code>```

It seems the callback is defined once at the latest iteration.

EDIT

As proposed by kawadhiya21, a class approach would work:

```<code>class CallbackFactory():
    def __init__(self, me):
       self.me = me

    def __call__(self):
       return 'I am %s' % self.me

u = {}
for me in ['foo', 'bar']:

   u[me] = CallbackFactory(me)
</code>```

But it is far more complicated than the former approach.

答:
First off, in your example, u['foo'] should not return a string at all, but a function handle. :) EDIT: this sentence is no longer relevant.

Second, your function callback uses me, from the outer scope. If you change this value (in your case by your loop) in the outer scope, then the function's output also changes.

To fix this, you need to make me part of the function's own scope, e.g. by doing:

```<code>def callback(int_me=me):
    return 'I am %s' % int_me
</code>```

Title: How to define a function inside a loop

Body:
Why is this not working ?

u = {}
for me in ['foo', 'bar']:
   def callback():
       return 'I am %s' % me
   u[me] = callback

The output I get is:

>>> u['foo']()
'I am bar'

It seems the callback is defined once at the latest iteration.

EDIT

As proposed by kawadhiya21, a class approach would work:

class CallbackFactory():
    def __init__(self, me):
       self.me = me

    def __call__(self):
       return 'I am %s' % self.me

u = {}
for me in ['foo', 'bar']:

   u[me] = CallbackFactory(me)

But it is far more complicated than the former approach.

Body:
First off, in your example, u['foo'] should not return a string at all, but a function handle. :) EDIT: this sentence is no longer relevant.

Second, your function callback uses me, from the outer scope. If you change this value (in your case by your loop) in the outer scope, then the function's output also changes.

To fix this, you need to make me part of the function's own scope, e.g. by doing:

def callback(int_me=me):
    return 'I am %s' % int_me


问:
Badly designed application: should we rewrite?
When you work on an application that has a bad architecture and you definitely know it won't support well a scale up, what would be the best solution to improve the app?

The app I work on has been built in a very bad way, is difficult to understand and took about 6 months to develop. Although I just arrived on this project and we need to take decisions.

Would you rewrite everything?

Would you refactor piece per piece?

Would you keep it as it and add new features with a better design?

Considering time is money how would you argue about the right solution?

Thanks

答:
I dont think that this can be answered in a general way. But I could ask some questions and the answeres could leed you to a descision:

What has caused the bad design?

Are you able to change the conditions that led to the problems? If not, you might face the same problems in your second attempt while rebuilding from scratch and your second version might also have design flaws.

Do you understand the code good enough to refactor it?

Do you have exclusive time for Refactoring? If you need to do that by the way, you won't be able to refactor bigger things

How good are your tests? Will they uncover new mistakes that will likely appear while refactoring?

Are you able to rebuild the app  without support by your customer? If not, will you get that support?

Are you able to estimate the costs of a redesign and the refactoring? Are you able to pay that?


问:
Docker container cannot access internet, only ping works
After hours of searching and trying solutions I am at an end.

When I start a Docker container on a Centos7 machine, this is what happens:

Cannot communicate via TCP (e.g. run apt update). ping works fine.

Switching network mode to --net=host fixes the issue, but I want to use the default bridge

I added net.ipv4.ip_forward=1 to /etc/sysctl.conf

Container is registered in the bridge network seen via docker network inspect bridge

DNS is configured properly, pinging hostnames works as well as addresses.

Further info

Running apt update shows messages such as:

```<code>Ign http://security.debian.org jessie/updates InRelease
Err http://security.debian.org jessie/updates Release.gpg
  Unable to connect to security.debian.org:http: [IP: 212.211.132.32 80]
</code>```

iptables configuration:

```<code>$ iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     icmp --  anywhere             anywhere
           tcp  --  anywhere             anywhere             tcp dpt:http /* HTTP-IN */
           tcp  --  anywhere             anywhere             tcp dpt:http flags:FIN,SYN,RST,ACK/SYN /* HTTP-SYN */
           tcp  --  anywhere             anywhere             tcp dpt:https /* HTTPS-IN */
           tcp  --  anywhere             anywhere             tcp dpt:https flags:FIN,SYN,RST,ACK/SYN /* HTTPS-SYN */
ACCEPT     tcp  --  anywhere             anywhere             tcp flags:!FIN,SYN,RST,ACK/SYN
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh match-set avast_internal src
ACCEPT     udp  --  anywhere             anywhere             udp dpt:snmp match-set avast_internal src
ACCEPT     tcp  --  anywhere             anywhere             tcp match-set avast_internal src

Chain FORWARD (policy DROP)
target     prot opt source               destination
DOCKER-ISOLATION  all  --  anywhere             anywhere
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
           tcp  --  anywhere             anywhere             tcp spt:http /* HTTP-OUT */
           tcp  --  anywhere             anywhere             tcp spt:https /* HTTPS-OUT */

Chain DOCKER (2 references)
target     prot opt source               destination

Chain DOCKER-ISOLATION (1 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere
</code>```

What could be the cause of this?

Edit:

After opening the firewall using these commands I was able to connect to the internet from the docker container:

```<code>sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT

sudo iptables -t nat -F
sudo iptables -t mangle -F
sudo iptables -F
sudo iptables -X
</code>```

However, after resetting the rules to find out which exactly caused the problem, I am unable to get it back to a working state, even after clearing all iptables rules and restarting docker daemon.

Edit 2:

Turns out there were some rules in the raw table as well, which I did not see before. The following rule was blocking Docker containers from the internet:

```<code>Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

CT         tcp  --  anywhere             anywhere             NOTRACK
</code>```

答:
As you said

```<code>Ign http://security.debian.org jessie/updates InRelease
Err http://security.debian.org jessie/updates Release.gpg
  Unable to connect to security.debian.org:http: [IP: 212.211.132.32 80]
</code>```

This kind of problem arises when the DNS is not confgured for the Docker Containers.[similar problem in my environment as well].

The following procedure will help in resolving the DNS issue while working with DOCKER containers.

First step is to check the external connectivity from the containers:

```<code># docker run busybox ping -c 2 192.203.230.10
PING 192.203.230.10 (192.203.230.10): 56 data bytes
64 bytes from 192.203.230.10: seq=0 ttl=56 time=66.724 ms
64 bytes from 192.203.230.10: seq=1 ttl=56 time=54.786 ms
</code>```

When you try to ping to google.com using the container it fails to reach because of DNS issue.

```<code># docker run busybox nslookup google.com
Server:    8.8.8.8
Address 1: 8.8.8.8
nslookup: can't resolve 'google.com'
</code>```

Find out the DNS server used in your machine :

```<code># nm-tool  |grep DNS
    DNS:             172.24.100.50
    DNS:             10.1.100.50
</code>```

Run it again using DNS IP found in the above step which resolves the DNS issue:

```<code># docker run --dns 172.24.100.50 busybox nslookup google.com
Server:    172.24.100.50
Address 1: 172.24.100.50 indc01.radisys.com
Name:      google.com
Address 1: 2607:f8b0:4009:80c::200e ord36s01-in-x0e.1e100.net
Address 2: 172.217.4.110 ord36s04-in-f14.1e100.net
</code>```

To resolve it permanently add the following content as below to a new file:

```<code># cat /etc/docker/daemon.json
{
    "dns" : ["172.24.100.50", "8.8.8.8"]
}
</code>```

More info on Docker DNS configuration : https://docs.docker.com/engine/userguide/networking/configure-dns/

Restart the docker service and check the connectivity again:

```<code># docker run busybox nslookup google.com
Server:    172.24.100.50
Address 1: 172.24.100.50 indc01.radisys.com
Name:      google.com
Address 1: 2607:f8b0:4009:801::200e ord30s31-in-x0e.1e100.net
Address 2: 172.217.4.238 ord30s31-in-f14.1e100.net
</code>```

Check it by running another container:

```<code># docker run -it e02e811dd08f
/ # ping google.com
PING google.com (172.217.4.238): 56 data bytes
64 bytes from 172.217.4.238: seq=0 ttl=47 time=251.506 ms
64 bytes from 172.217.4.238: seq=1 ttl=47 time=245.621 ms
</code>```

Body:
After hours of searching and trying solutions I am at an end.

When I start a Docker container on a Centos7 machine, this is what happens:

Cannot communicate via TCP (e.g. run apt update). ping works fine.

Switching network mode to --net=host fixes the issue, but I want to use the default bridge

I added net.ipv4.ip_forward=1 to /etc/sysctl.conf

Container is registered in the bridge network seen via docker network inspect bridge

DNS is configured properly, pinging hostnames works as well as addresses.

Further info

Running apt update shows messages such as:

Ign http://security.debian.org jessie/updates InRelease
Err http://security.debian.org jessie/updates Release.gpg
  Unable to connect to security.debian.org:http: [IP: 212.211.132.32 80]

iptables configuration:

$ iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     icmp --  anywhere             anywhere
           tcp  --  anywhere             anywhere             tcp dpt:http /* HTTP-IN */
           tcp  --  anywhere             anywhere             tcp dpt:http flags:FIN,SYN,RST,ACK/SYN /* HTTP-SYN */
           tcp  --  anywhere             anywhere             tcp dpt:https /* HTTPS-IN */
           tcp  --  anywhere             anywhere             tcp dpt:https flags:FIN,SYN,RST,ACK/SYN /* HTTPS-SYN */
ACCEPT     tcp  --  anywhere             anywhere             tcp flags:!FIN,SYN,RST,ACK/SYN
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh match-set avast_internal src
ACCEPT     udp  --  anywhere             anywhere             udp dpt:snmp match-set avast_internal src
ACCEPT     tcp  --  anywhere             anywhere             tcp match-set avast_internal src

Chain FORWARD (policy DROP)
target     prot opt source               destination
DOCKER-ISOLATION  all  --  anywhere             anywhere
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
           tcp  --  anywhere             anywhere             tcp spt:http /* HTTP-OUT */
           tcp  --  anywhere             anywhere             tcp spt:https /* HTTPS-OUT */

Chain DOCKER (2 references)
target     prot opt source               destination

Chain DOCKER-ISOLATION (1 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere

What could be the cause of this?

Edit:

After opening the firewall using these commands I was able to connect to the internet from the docker container:

sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT

sudo iptables -t nat -F
sudo iptables -t mangle -F
sudo iptables -F
sudo iptables -X

However, after resetting the rules to find out which exactly caused the problem, I am unable to get it back to a working state, even after clearing all iptables rules and restarting docker daemon.

Edit 2:

Turns out there were some rules in the raw table as well, which I did not see before. The following rule was blocking Docker containers from the internet:

Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

CT         tcp  --  anywhere             anywhere             NOTRACK

Body:
As you said

Ign http://security.debian.org jessie/updates InRelease
Err http://security.debian.org jessie/updates Release.gpg
  Unable to connect to security.debian.org:http: [IP: 212.211.132.32 80]

This kind of problem arises when the DNS is not confgured for the Docker Containers.[similar problem in my environment as well].

The following procedure will help in resolving the DNS issue while working with DOCKER containers.

First step is to check the external connectivity from the containers:

# docker run busybox ping -c 2 192.203.230.10
PING 192.203.230.10 (192.203.230.10): 56 data bytes
64 bytes from 192.203.230.10: seq=0 ttl=56 time=66.724 ms
64 bytes from 192.203.230.10: seq=1 ttl=56 time=54.786 ms

When you try to ping to google.com using the container it fails to reach because of DNS issue.

# docker run busybox nslookup google.com
Server:    8.8.8.8
Address 1: 8.8.8.8
nslookup: can't resolve 'google.com'

Find out the DNS server used in your machine :

# nm-tool  |grep DNS
    DNS:             172.24.100.50
    DNS:             10.1.100.50

Run it again using DNS IP found in the above step which resolves the DNS issue:

# docker run --dns 172.24.100.50 busybox nslookup google.com
Server:    172.24.100.50
Address 1: 172.24.100.50 indc01.radisys.com
Name:      google.com
Address 1: 2607:f8b0:4009:80c::200e ord36s01-in-x0e.1e100.net
Address 2: 172.217.4.110 ord36s04-in-f14.1e100.net

To resolve it permanently add the following content as below to a new file:

# cat /etc/docker/daemon.json
{
    "dns" : ["172.24.100.50", "8.8.8.8"]
}

More info on Docker DNS configuration : https://docs.docker.com/engine/userguide/networking/configure-dns/

Restart the docker service and check the connectivity again:

# docker run busybox nslookup google.com
Server:    172.24.100.50
Address 1: 172.24.100.50 indc01.radisys.com
Name:      google.com
Address 1: 2607:f8b0:4009:801::200e ord30s31-in-x0e.1e100.net
Address 2: 172.217.4.238 ord30s31-in-f14.1e100.net

Check it by running another container:

# docker run -it e02e811dd08f
/ # ping google.com
PING google.com (172.217.4.238): 56 data bytes
64 bytes from 172.217.4.238: seq=0 ttl=47 time=251.506 ms
64 bytes from 172.217.4.238: seq=1 ttl=47 time=245.621 ms


问:
Why does the content overflow when mu content is set to 100% height
My layout has a header and footer and in between those a content div.

When I set my content height to 100% it overflows instead of expanding the div.

* {
  margin: 0;
  padding: 0;
}

body,
html {
  height: 100%;
}

.header,
.footer {
  height: 100px;
  width: 100%;
  background-color: red;
  color: white;
}

.content {
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <h1>Heading</h1>
</div>
<div class="content">
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
</div>
<div class="footer">
  <h1>Footer
    <h1>
</div></code>```

I already know the solution is to get rid of the 100% height.
But what I want to know is why does this happen. Shouldn't 100% height expand it's height to fit the parent?

Here is the fiddle for my code.

答:
Of course it will overflow.

What height : 100% does is to take the parent's height and use it as its height. It doesn't take what's left of the height remaining, instead it takes the original height of the parent and set it as it's height. I think that's the explanation you want.

Body:
My layout has a header and footer and in between those a content div.

When I set my content height to 100% it overflows instead of expanding the div.

* {
  margin: 0;
  padding: 0;
}

body,
html {
  height: 100%;
}

.header,
.footer {
  height: 100px;
  width: 100%;
  background-color: red;
  color: white;
}

.content {
  width: 100%;
  height: 100%;
}

Heading

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Footer

I already know the solution is to get rid of the 100% height.
But what I want to know is why does this happen. Shouldn't 100% height expand it's height to fit the parent?

Here is the fiddle for my code.


问:
Java Swagger (Springfox) annotations for streaming multipart file upload
We are using spring controllers to handle file uploads:

For example:

```<code>@RequestMapping(value = "/scan", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public ScanResult scan(HttpServletRequest request) throws IOException, FileUploadException {
    return scanService.scanFile(parseMultipart(request));
}
</code>```

But we are not using any multipart resolver, we are streaming the files from the servlet request input stream. We need to start processing the file immediately for performance reasons.

When doing this this way, we can't seem to use the typical detection/configuration for multipart files. I know Springfox (which we use to generate our swagger docs) will generate the appropriate swagger controls if it sees a MultipartFile as a controller parameter, which will not be the case for us.

Are there any other config options available to hint to springfox that we want a file upload here?

答:
Regarding breaking changes in Springfox v2.7.0:

You need to use dataType = "__file" instead of file as commented in https://github.com/springfox/springfox/issues/1285

Body:
We are using spring controllers to handle file uploads:

For example:

@RequestMapping(value = "/scan", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public ScanResult scan(HttpServletRequest request) throws IOException, FileUploadException {
    return scanService.scanFile(parseMultipart(request));
}

But we are not using any multipart resolver, we are streaming the files from the servlet request input stream. We need to start processing the file immediately for performance reasons.

When doing this this way, we can't seem to use the typical detection/configuration for multipart files. I know Springfox (which we use to generate our swagger docs) will generate the appropriate swagger controls if it sees a MultipartFile as a controller parameter, which will not be the case for us.

Are there any other config options available to hint to springfox that we want a file upload here?


问:
Need to further optimize code
Following is the code which I need to optimize:

```<code>    Scanner sc = new Scanner(System.in);
    int sum=0;           //stores the result
</code>```

Creating 4 lists, A B C to save the input values respectively, D to get the final list of results and S to store the sums.

```<code>    ArrayList<Integer> listA = new ArrayList<Integer>();
    ArrayList<Integer> listB = new ArrayList<Integer>();
    ArrayList<Integer> listC = new ArrayList<Integer>();
    ArrayList<Integer> listD = new ArrayList<Integer>();
    ArrayList<Integer> listS = new ArrayList<Integer>();
</code>```

Getting the total number of test cases

```<code>    int T = sc.nextInt();
</code>```

The first line of each testcase contains 3 integers: p, q and r. These denote the lengths of A,B and C respectively.
The second line contains p integers, which are the elements of A. The third line contains q integers, which are the elements of B. The fourth line contains r integers, which are the elements of C.

```<code>    for(int i=0; i<T; i++){
        int p = sc.nextInt();
        int q = sc.nextInt();
        int r = sc.nextInt();
        for(int j=0; j<p; j++){
            int x = sc.nextInt();
            listA.add(x);
        }
        for(int j=0; j<q; j++){
            int x = sc.nextInt();
            listB.add(x);
        }
        for(int j=0; j<r; j++){
            int x = sc.nextInt();
            listC.add(x);
        }
        for (int k = 0; k < listA.size(); k++){
            int a = listA.get(k);
            for(int j=0; j<listB.size(); j++){
                int b = listB.get(j);
                for(int l=0; l<listC.size(); l++){
                    int c=listC.get(l);
                    //System.out.println("a: "+a+" b: "+b+" c: "+c);
                    int d = (a+b)*(b+c);
                    listD.add(d);
                }
            }

        }
        for(int y=0; y<listD.size(); y++){
            sum += listD.get(y);
        }
        sum = sum%1000000007;
        System.out.println(listD);
        listS.add(sum);

    }
    String formattedString = listS.toString()
            .replace(",", "\n")  //remove the commas
            .replace("[", "")  //remove the right bracket
            .replace("]", "")  //remove the left bracket
            .replace(" ", "")
            .trim();
    System.out.println(formattedString);
    sc.close();
</code>```

Is there any way to reduce all the nested loops?

答:
So basically you need to calculate the value of sum in the above code which is basically the sum of all possible permutations of (a+b)*(b+c). I formulated this into a simple sigma equation and simplified it as follows:

From the last equation above if you consider the sum of each list to be X, Y and Z respectively, the above equation boils down to:

```<code>sum=rXY+qXZ+pr*(sum of squares of each element in listB)+p*YZ
</code>```

This is of the order of O(q^2) in worst case as compared to O(pqr) in your code.

Title: Need to further optimize code

Body:
Following is the code which I need to optimize:

    Scanner sc = new Scanner(System.in);
    int sum=0;           //stores the result

Creating 4 lists, A B C to save the input values respectively, D to get the final list of results and S to store the sums.

    ArrayList<Integer> listA = new ArrayList<Integer>();
    ArrayList<Integer> listB = new ArrayList<Integer>();
    ArrayList<Integer> listC = new ArrayList<Integer>();
    ArrayList<Integer> listD = new ArrayList<Integer>();
    ArrayList<Integer> listS = new ArrayList<Integer>();

Getting the total number of test cases

    int T = sc.nextInt();

The first line of each testcase contains 3 integers: p, q and r. These denote the lengths of A,B and C respectively.
The second line contains p integers, which are the elements of A. The third line contains q integers, which are the elements of B. The fourth line contains r integers, which are the elements of C.

    for(int i=0; i<T; i++){
        int p = sc.nextInt();
        int q = sc.nextInt();
        int r = sc.nextInt();
        for(int j=0; j<p; j++){
            int x = sc.nextInt();
            listA.add(x);
        }
        for(int j=0; j<q; j++){
            int x = sc.nextInt();
            listB.add(x);
        }
        for(int j=0; j<r; j++){
            int x = sc.nextInt();
            listC.add(x);
        }
        for (int k = 0; k < listA.size(); k++){
            int a = listA.get(k);
            for(int j=0; j<listB.size(); j++){
                int b = listB.get(j);
                for(int l=0; l<listC.size(); l++){
                    int c=listC.get(l);
                    //System.out.println("a: "+a+" b: "+b+" c: "+c);
                    int d = (a+b)*(b+c);
                    listD.add(d);
                }
            }

        }
        for(int y=0; y<listD.size(); y++){
            sum += listD.get(y);
        }
        sum = sum%1000000007;
        System.out.println(listD);
        listS.add(sum);

    }
    String formattedString = listS.toString()
            .replace(",", "\n")  //remove the commas
            .replace("[", "")  //remove the right bracket
            .replace("]", "")  //remove the left bracket
            .replace(" ", "")
            .trim();
    System.out.println(formattedString);
    sc.close();

Is there any way to reduce all the nested loops?

Body:
So basically you need to calculate the value of sum in the above code which is basically the sum of all possible permutations of (a+b)*(b+c). I formulated this into a simple sigma equation and simplified it as follows:

From the last equation above if you consider the sum of each list to be X, Y and Z respectively, the above equation boils down to:

sum=rXY+qXZ+pr*(sum of squares of each element in listB)+p*YZ

This is of the order of O(q^2) in worst case as compared to O(pqr) in your code.


问:
try block with empty finally block
When we have a try block without any code is finally block, the compiler compiles it fine. However, there is no purpose of try here - because we are neither catching a exception nor cleaning up code in finally block.

```<code>public int updateTable(InputVo sfVo){
    //SqlSession session = ConnFactory.getSqlSession();
    //InputMapper spMapper = session.getMapper(InputMapper .class);
    int updRecs=0;
    try {

        mapper.updateData(sfVo);

        updRecs=sfVo.getRecsUpdated();
        return updRecs;

    } finally {
        //session.close();
    }
}
</code>```

If thats the case, why does JAVA has not considered a compile time check on this ?

Wouldn't be better if compiler throws error at compile time itself - like "Cannot have a empty finally block"

答:
Using a try-finally statement without declaring a catch statement is legal.

From the JLS :

14.20.2. Execution of try-finally and try-catch-finally

A try statement with a finally block is executed by first executing
  the try block. Then there is a choice:

If execution of the try block completes normally, then the finally
  block is executed, and then there is a choice:

If the finally block completes normally, then the try statement
  completes normally.

If the finally block completes abruptly for reason S, then the try
  statement completes abruptly for reason S.

You said :

we are neither catching a exception nor cleaning up code in finally
  block.
  If thats the case, why does JAVA has not considered a compile time
  check on this ?

What you write in the finally statement is of course at the hand of the developer.

Having a empty finally statement is useless but it is the same thing that having an empty if or for statement.

These are helpless but the compiler will not complain about it as it stays valid code in terms of compilation.

However, IDEs could emit warnings about it to point bad smells.

Title: try block with empty finally block

Body:
When we have a try block without any code is finally block, the compiler compiles it fine. However, there is no purpose of try here - because we are neither catching a exception nor cleaning up code in finally block.

public int updateTable(InputVo sfVo){
    //SqlSession session = ConnFactory.getSqlSession();
    //InputMapper spMapper = session.getMapper(InputMapper .class);
    int updRecs=0;
    try {

        mapper.updateData(sfVo);

        updRecs=sfVo.getRecsUpdated();
        return updRecs;

    } finally {
        //session.close();
    }
}

If thats the case, why does JAVA has not considered a compile time check on this ?

Wouldn't be better if compiler throws error at compile time itself - like "Cannot have a empty finally block"


问:
How do you exclude a property in a persistent object in db4o using C#?
Since "[Transient]" does not really work on properties. What do I do now?</p>

答:
db4o doesn't care about properties. It cares about fields.

I guess you are trying to use "auto-implemented properties", correct?

Until we improve db4o to fully understand auto-implemented properties my best bet is to use normal properties for such cases.

[edited]

```<code>class Item
{
    [Transient]
    private int serviceLength;

    public int ServiceLength
    {
       get { return serviceLength; }
       set { serviceLength = value; }
    }
}
</code>```

[/edited]

We do have an open issue to add support for automatic properties. If that's important for you, please, vote on it.

Best

Adriano

Body:
db4o doesn't care about properties. It cares about fields.

I guess you are trying to use "auto-implemented properties", correct?

Until we improve db4o to fully understand auto-implemented properties my best bet is to use normal properties for such cases.

[edited]

class Item
{
    [Transient]
    private int serviceLength;

    public int ServiceLength
    {
       get { return serviceLength; }
       set { serviceLength = value; }
    }
}

[/edited]

We do have an open issue to add support for automatic properties. If that's important for you, please, vote on it.

Best

Adriano


问:
text-overflow in span element not cutting texta outside element width
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

```<code>A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"
</code>```

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>A</span>
  <span id="long-text">Very long text here....</span>
  <span>A</span>
</div></code>```

答:
div {
border-radius: 5px;
 border: 1px solid #000000;
 width: 100px;
 text-overflow: ellipsis;
 display: block;
 overflow: hidden;
 padding: 10px 20px;
 }

span {

text-overflow: ellipsis;
 white-space: nowrap;
 overflow: hidden;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <span>A</span>
    <span id="long-text">Very long text here......</span>
    <span>A</span>
</div></code>```

Body:
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}

  A
  Very long text here....
  A

Body:
div {
border-radius: 5px;
 border: 1px solid #000000;
 width: 100px;
 text-overflow: ellipsis;
 display: block;
 overflow: hidden;
 padding: 10px 20px;
 }

span {

text-overflow: ellipsis;
 white-space: nowrap;
 overflow: hidden;

}

<div>
    <span>A</span>
    <span id="long-text">Very long text here......</span>
    <span>A</span>
</div>


问:
Make a global dict object in python which can access and edit from any py files
I want keep some global data which can access and edit from any python files. I tried with python classes but it is not working across the files the code is given below.(Note :I am not interested to do any file operations)</p>

```<code>class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if Settings.device is None:
            Settings.device = DeviceSettings()

class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

Settings()
Settings.device
</code>```

答:
Dictionaries are mutable by default. You don't need to write a class for it.

```<code># common.py
common_data = {
}

# file1.py
from common import common_data
common_data['key'] = 'value'
</code>```

Now the important question, you need to ask is, is it advisable to use a global variable for mutation.

Body:
I want keep some global data which can access and edit from any python files. I tried with python classes but it is not working across the files the code is given below.(Note :I am not interested to do any file operations)

class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if Settings.device is None:
            Settings.device = DeviceSettings()

class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

Settings()
Settings.device

Body:
Dictionaries are mutable by default. You don't need to write a class for it.

# common.py
common_data = {
}

# file1.py
from common import common_data
common_data['key'] = 'value'

Now the important question, you need to ask is, is it advisable to use a global variable for mutation.


问:
How to test that an expected exception is being thrown using google-truth?
I just want to test if an exception with a given message is being thrown using google-truth.

Is quite easy to do that using junit using @Test(expected=, but I'm unable to figure out how to do that with truth. There are no samples around ThrowableSubject.

Should I stick with plain JUnit for these kind of tests?

答:
As an update here, we've moved away from the pattern Christian described, and Issue #219 has been closed in favor of JUnit's expectThrows() (coming in 4.13, similar methods already exists in TestNG's Assert).

In tandem with expectThrows() you can use Truth to make assertions about the thrown exception. So Christian's example would now be:

```<code>SpecificException expected = expectThrows(
    SpecificException.class, () -> doSomethingThatThrows());
assertThat(expected).hasMessageThat().contains("blah blah blah");
</code>```

Body:
As an update here, we've moved away from the pattern Christian described, and Issue #219 has been closed in favor of JUnit's expectThrows() (coming in 4.13, similar methods already exists in TestNG's Assert).

In tandem with expectThrows() you can use Truth to make assertions about the thrown exception. So Christian's example would now be:

SpecificException expected = expectThrows(
    SpecificException.class, () -> doSomethingThatThrows());
assertThat(expected).hasMessageThat().contains("blah blah blah");


问:
C# WPF Static item and binding combobox
I am trying to do some simple thing in WPF but can't find the way to do it.

I have a ComboBox in a DataGrid header to filter data. The data is binded to a GrouBy statement of all my data.

These show some CheckBox The XAML code is:

```<code><DataGridTextColumn x:Name="Type"
                    Binding="{Binding TypeOfData, Mode=OneTime}"
                    SortMemberPath="TypeOfData"
                    IsReadOnly="true"
                    CanUserSort="true">
    <DataGridTextColumn.Header>
        <DockPanel>
            <Label Content="Type Of Data"
                   DockPanel.Dock="Left"/>
            <ComboBox x:Name="comboBoxType"
                      DockPanel.Dock="Right"
                      SelectionChanged="comboBoxType_SelectionChanged">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel x:Name="itemsComboBox">
                           <CheckBox Name="checkBoxType"
                                     IsChecked="False"
                                     Content="{Binding Key}"
                                     Unchecked="FilterChange"
                                     Checked="FilterChange"/>
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
        </DockPanel>
    </DataGridTextColumn.Header>
</DataGridTextColumn>
</code>```

The code behind fore binding is:

```<code>comboBoxType.ItemsSource = allData.GroupBy(data=> data.TypeOfData).OrderBy(grp=> grp.Key);
</code>```

And this work.

But now I want to add 2 button to check and uncheck all at the end or at the start of the ComboBox but I can't seem to find how to add those static button in a dynamic data template.

Edit Answer to grek40:
I want the buttons in the combobox Items before or after the checkboxes.

CompositeCollection could help but I can't seem to make it work.

Thank You

答:
Replace the DockPanel with a Grid that has several ColumnDefinitions:

```<code><DataGridTextColumn x:Name="Type" Binding="{Binding TypeOfData, Mode=OneTime}" SortMemberPath="TypeOfData" IsReadOnly="true" CanUserSort="true">
    <DataGridTextColumn.Header>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <Label Content="Type Of Data"  />
            <ComboBox x:Name="comboBoxType"
                      Grid.Column="1"
                      SelectionChanged="comboBoxType_SelectionChanged">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel x:Name="itemsComboBox">
                            <CheckBox Name="checkBoxType"
                                      IsChecked="False"
                                      Content="{Binding Key}"
                                      Unchecked="FilterChange"
                                      Checked="FilterChange"/>
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
            <Button Content="Check"
                    Grid.Column="2" />
        </Grid>
    </DataGridTextColumn.Header>
</DataGridTextColumn>
</code>```

Title: C# WPF Static item and binding combobox

Body:
I am trying to do some simple thing in WPF but can't find the way to do it.

I have a ComboBox in a DataGrid header to filter data. The data is binded to a GrouBy statement of all my data.

These show some CheckBox The XAML code is:

<DataGridTextColumn x:Name="Type"
                    Binding="{Binding TypeOfData, Mode=OneTime}"
                    SortMemberPath="TypeOfData"
                    IsReadOnly="true"
                    CanUserSort="true">
    <DataGridTextColumn.Header>
        <DockPanel>

            <ComboBox x:Name="comboBoxType"
                      DockPanel.Dock="Right"
                      SelectionChanged="comboBoxType_SelectionChanged">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel x:Name="itemsComboBox">
                           <CheckBox Name="checkBoxType"
                                     IsChecked="False"
                                     Content="{Binding Key}"
                                     Unchecked="FilterChange"
                                     Checked="FilterChange"/>
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
        </DockPanel>
    </DataGridTextColumn.Header>
</DataGridTextColumn>

The code behind fore binding is:

comboBoxType.ItemsSource = allData.GroupBy(data=> data.TypeOfData).OrderBy(grp=> grp.Key);

And this work.

But now I want to add 2 button to check and uncheck all at the end or at the start of the ComboBox but I can't seem to find how to add those static button in a dynamic data template.

Edit Answer to grek40:
I want the buttons in the combobox Items before or after the checkboxes.

CompositeCollection could help but I can't seem to make it work.

Thank You

Body:
Replace the DockPanel with a Grid that has several ColumnDefinitions:

<DataGridTextColumn x:Name="Type" Binding="{Binding TypeOfData, Mode=OneTime}" SortMemberPath="TypeOfData" IsReadOnly="true" CanUserSort="true">
    <DataGridTextColumn.Header>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <Label Content="Type Of Data"  />
            <ComboBox x:Name="comboBoxType"
                      Grid.Column="1"
                      SelectionChanged="comboBoxType_SelectionChanged">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel x:Name="itemsComboBox">
                            <CheckBox Name="checkBoxType"
                                      IsChecked="False"
                                      Content="{Binding Key}"
                                      Unchecked="FilterChange"
                                      Checked="FilterChange"/>
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
            <Button Content="Check"
                    Grid.Column="2" />
        </Grid>
    </DataGridTextColumn.Header>
</DataGridTextColumn>