问:
react-native Animate image to "breath" in and out
I'm new to react-native and need some help with Animate.

Goal: to animate Image, so that it looks like its slowly breathing.(getting a little larger then smaller, then back again, constantly, like someone breathing in and out)

My images are stored in an array, inside newOrder() method:

```<code> newOrder(timeAsProp) {
    const hour = timeAsProp.slice(0, 2);
    let returnValue = [];
    const yud = <Image key="yud" source={require('./img/yud.png')} style={Style.image} />;
    const hey1 = <Image key="hey1" source={require('./img/hey1.png')} style={Style.image} />;
    const vav = <Image key="vav" source={require('./img/vav.png')} style={Style.image} />;
    const hey2 = <Image key="hey2" source={require('./img/hey2.png')} style={Style.image} />;
     return (
<View style={Style.displayContainer}>{returnValue}</View>
);
</code>```

called in the render method, like this:

```<code>{this.newOrder(parsedTime)}
</code>```

its four seperate images, which are rendered and displayed together on one line.
it looks like this:

letters being rendered to one word:

its important that the Image as a whole, should be breathing together in unison, and not each image on its own.
heres a screen pic so you see what the image looks like, if that will help you understand the best method to make it look alive:

edit:
something that would add to the animation i think, would be two things:
1)size getting larger and smaller
2)actual color patch on the letters slightly moving, maybe closer and further, like zooming in and out or something like that.
i think those two together would make the breathing 3d.

so im interested in hearing peoples opinions how to do this...
thnks!

答:
So for an infinite animation (that you can stop on your own), you can set the width and height of all of the images to the same interpolated Animated value. To generate a breathing effect, one possible way to do this is to tie two animation functions together with one increasing and the other decreasing. For example:

```<code>import React, { Component } from 'react';
import { View, StyleSheet, Animated, Image, Easing } from 'react-native';
import { Constants } from 'expo';

const AnimatedImage = Animated.createAnimatedComponent(Image);

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      size: new Animated.Value(1)
    }
  }

  componentDidMount () {
    this._loopAnimationUp();
  }

  // The animation functions. Initial and end values can be anything (not just 1, 10, but remember to use the same value and flip them:
  _loopAnimationUp() {
    this.state.size.setValue(1);
    Animated.timing(this.state.size, {
      toValue: 10,
      duration: 5000,
      easing: Easing.linear
    }).start((o) => {
      if (o.finished) {
        this._loopAnimationDown();
      }
    });
  }

  _loopAnimationDown() {
    this.state.size.setValue(10);
    Animated.timing(this.state.size, {
      toValue: 1,
      duration: 5000,
      easing: Easing.linear
    }).start((o) => {
      if (o.finished) {
        this._loopAnimationUp();
      }
    });
  }

  render() {
    const size = this.state.size.interpolate({
      inputRange: [1, 10],
      outputRange: [10, 50],
      extrapolate: 'clamp',
    });

    return (
      <View style={styles.container}>
        <AnimatedImage
          style={[styles.image, {
            width: size,
            height: size,
          }]}
          source={{uri: 'http://placekitten.com/g/200/200'}}
        />
        <AnimatedImage
          style={[styles.image, {
            width: size,
            height: size,
          }]}
          source={{uri: 'http://placekitten.com/g/200/200'}}
        />
        <AnimatedImage
          style={[styles.image, {
            width: size,
            height: size,
          }]}
          source={{uri: 'http://placekitten.com/g/200/200'}}
        />
        <AnimatedImage
          style={[styles.image, {
            width: size,
            height: size,
          }]}
          source={{uri: 'http://placekitten.com/g/200/200'}}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    flexDirection: 'row',
  },
  image: {
    justifyContent:'center',
    backgroundColor:'transparent'
  },
});
</code>```

If you need to later stop the animation, you can use:

```<code>this.state.size.stopAnimation();
</code>```

You can see a working implementation of it here using placeholder images.

For the more math inclined, there is probably a way to accomplish this with a single looping animation and using interpolation in a more complex manner.

Body:
I'm new to react-native and need some help with Animate.

Goal: to animate Image, so that it looks like its slowly breathing.(getting a little larger then smaller, then back again, constantly, like someone breathing in and out)

My images are stored in an array, inside newOrder() method:

 newOrder(timeAsProp) {
    const hour = timeAsProp.slice(0, 2);
    let returnValue = [];
    const yud = <Image key="yud" source={require('./img/yud.png')} style={Style.image} />;
    const hey1 = <Image key="hey1" source={require('./img/hey1.png')} style={Style.image} />;
    const vav = <Image key="vav" source={require('./img/vav.png')} style={Style.image} />;
    const hey2 = <Image key="hey2" source={require('./img/hey2.png')} style={Style.image} />;
     return (
<View style={Style.displayContainer}>{returnValue}</View>
);

called in the render method, like this:

{this.newOrder(parsedTime)}

its four seperate images, which are rendered and displayed together on one line.
it looks like this:

letters being rendered to one word:

its important that the Image as a whole, should be breathing together in unison, and not each image on its own.
heres a screen pic so you see what the image looks like, if that will help you understand the best method to make it look alive:

edit:
something that would add to the animation i think, would be two things:
1)size getting larger and smaller
2)actual color patch on the letters slightly moving, maybe closer and further, like zooming in and out or something like that.
i think those two together would make the breathing 3d.

so im interested in hearing peoples opinions how to do this...
thnks!

Body:
So for an infinite animation (that you can stop on your own), you can set the width and height of all of the images to the same interpolated Animated value. To generate a breathing effect, one possible way to do this is to tie two animation functions together with one increasing and the other decreasing. For example:

import React, { Component } from 'react';
import { View, StyleSheet, Animated, Image, Easing } from 'react-native';
import { Constants } from 'expo';

const AnimatedImage = Animated.createAnimatedComponent(Image);

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      size: new Animated.Value(1)
    }
  }

  componentDidMount () {
    this._loopAnimationUp();
  }

  // The animation functions. Initial and end values can be anything (not just 1, 10, but remember to use the same value and flip them:
  _loopAnimationUp() {
    this.state.size.setValue(1);
    Animated.timing(this.state.size, {
      toValue: 10,
      duration: 5000,
      easing: Easing.linear
    }).start((o) => {
      if (o.finished) {
        this._loopAnimationDown();
      }
    });
  }

  _loopAnimationDown() {
    this.state.size.setValue(10);
    Animated.timing(this.state.size, {
      toValue: 1,
      duration: 5000,
      easing: Easing.linear
    }).start((o) => {
      if (o.finished) {
        this._loopAnimationUp();
      }
    });
  }

  render() {
    const size = this.state.size.interpolate({
      inputRange: [1, 10],
      outputRange: [10, 50],
      extrapolate: 'clamp',
    });

    return (
      <View style={styles.container}>
        <AnimatedImage
          style={[styles.image, {
            width: size,
            height: size,
          }]}
          source={{uri: 'http://placekitten.com/g/200/200'}}
        />
        <AnimatedImage
          style={[styles.image, {
            width: size,
            height: size,
          }]}
          source={{uri: 'http://placekitten.com/g/200/200'}}
        />
        <AnimatedImage
          style={[styles.image, {
            width: size,
            height: size,
          }]}
          source={{uri: 'http://placekitten.com/g/200/200'}}
        />
        <AnimatedImage
          style={[styles.image, {
            width: size,
            height: size,
          }]}
          source={{uri: 'http://placekitten.com/g/200/200'}}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    flexDirection: 'row',
  },
  image: {
    justifyContent:'center',
    backgroundColor:'transparent'
  },
});

If you need to later stop the animation, you can use:

this.state.size.stopAnimation();

You can see a working implementation of it here using placeholder images.

For the more math inclined, there is probably a way to accomplish this with a single looping animation and using interpolation in a more complex manner.


来源: stackexchange

问:
libcurl download file size exceed buffer size
I have a question regarding this code at https://curl.haxx.se/libcurl/c/ftpget.html

In the call back function

```<code>static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
  struct FtpFile *out=(struct FtpFile *)stream;
  if(out && !out->stream) {
    /* open file for writing */
    out->stream=fopen(out->filename, "wb");
    if(!out->stream)
      return -1; /* failure, can't open file to write */
  }
  return fwrite(buffer, size, nmemb, out->stream);
}
</code>```

What if the file size exceed the buffer size? I think the function will not be called iteratively since it overwrites the file everytime. Is there a work-around of it? Thanks!

答:
From curl documentation :

The callback function will be passed as much data as possible in all
  invokes, but you must not make any assumptions. It may be one byte, it
  may be thousands. The maximum amount of body data that will be passed
  to the write callback is defined in the curl.h header file:
  CURL_MAX_WRITE_SIZE (the usual default is 16K). If CURLOPT_HEADER is
  enabled, which makes header data get passed to the write callback, you
  can get up to CURL_MAX_HTTP_HEADER bytes of header data passed into
  it. This usually means 100K.

ContentLicense: CC BY-SA 3.0

Body:
I have a question regarding this code at https://curl.haxx.se/libcurl/c/ftpget.html

In the call back function

static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
  struct FtpFile *out=(struct FtpFile *)stream;
  if(out && !out->stream) {
    /* open file for writing */
    out->stream=fopen(out->filename, "wb");
    if(!out->stream)
      return -1; /* failure, can't open file to write */
  }
  return fwrite(buffer, size, nmemb, out->stream);
}

What if the file size exceed the buffer size? I think the function will not be called iteratively since it overwrites the file everytime. Is there a work-around of it? Thanks!


问:
Where does a customer enter coupon code 2checkout?
I want to add coupons on my live site but before I do that I am testing the coupons on my sandbox. I have created coupons in the 2checkout admin area. According to the documentation, a customer enters the coupon code after being redirected to the 2checkout site. However, I only see the pop up but i don't see any area to enter coupon code.What gives?

``` <form class="form-horizontal form" action="<?php echo $action;?>" method="post">

BILLING INFORMATION

                    Country

                        <select id="country" class="form-control" name="country" autocomplete="on" required="">
                            <option value="" class="ng-binding">- Choose Country -</option>
                            <option value="USA">United States</option>
                            <option value="GBR">United Kingdom</option>
                            <option value="CAN">Canada</option>
                            <option value="AUS">Australia</option>
                            <option disabled="" value="—">—</option>
                            <option value="ALA">Åland Islands</option>
                            <option value="AFG">Afghanistan</option>
                            <option value="ALB">Albania</option>
                            <option value="DZA">Algeria</option>
                            <option value="ASM">American Samoa</option>
                            <option value="AND">Andorra</option>
                            <option value="AGO">Angola</option>
                            <option value="AIA">Anguilla</option>
                            <option value="ATA">Antarctica</option>
                            <option value="ATG">Antigua and Barbuda</option>
                            <option value="ARG">Argentina</option>
                            <option value="ARM">Armenia</option>
                            <option value="ABW">Aruba</option>
                            <option value="AUS">Australia</option>
                            <option value="AUT">Austria</option>
                            <option value="AZE">Azerbaijan</option>
                            <option value="BHS">Bahamas</option>
                            <option value="BHR">Bahrain</option>
                            <option value="BGD">Bangladesh</option>
                            <option value="BRB">Barbados</option>
                            <option value="BLR">Belarus</option>
                            <option value="BEL">Belgium</option>
                            <option value="BLZ">Belize</option>
                            <option value="BEN">Benin</option>
                            <option value="BMU">Bermuda</option>
                            <option value="BTN">Bhutan</option>
                            <option value="BOL">Bolivia</option>
                            <option value="BES">Bonaire, Sint Eustatius and Saba</option>
                            <option value="BIH">Bosnia and Herzegovina</option>
                            <option value="BWA">Botswana</option>
                            <option value="BVT">Bouvet Island</option>
                            <option value="BRA">Brazil</option>
                            <option value="IOT">British Indian Ocean Territory</option>
                            <option value="BRN">Brunei Darussalam</option>
                            <option value="BGR">Bulgaria</option>
                            <option value="BFA">Burkina Faso</option>
                            <option value="BDI">Burundi</option>
                            <option value="KHM">Cambodia</option>
                            <option value="CMR">Cameroon</option>
                            <option value="CAN">Canada</option>
                            <option value="CPV">Cape Verde</option>
                            <option value="CYM">Cayman Islands</option>
                            <option value="CAF">Central African Republic</option>
                            <option value="TCD">Chad</option>
                            <option value="CHL">Chile</option>
                            <option value="CHN">China</option>
                            <option value="CXR">Christmas Island</option>
                            <option value="CCK">Cocos (Keeling) Islands</option>
                            <option value="COL">Colombia</option>
                            <option value="COM">Comoros</option>
                            <option value="COG">Congo</option>
                            <option value="COD">Congo, the Democratic Republic of the</option>
                            <option value="COK">Cook Islands</option>
                            <option value="CRI">Costa Rica</option>
                            <option value="CIV">Cote D'ivoire</option>
                            <option value="HRV">Croatia (Hrvatska)</option>
                            <option value="CYP">Cyprus</option>
                            <option value="CZE">Czech Republic</option>
                            <option value="DNK">Denmark</option>
                            <option value="DJI">Djibouti</option>
                            <option value="DMA">Dominica</option>
                            <option value="DOM">Dominican Republic</option>
                            <option value="ECU">Ecuador</option>
                            <option value="EGY">Egypt</option>
                            <option value="SLV">El Salvador</option>
                            <option value="GNQ">Equatorial Guinea</option>
                            <option value="ERI">Eritrea</option>
                            <option value="EST">Estonia</option>
                            <option value="ETH">Ethiopia</option>
                            <option value="FLK">Falkland Islands (Malvinas)</option>
                            <option value="FRO">Faroe Islands</option>
                            <option value="FJI">Fiji</option>
                            <option value="FIN">Finland</option>
                            <option value="FRA">France</option>
                            <option value="FXX">France, Metropolitan</option>
                            <option value="GUF">French Guiana</option>
                            <option value="PYF">French Polynesia</option>
                            <option value="ATF">French Southern Territories</option>
                            <option value="GAB">Gabon</option>
                            <option value="GMB">Gambia</option>
                            <option value="GEO">Georgia</option>
                            <option value="DEU">Germany</option>
                            <option value="GHA">Ghana</option>
                            <option value="GIB">Gibraltar</option>
                            <option value="GRC">Greece</option>
                            <option value="GRL">Greenland</option>
                            <option value="GRD">Grenada</option>
                            <option value="GLP">Guadeloupe</option>
                            <option value="GUM">Guam</option>
                            <option value="GTM">Guatemala</option>
                            <option value="GGY">Guernsey</option>
                            <option value="GIN">Guinea</option>
                            <option value="GNB">Guinea-Bissau</option>
                            <option value="GUY">Guyana</option>
                            <option value="HTI">Haiti</option>
                            <option value="HMD">Heard Island and Mcdonald Islands</option>
                            <option value="HND">Honduras</option>
                            <option value="HKG">Hong Kong</option>
                            <option value="HUN">Hungary</option>
                            <option value="ISL">Iceland</option>
                            <option value="IND">India</option>
                            <option value="IDN">Indonesia</option>
                            <option value="IRQ">Iraq</option>
                            <option value="IRL">Ireland</option>
                            <option value="IMN">Isle of Man</option>
                            <option value="ISR">Israel</option>
                            <option value="ITA">Italy</option>
                            <option value="JAM">Jamaica</option>
                            <option value="JPN">Japan</option>
                            <option value="JEY">Jersey</option>
                            <option value="JOR">Jordan</option>
                            <option value="KAZ">Kazakhstan</option>
                            <option value="KEN">Kenya</option>
                            <option value="KIR">Kiribati</option>
                            <option value="KOR">Korea, Republic of</option>
                            <option value="UNK">UNK</option>
                            <option value="KWT">Kuwait</option>
                            <option value="KGZ">Kyrgyzstan</option>
                            <option value="LAO">Lao People's Democratic Republic</option>
                            <option value="LVA">Latvia</option>
                            <option value="LBN">Lebanon</option>
                            <option value="LSO">Lesotho</option>
                            <option value="LBR">Liberia</option>
                            <option value="LBY">Libyan Arab Jamahiriya</option>
                            <option value="LIE">Liechtenstein</option>
                            <option value="LTU">Lithuania</option>
                            <option value="LUX">Luxembourg</option>
                            <option value="MAC">Macao</option>
                            <option value="MKD">Macedonia</option>
                            <option value="MDG">Madagascar</option>
                            <option value="MWI">Malawi</option>
                            <option value="MYS">Malaysia</option>
                            <option value="MDV">Maldives</option>
                            <option value="MLI">Mali</option>
                            <option value="MLT">Malta</option>
                            <option value="MHL">Marshall Islands</option>
                            <option value="MTQ">Martinique</option>
                            <option value="MRT">Mauritania</option>
                            <option value="MUS">Mauritius</option>
                            <option value="MYT">Mayotte</option>
                            <option value="MEX">Mexico</option>
                            <option value="FSM">Micronesia, Federated States of</option>
                            <option value="MDA">Moldova, Republic of</option>
                            <option value="MCO">Monaco</option>
                            <option value="MNG">Mongolia</option>
                            <option value="MNE">Montenegro</option>
                            <option value="MSR">Montserrat</option>
                            <option value="MAR">Morocco</option>
                            <option value="MOZ">Mozambique</option>
                            <option value="MMR">Myanmar</option>
                            <option value="NAM">Namibia</option>
                            <option value="NRU">Nauru</option>
                            <option value="NPL">Nepal</option>
                            <option value="NLD">Netherlands</option>
                            <option value="ANT">Netherlands Antilles</option>
                            <option value="NCL">New Caledonia</option>
                            <option value="NZL">New Zealand</option>
                            <option value="NIC">Nicaragua</option>
                            <option value="NER">Niger</option>
                            <option value="NGA">Nigeria</option>
                            <option value="NIU">Niue</option>
                            <option value="NFK">Norfolk Island</option>
                            <option value="MNP">Northern Mariana Islands</option>
                            <option value="NOR">Norway</option>
                            <option value="OMN">Oman</option>
                            <option value="PAK">Pakistan</option>
                            <option value="PLW">Palau</option>
                            <option value="PSE">Palestinian Territory, Occupied</option>
                            <option value="PAN">Panama</option>
                            <option value="PNG">Papua New Guinea</option>
                            <option value="PRY">Paraguay</option>
                            <option value="PER">Peru</option>
                            <option value="PHL">Philippines</option>
                            <option value="PCN">Pitcairn</option>
                            <option value="POL">Poland</option>
                            <option value="PRT">Portugal</option>
                            <option value="PRI">Puerto Rico</option>
                            <option value="QAT">Qatar</option>
                            <option value="REU">Reunion</option>
                            <option value="ROU">Romania</option>
                            <option value="RUS">Russian Federation</option>
                            <option value="RWA">Rwanda</option>
                            <option value="SHN">Saint Helena</option>
                            <option value="KNA">Saint Kitts and Nevis</option>
                            <option value="LCA">Saint Lucia</option>
                            <option value="SPM">Saint Pierre and Miquelon</option>
                            <option value="VCT">Saint Vincent and the Grenadines</option>
                            <option value="WSM">Samoa</option>
                            <option value="SMR">San Marino</option>
                            <option value="STP">Sao Tome and Principe</option>
                            <option value="SAU">Saudi Arabia</option>
                            <option value="SEN">Senegal</option>
                            <option value="SRB">Serbia</option>
                            <option value="SCG">Serbia and Montenegro</option>
                            <option value="SYC">Seychelles</option>
                            <option value="SLE">Sierra Leone</option>
                            <option value="SGP">Singapore</option>
                            <option value="SVK">Slovakia</option>
                            <option value="SVN">Slovenia</option>
                            <option value="SLB">Solomon Islands</option>
                            <option value="SOM">Somalia</option>
                            <option value="ZAF">South Africa</option>
                            <option value="SGS">South Georgia and the South Sandwich Islands</option>
                            <option value="ESP">Spain</option>
                            <option value="LKA">Sri Lanka</option>
                            <option value="SUR">Suriname</option>
                            <option value="SJM">Svalbard and Jan Mayen Islands</option>
                            <option value="SWZ">Swaziland</option>
                            <option value="SWE">Sweden</option>
                            <option value="CHE">Switzerland</option>
                            <option value="TWN">Taiwan</option>
                            <option value="TJK">Tajikistan</option>
                            <option value="TZA">Tanzania, United Republic of</option>
                            <option value="THA">Thailand</option>
                            <option value="TLS">Timor-Leste</option>
                            <option value="TGO">Togo</option>
                            <option value="TKL">Tokelau</option>
                            <option value="TON">Tonga</option>
                            <option value="TTO">Trinidad and Tobago</option>
                            <option value="TUN">Tunisia</option>
                            <option value="TUR">Turkey</option>
                            <option value="TKM">Turkmenistan</option>
                            <option value="TCA">Turks and Caicos Islands</option>
                            <option value="TUV">Tuvalu</option>
                            <option value="UGA">Uganda</option>
                            <option value="UKR">Ukraine</option>
                            <option value="ARE">United Arab Emirates</option>
                            <option value="GBR">United Kingdom</option>
                            <option value="USA">United States</option>
                            <option value="UMI">United States Minor Outlying Islands</option>
                            <option value="URY">Uruguay</option>
                            <option value="UZB">Uzbekistan</option>
                            <option value="VUT">Vanuatu</option>
                            <option value="VAT">Vatican City State (Holy See)</option>
                            <option value="VEN">Venezuela</option>
                            <option value="VNM">Viet Nam</option>
                            <option value="VGB">Virgin Islands, British</option>
                            <option value="VIR">Virgin Islands, U.S.</option>
                            <option value="WLF">Wallis and Futuna Islands</option>
                            <option value="ESH">Western Sahara</option>
                            <option value="YEM">Yemen</option>
                            <option value="YUG">Yugoslavia</option>
                            <option value="ZAR">Zaire</option>
                            <option value="ZMB">Zambia</option>
                            <option value="ZWE">Zimbabwe</option>
                        </select>

                    Full Name

                        <input class="form-control" id="card_holder_name" name="card_holder_name" type="text" placeholder="Full Name" required />

                    Address 1

                        <input class="form-control" id="street_address" name="street_address" type="text" placeholder="Address 1" required />

                    Address 2

                        <input class="form-control" id="street_address2" name="street_address2" type="text" placeholder="Address 2"/>

                    City

                        <input class="form-control" id="city" name="city" type="text" placeholder="City" required />

                    State / Province

                        <input class="form-control" id="state" name="state" type="text" placeholder="State/Province" required />

                    Postal Code

                        <input class="form-control" id="zip" name="zip" type="text" placeholder="Postal Code" required />

                    Phone

                        <input class="form-control" id="phone" name="phone" type="text" placeholder="Phone" required />

                    Email

                        <input class="form-control" id="email" name="email" type="text" placeholder="Email" required />

                <input type='hidden' name='sid' value='<?php echo TWOCHECKOUT_SELLER_ID;?>' />
                <input type='hidden' name='mode' value='2CO' />
                <input type='hidden' name='li_0_type' value='product' />
                <input type='hidden' name='li_0_name' value='<?php echo $product_name;?>' />
                <input type='hidden' name='li_0_product_id' value='<?php echo $order_id;?>' />
                <input type='hidden' name='li_0_price' value='<?php echo $total;?>' />

            <input type="submit" class="btn btn-success btn-sm" value="Complete Checkout">

    </form>
```

答: Consider using standard checkout instead. It lets the customer add the coupon code in the review cart step</p>

Body:
I want to add coupons on my live site but before I do that I am testing the coupons on my sandbox. I have created coupons in the 2checkout admin area. According to the documentation, a customer enters the coupon code after being redirected to the 2checkout site. However, I only see the pop up but i don't see any area to enter coupon code.What gives?

 <form class="form-horizontal form" action="<?php echo $action;?>" method="post">

BILLING INFORMATION

                    Country

                        <select id="country" class="form-control" name="country" autocomplete="on" required="">
                            <option value="" class="ng-binding">- Choose Country -</option>
                            <option value="USA">United States</option>
                            <option value="GBR">United Kingdom</option>
                            <option value="CAN">Canada</option>
                            <option value="AUS">Australia</option>
                            <option disabled="" value="—">—</option>
                            <option value="ALA">Åland Islands</option>
                            <option value="AFG">Afghanistan</option>
                            <option value="ALB">Albania</option>
                            <option value="DZA">Algeria</option>
                            <option value="ASM">American Samoa</option>
                            <option value="AND">Andorra</option>
                            <option value="AGO">Angola</option>
                            <option value="AIA">Anguilla</option>
                            <option value="ATA">Antarctica</option>
                            <option value="ATG">Antigua and Barbuda</option>
                            <option value="ARG">Argentina</option>
                            <option value="ARM">Armenia</option>
                            <option value="ABW">Aruba</option>
                            <option value="AUS">Australia</option>
                            <option value="AUT">Austria</option>
                            <option value="AZE">Azerbaijan</option>
                            <option value="BHS">Bahamas</option>
                            <option value="BHR">Bahrain</option>
                            <option value="BGD">Bangladesh</option>
                            <option value="BRB">Barbados</option>
                            <option value="BLR">Belarus</option>
                            <option value="BEL">Belgium</option>
                            <option value="BLZ">Belize</option>
                            <option value="BEN">Benin</option>
                            <option value="BMU">Bermuda</option>
                            <option value="BTN">Bhutan</option>
                            <option value="BOL">Bolivia</option>
                            <option value="BES">Bonaire, Sint Eustatius and Saba</option>
                            <option value="BIH">Bosnia and Herzegovina</option>
                            <option value="BWA">Botswana</option>
                            <option value="BVT">Bouvet Island</option>
                            <option value="BRA">Brazil</option>
                            <option value="IOT">British Indian Ocean Territory</option>
                            <option value="BRN">Brunei Darussalam</option>
                            <option value="BGR">Bulgaria</option>
                            <option value="BFA">Burkina Faso</option>
                            <option value="BDI">Burundi</option>
                            <option value="KHM">Cambodia</option>
                            <option value="CMR">Cameroon</option>
                            <option value="CAN">Canada</option>
                            <option value="CPV">Cape Verde</option>
                            <option value="CYM">Cayman Islands</option>
                            <option value="CAF">Central African Republic</option>
                            <option value="TCD">Chad</option>
                            <option value="CHL">Chile</option>
                            <option value="CHN">China</option>
                            <option value="CXR">Christmas Island</option>
                            <option value="CCK">Cocos (Keeling) Islands</option>
                            <option value="COL">Colombia</option>
                            <option value="COM">Comoros</option>
                            <option value="COG">Congo</option>
                            <option value="COD">Congo, the Democratic Republic of the</option>
                            <option value="COK">Cook Islands</option>
                            <option value="CRI">Costa Rica</option>
                            <option value="CIV">Cote D'ivoire</option>
                            <option value="HRV">Croatia (Hrvatska)</option>
                            <option value="CYP">Cyprus</option>
                            <option value="CZE">Czech Republic</option>
                            <option value="DNK">Denmark</option>
                            <option value="DJI">Djibouti</option>
                            <option value="DMA">Dominica</option>
                            <option value="DOM">Dominican Republic</option>
                            <option value="ECU">Ecuador</option>
                            <option value="EGY">Egypt</option>
                            <option value="SLV">El Salvador</option>
                            <option value="GNQ">Equatorial Guinea</option>
                            <option value="ERI">Eritrea</option>
                            <option value="EST">Estonia</option>
                            <option value="ETH">Ethiopia</option>
                            <option value="FLK">Falkland Islands (Malvinas)</option>
                            <option value="FRO">Faroe Islands</option>
                            <option value="FJI">Fiji</option>
                            <option value="FIN">Finland</option>
                            <option value="FRA">France</option>
                            <option value="FXX">France, Metropolitan</option>
                            <option value="GUF">French Guiana</option>
                            <option value="PYF">French Polynesia</option>
                            <option value="ATF">French Southern Territories</option>
                            <option value="GAB">Gabon</option>
                            <option value="GMB">Gambia</option>
                            <option value="GEO">Georgia</option>
                            <option value="DEU">Germany</option>
                            <option value="GHA">Ghana</option>
                            <option value="GIB">Gibraltar</option>
                            <option value="GRC">Greece</option>
                            <option value="GRL">Greenland</option>
                            <option value="GRD">Grenada</option>
                            <option value="GLP">Guadeloupe</option>
                            <option value="GUM">Guam</option>
                            <option value="GTM">Guatemala</option>
                            <option value="GGY">Guernsey</option>
                            <option value="GIN">Guinea</option>
                            <option value="GNB">Guinea-Bissau</option>
                            <option value="GUY">Guyana</option>
                            <option value="HTI">Haiti</option>
                            <option value="HMD">Heard Island and Mcdonald Islands</option>
                            <option value="HND">Honduras</option>
                            <option value="HKG">Hong Kong</option>
                            <option value="HUN">Hungary</option>
                            <option value="ISL">Iceland</option>
                            <option value="IND">India</option>
                            <option value="IDN">Indonesia</option>
                            <option value="IRQ">Iraq</option>
                            <option value="IRL">Ireland</option>
                            <option value="IMN">Isle of Man</option>
                            <option value="ISR">Israel</option>
                            <option value="ITA">Italy</option>
                            <option value="JAM">Jamaica</option>
                            <option value="JPN">Japan</option>
                            <option value="JEY">Jersey</option>
                            <option value="JOR">Jordan</option>
                            <option value="KAZ">Kazakhstan</option>
                            <option value="KEN">Kenya</option>
                            <option value="KIR">Kiribati</option>
                            <option value="KOR">Korea, Republic of</option>
                            <option value="UNK">UNK</option>
                            <option value="KWT">Kuwait</option>
                            <option value="KGZ">Kyrgyzstan</option>
                            <option value="LAO">Lao People's Democratic Republic</option>
                            <option value="LVA">Latvia</option>
                            <option value="LBN">Lebanon</option>
                            <option value="LSO">Lesotho</option>
                            <option value="LBR">Liberia</option>
                            <option value="LBY">Libyan Arab Jamahiriya</option>
                            <option value="LIE">Liechtenstein</option>
                            <option value="LTU">Lithuania</option>
                            <option value="LUX">Luxembourg</option>
                            <option value="MAC">Macao</option>
                            <option value="MKD">Macedonia</option>
                            <option value="MDG">Madagascar</option>
                            <option value="MWI">Malawi</option>
                            <option value="MYS">Malaysia</option>
                            <option value="MDV">Maldives</option>
                            <option value="MLI">Mali</option>
                            <option value="MLT">Malta</option>
                            <option value="MHL">Marshall Islands</option>
                            <option value="MTQ">Martinique</option>
                            <option value="MRT">Mauritania</option>
                            <option value="MUS">Mauritius</option>
                            <option value="MYT">Mayotte</option>
                            <option value="MEX">Mexico</option>
                            <option value="FSM">Micronesia, Federated States of</option>
                            <option value="MDA">Moldova, Republic of</option>
                            <option value="MCO">Monaco</option>
                            <option value="MNG">Mongolia</option>
                            <option value="MNE">Montenegro</option>
                            <option value="MSR">Montserrat</option>
                            <option value="MAR">Morocco</option>
                            <option value="MOZ">Mozambique</option>
                            <option value="MMR">Myanmar</option>
                            <option value="NAM">Namibia</option>
                            <option value="NRU">Nauru</option>
                            <option value="NPL">Nepal</option>
                            <option value="NLD">Netherlands</option>
                            <option value="ANT">Netherlands Antilles</option>
                            <option value="NCL">New Caledonia</option>
                            <option value="NZL">New Zealand</option>
                            <option value="NIC">Nicaragua</option>
                            <option value="NER">Niger</option>
                            <option value="NGA">Nigeria</option>
                            <option value="NIU">Niue</option>
                            <option value="NFK">Norfolk Island</option>
                            <option value="MNP">Northern Mariana Islands</option>
                            <option value="NOR">Norway</option>
                            <option value="OMN">Oman</option>
                            <option value="PAK">Pakistan</option>
                            <option value="PLW">Palau</option>
                            <option value="PSE">Palestinian Territory, Occupied</option>
                            <option value="PAN">Panama</option>
                            <option value="PNG">Papua New Guinea</option>
                            <option value="PRY">Paraguay</option>
                            <option value="PER">Peru</option>
                            <option value="PHL">Philippines</option>
                            <option value="PCN">Pitcairn</option>
                            <option value="POL">Poland</option>
                            <option value="PRT">Portugal</option>
                            <option value="PRI">Puerto Rico</option>
                            <option value="QAT">Qatar</option>
                            <option value="REU">Reunion</option>
                            <option value="ROU">Romania</option>
                            <option value="RUS">Russian Federation</option>
                            <option value="RWA">Rwanda</option>
                            <option value="SHN">Saint Helena</option>
                            <option value="KNA">Saint Kitts and Nevis</option>
                            <option value="LCA">Saint Lucia</option>
                            <option value="SPM">Saint Pierre and Miquelon</option>
                            <option value="VCT">Saint Vincent and the Grenadines</option>
                            <option value="WSM">Samoa</option>
                            <option value="SMR">San Marino</option>
                            <option value="STP">Sao Tome and Principe</option>
                            <option value="SAU">Saudi Arabia</option>
                            <option value="SEN">Senegal</option>
                            <option value="SRB">Serbia</option>
                            <option value="SCG">Serbia and Montenegro</option>
                            <option value="SYC">Seychelles</option>
                            <option value="SLE">Sierra Leone</option>
                            <option value="SGP">Singapore</option>
                            <option value="SVK">Slovakia</option>
                            <option value="SVN">Slovenia</option>
                            <option value="SLB">Solomon Islands</option>
                            <option value="SOM">Somalia</option>
                            <option value="ZAF">South Africa</option>
                            <option value="SGS">South Georgia and the South Sandwich Islands</option>
                            <option value="ESP">Spain</option>
                            <option value="LKA">Sri Lanka</option>
                            <option value="SUR">Suriname</option>
                            <option value="SJM">Svalbard and Jan Mayen Islands</option>
                            <option value="SWZ">Swaziland</option>
                            <option value="SWE">Sweden</option>
                            <option value="CHE">Switzerland</option>
                            <option value="TWN">Taiwan</option>
                            <option value="TJK">Tajikistan</option>
                            <option value="TZA">Tanzania, United Republic of</option>
                            <option value="THA">Thailand</option>
                            <option value="TLS">Timor-Leste</option>
                            <option value="TGO">Togo</option>
                            <option value="TKL">Tokelau</option>
                            <option value="TON">Tonga</option>
                            <option value="TTO">Trinidad and Tobago</option>
                            <option value="TUN">Tunisia</option>
                            <option value="TUR">Turkey</option>
                            <option value="TKM">Turkmenistan</option>
                            <option value="TCA">Turks and Caicos Islands</option>
                            <option value="TUV">Tuvalu</option>
                            <option value="UGA">Uganda</option>
                            <option value="UKR">Ukraine</option>
                            <option value="ARE">United Arab Emirates</option>
                            <option value="GBR">United Kingdom</option>
                            <option value="USA">United States</option>
                            <option value="UMI">United States Minor Outlying Islands</option>
                            <option value="URY">Uruguay</option>
                            <option value="UZB">Uzbekistan</option>
                            <option value="VUT">Vanuatu</option>
                            <option value="VAT">Vatican City State (Holy See)</option>
                            <option value="VEN">Venezuela</option>
                            <option value="VNM">Viet Nam</option>
                            <option value="VGB">Virgin Islands, British</option>
                            <option value="VIR">Virgin Islands, U.S.</option>
                            <option value="WLF">Wallis and Futuna Islands</option>
                            <option value="ESH">Western Sahara</option>
                            <option value="YEM">Yemen</option>
                            <option value="YUG">Yugoslavia</option>
                            <option value="ZAR">Zaire</option>
                            <option value="ZMB">Zambia</option>
                            <option value="ZWE">Zimbabwe</option>
                        </select>

                    Full Name

                        <input class="form-control" id="card_holder_name" name="card_holder_name" type="text" placeholder="Full Name" required />

                    Address 1

                        <input class="form-control" id="street_address" name="street_address" type="text" placeholder="Address 1" required />

                    Address 2

                        <input class="form-control" id="street_address2" name="street_address2" type="text" placeholder="Address 2"/>

                    City

                        <input class="form-control" id="city" name="city" type="text" placeholder="City" required />

                    State / Province

                        <input class="form-control" id="state" name="state" type="text" placeholder="State/Province" required />

                    Postal Code

                        <input class="form-control" id="zip" name="zip" type="text" placeholder="Postal Code" required />

                    Phone

                        <input class="form-control" id="phone" name="phone" type="text" placeholder="Phone" required />

                    Email

                        <input class="form-control" id="email" name="email" type="text" placeholder="Email" required />

                <input type='hidden' name='sid' value='<?php echo TWOCHECKOUT_SELLER_ID;?>' />
                <input type='hidden' name='mode' value='2CO' />
                <input type='hidden' name='li_0_type' value='product' />
                <input type='hidden' name='li_0_name' value='<?php echo $product_name;?>' />
                <input type='hidden' name='li_0_product_id' value='<?php echo $order_id;?>' />
                <input type='hidden' name='li_0_price' value='<?php echo $total;?>' />

            <input type="submit" class="btn btn-success btn-sm" value="Complete Checkout">

    </form>


问:
Why do Travis CI download everything each time it builds?
I found out that each time Travis CI build the project, it has to download again all the SDK packages like the platform-tools, the support library, the current SDK, etc.

Is it possible to avoid it and make Travis reuse what it downloaded the first time ?

I probably made some mistakes in my .travis.yml file, here is a copy of it

```<code>language: android
android:
  components:
    # Uncomment the lines below if you want to
    # use the latest revision of Android SDK Tools
    - platform-tools
    - tools

    # The BuildTools version used by your project
    - build-tools-23.0.2

    # The SDK version used to compile your project
    - android-23

    # Additional components
    - extra-android-support
    - extra-google-google_play_services
    - extra-google-m2repository
    - extra-android-m2repository
    - addon-google_apis-google-19

    # Specify at least one system image,
    # if you need to run emulator(s) during your tests
    # - sys-img-armeabi-v7a-android-19
    # - sys-img-x86-android-17

script:
  - ./gradlew check
  - ./gradlew test --continue
  # - ./gradlew build connectedCheck
</code>```

答:
Why do Travis CI download everything each time it builds?

We talk about this here, Travis-ci downloads the cache from S3, so there is not a significant speed improvement caching big files like Android SDK.

How to include Android SDK in Travis-ci cache? (not recommended)

The relevant bits are here, you can add to the cache any file you like and know his path:

```<code>cache:
  directories:
    - ${TRAVIS_BUILD_DIR}/gradle/caches/
    - ${TRAVIS_BUILD_DIR}/gradle/wrapper/dists/
    - ${TRAVIS_BUILD_DIR}/android-sdk/extras/ # please don't include sys-images
</code>```

I did it time ago, you can see the code in the link shared by @nicolas-f:

```<code>language: android
jdk: oraclejdk8
env:
  global:
    - GRADLE_USER_HOME=${TRAVIS_BUILD_DIR}/gradle
    - ANDROID_HOME=${TRAVIS_BUILD_DIR}/android-sdk
    - SDK=${TRAVIS_BUILD_DIR}/android-sdk
    - PATH=${GRADLE_USER_HOME}/bin/:${SDK}/:${SDK}/tools/:${SDK}/platform-tools/:${PATH}
before_install:
  - export OLD_SDK=/usr/local/android-sdk-24.0.2;
                                           mkdir -p ${SDK};
                                           cp -u -R ${OLD_SDK}/platforms ${SDK}/platforms;
                                           cp -u -R ${OLD_SDK}/system-images ${SDK}/system-images;
                                           cp -u -R ${OLD_SDK}/tools ${SDK}/tools

cache:
  apt: true
  directories:
    - ${TRAVIS_BUILD_DIR}/gradle/caches/
    - ${TRAVIS_BUILD_DIR}/gradle/wrapper/dists/
    - ${TRAVIS_BUILD_DIR}/android-sdk/extras/
android:
  components:
     # Update Android SDK Tools
    - tools
    - platform-tools
    - build-tools-23.0.2
    - android-23
    - add-on
    - extra

script:
   - ./gradlew check
</code>```

Use ls to confirm that the SDK path has not changed another time.

It's not currently necessary to move the SDK, and you need to update other things, perhaps add another tools after platform-tools, this code is outdated.

Body:
I found out that each time Travis CI build the project, it has to download again all the SDK packages like the platform-tools, the support library, the current SDK, etc.

Is it possible to avoid it and make Travis reuse what it downloaded the first time ?

I probably made some mistakes in my .travis.yml file, here is a copy of it

language: android
android:
  components:
    # Uncomment the lines below if you want to
    # use the latest revision of Android SDK Tools
    - platform-tools
    - tools

    # The BuildTools version used by your project
    - build-tools-23.0.2

    # The SDK version used to compile your project
    - android-23

    # Additional components
    - extra-android-support
    - extra-google-google_play_services
    - extra-google-m2repository
    - extra-android-m2repository
    - addon-google_apis-google-19

    # Specify at least one system image,
    # if you need to run emulator(s) during your tests
    # - sys-img-armeabi-v7a-android-19
    # - sys-img-x86-android-17

script:
  - ./gradlew check
  - ./gradlew test --continue
  # - ./gradlew build connectedCheck

Body:
Why do Travis CI download everything each time it builds?

We talk about this here, Travis-ci downloads the cache from S3, so there is not a significant speed improvement caching big files like Android SDK.

How to include Android SDK in Travis-ci cache? (not recommended)

The relevant bits are here, you can add to the cache any file you like and know his path:

cache:
  directories:
    - ${TRAVIS_BUILD_DIR}/gradle/caches/
    - ${TRAVIS_BUILD_DIR}/gradle/wrapper/dists/
    - ${TRAVIS_BUILD_DIR}/android-sdk/extras/ # please don't include sys-images

I did it time ago, you can see the code in the link shared by @nicolas-f:

language: android
jdk: oraclejdk8
env:
  global:
    - GRADLE_USER_HOME=${TRAVIS_BUILD_DIR}/gradle
    - ANDROID_HOME=${TRAVIS_BUILD_DIR}/android-sdk
    - SDK=${TRAVIS_BUILD_DIR}/android-sdk
    - PATH=${GRADLE_USER_HOME}/bin/:${SDK}/:${SDK}/tools/:${SDK}/platform-tools/:${PATH}
before_install:
  - export OLD_SDK=/usr/local/android-sdk-24.0.2;
                                           mkdir -p ${SDK};
                                           cp -u -R ${OLD_SDK}/platforms ${SDK}/platforms;
                                           cp -u -R ${OLD_SDK}/system-images ${SDK}/system-images;
                                           cp -u -R ${OLD_SDK}/tools ${SDK}/tools

cache:
  apt: true
  directories:
    - ${TRAVIS_BUILD_DIR}/gradle/caches/
    - ${TRAVIS_BUILD_DIR}/gradle/wrapper/dists/
    - ${TRAVIS_BUILD_DIR}/android-sdk/extras/
android:
  components:
     # Update Android SDK Tools
    - tools
    - platform-tools
    - build-tools-23.0.2
    - android-23
    - add-on
    - extra

script:
   - ./gradlew check

Use ls to confirm that the SDK path has not changed another time.

It's not currently necessary to move the SDK, and you need to update other things, perhaps add another tools after platform-tools, this code is outdated.


问:
jquery menu onclick minus width from nav
how do i get the minus navWidth working?!

here is my jquery script

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

    //------------------menu-----------

    var navWidth = $("nav").css("width");

    $("#menu_btn").click(function () {
        $(".primary").css({
            "right": "0px",
        })
        $(".lightbox").show();
    });

    $("#menu_close_btn").click(function () {
        $(".primary").css({
            "right": -navWidth + "px",
        })
        $(".lightbox").hide()
    });

    $(".lightbox").click(function () {
        $(".primary").css({
            "right": -navWidth + "px",
        })
        $(this).hide();
    });

    $("nav ul li a").click(function() {
        $(".primary").css({
            "right": -navWidth + "px",
        })
    })

    $('a[href^="#"]').click(function () {

        $('html,body').animate({
            scrollTop: $(this.hash).offset().top
        }, 300);

        return false;

        e.preventDefault();

    });

    //------------------end menu-----------

    });
</code>```

here is my html:

```<code>    <section class="header" id="header">
        <header>
            <i class="fa fa-bars" id="menu_btn" aria-hidden="true"></i>
        </header>

        <nav class="primary">
            <i class="fa fa-times" id="menu_close_btn" aria-hidden="true"></i>
            <ul>
                <li><a href="#header">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#my_work">My Work</a></li>
            </ul>
        </nav>
</code>```

here is my css:

```<code>    header #menu_btn {
        font-size: 35px;
    margin: 0px 2%;
    line-height: 45px;
    }

nav {
    position: fixed;
    height: 100vh;
    width: 350px;
    right: -350px;
    top: 0;
    z-index: 150;
    background-color: #383838;
    transition: all 0.5s;
}

nav i {
    position: absolute;
    top: 3%;
    right: 7%;
    color: white;
}

nav ul {
    position: relative;
    float: left;
    top: 50%;
    left: 50%;
    transform: translate(-104.9%, -50%);
    list-style-type: none;
    text-align: left;
    line-height: 55px;
}

nav ul l i {}

nav ul li a {
    font-size: 16px;
    color: #c4c4c4;
    text-decoration: none;
}

nav ul li a:hover {
    color: #fff;
}
</code>```

sdasodhusandjisadiandjskakjdnasjkdnasjkdnjaksndjksandjkankjsdnasjkdjkadsanjdkas ndjksandjksandkjsa ncsjand jksandjk  ndjkasn dkjsanjk  ndjkasn kdsa

答:
I modified:

```<code>"right": -$("nav").width() + "px",
</code>```

$(document).ready(function () {

    //------------------menu-----------

    $("#menu_btn").click(function () {
        $(".primary").css({
            "right": "0px",
        })
        $(".lightbox").show();
    });

    $("#menu_close_btn").click(function () {
        $(".primary").css({
            "right": -$("nav").width() + "px",
        })
        $(".lightbox").hide()
    });

    $(".lightbox").click(function () {
        $(".primary").css({
            "right": -navWidth + "px",
        })
        $(this).hide();
    });

    $("nav ul li a").click(function() {
        $(".primary").css({
            "right": -navWidth + "px",
        })
    })

    $('a[href^="#"]').click(function () {

        $('html,body').animate({
            scrollTop: $(this.hash).offset().top
        }, 300);

        return false;

        e.preventDefault();

    });

    //------------------end menu-----------

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>header #menu_btn {
        font-size: 35px;
    margin: 0px 2%;
    line-height: 45px;
    }

nav {
    position: fixed;
    height: 100vh;
    width: 350px;
    right: -350px;
    top: 0;
    z-index: 150;
    background-color: #383838;
    transition: all 0.5s;
}

nav i {
    position: absolute;
    top: 3%;
    right: 7%;
    color: white;
}

nav ul {
    position: relative;
    float: left;
    top: 50%;
    left: 50%;
    transform: translate(-104.9%, -50%);
    list-style-type: none;
    text-align: left;
    line-height: 55px;
}

nav ul l i {}

nav ul li a {
    font-size: 16px;
    color: #c4c4c4;
    text-decoration: none;
}

nav ul li a:hover {
    color: #fff;
}</code>```

<link rel="stylesheet" href="https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css" integrity="sha384-dNpIIXE8U05kAbPhy3G1cz+yZmTzA6CY8Vg/u2L9xRnHjJiAK76m2BIEaSEV+/aU" crossorigin="anonymous">

Home

About

My Work

```

Body:
how do i get the minus navWidth working?!

here is my jquery script

    $(document).ready(function () {

    //------------------menu-----------

    var navWidth = $("nav").css("width");

    $("#menu_btn").click(function () {
        $(".primary").css({
            "right": "0px",
        })
        $(".lightbox").show();
    });

    $("#menu_close_btn").click(function () {
        $(".primary").css({
            "right": -navWidth + "px",
        })
        $(".lightbox").hide()
    });

    $(".lightbox").click(function () {
        $(".primary").css({
            "right": -navWidth + "px",
        })
        $(this).hide();
    });

    $("nav ul li a").click(function() {
        $(".primary").css({
            "right": -navWidth + "px",
        })
    })

    $('a[href^="#"]').click(function () {

        $('html,body').animate({
            scrollTop: $(this.hash).offset().top
        }, 300);

        return false;

        e.preventDefault();

    });

    //------------------end menu-----------

    });

here is my html:

Home

About

My Work

here is my css:

    header #menu_btn {
        font-size: 35px;
    margin: 0px 2%;
    line-height: 45px;
    }

nav {
    position: fixed;
    height: 100vh;
    width: 350px;
    right: -350px;
    top: 0;
    z-index: 150;
    background-color: #383838;
    transition: all 0.5s;
}

nav i {
    position: absolute;
    top: 3%;
    right: 7%;
    color: white;
}

nav ul {
    position: relative;
    float: left;
    top: 50%;
    left: 50%;
    transform: translate(-104.9%, -50%);
    list-style-type: none;
    text-align: left;
    line-height: 55px;
}

nav ul l i {}

nav ul li a {
    font-size: 16px;
    color: #c4c4c4;
    text-decoration: none;
}

nav ul li a:hover {
    color: #fff;
}

sdasodhusandjisadiandjskakjdnasjkdnasjkdnjaksndjksandjkankjsdnasjkdjkadsanjdkas ndjksandjksandkjsa ncsjand jksandjk  ndjkasn dkjsanjk  ndjkasn kdsa

Body:
I modified:

"right": -$("nav").width() + "px",

$(document).ready(function () {

    //------------------menu-----------

    $("#menu_btn").click(function () {
        $(".primary").css({
            "right": "0px",
        })
        $(".lightbox").show();
    });

    $("#menu_close_btn").click(function () {
        $(".primary").css({
            "right": -$("nav").width() + "px",
        })
        $(".lightbox").hide()
    });

    $(".lightbox").click(function () {
        $(".primary").css({
            "right": -navWidth + "px",
        })
        $(this).hide();
    });

    $("nav ul li a").click(function() {
        $(".primary").css({
            "right": -navWidth + "px",
        })
    })

    $('a[href^="#"]').click(function () {

        $('html,body').animate({
            scrollTop: $(this.hash).offset().top
        }, 300);

        return false;

        e.preventDefault();

    });

    //------------------end menu-----------

    });

header #menu_btn {
        font-size: 35px;
    margin: 0px 2%;
    line-height: 45px;
    }

nav {
    position: fixed;
    height: 100vh;
    width: 350px;
    right: -350px;
    top: 0;
    z-index: 150;
    background-color: #383838;
    transition: all 0.5s;
}

nav i {
    position: absolute;
    top: 3%;
    right: 7%;
    color: white;
}

nav ul {
    position: relative;
    float: left;
    top: 50%;
    left: 50%;
    transform: translate(-104.9%, -50%);
    list-style-type: none;
    text-align: left;
    line-height: 55px;
}

nav ul l i {}

nav ul li a {
    font-size: 16px;
    color: #c4c4c4;
    text-decoration: none;
}

nav ul li a:hover {
    color: #fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css" integrity="sha384-dNpIIXE8U05kAbPhy3G1cz+yZmTzA6CY8Vg/u2L9xRnHjJiAK76m2BIEaSEV+/aU" crossorigin="anonymous">
<section class="header" id="header">
        <header>
            <i class="fa fa-bars" id="menu_btn" aria-hidden="true"></i>
        </header>

        <nav class="primary">
            <i class="fa fa-times" id="menu_close_btn" aria-hidden="true"></i>
            <ul>
                <li><a href="#header">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#my_work">My Work</a></li>
            </ul>
        </nav>
</section>


问:
Configure eclipse so that backspace unindents
Having eclipse configured to use space instead of tabs, is it possible to configure eclipse so that the backspace key unindents like the tab key indents?

A demonstration to clarify what I mean with backspace unindent (the vertical bar stands for cursor position and the dots for spaces):

```<code>if(bar == 0) {
|foo = 0;
}
</code>```

Pressing tab will indent 4 spaces:

```<code>if(bar == 0) {
....|foo = 0;
}
</code>```

Pressing backspace only goes back 1 space:

```<code>if(bar == 0) {
...|foo = 0;
}
</code>```

What I want is that it goes back 4 spaces:

```<code>if(bar == 0) {
|foo = 0;
}
</code>```

答:
Hard way: set Eclipse to format indention using the tab character. Then backspace will remove the tab char

Easy way: start using the formatting feature of Eclipse to fix the formatting.  Ctrl-Shift-F will format the selected lines or the whole file if there is nothing selected, using the formatting rules you configure.

Alternative: select the lines of text you want unindented and use shift-tab, it will unindent the selected lines.

Body:
Having eclipse configured to use space instead of tabs, is it possible to configure eclipse so that the backspace key unindents like the tab key indents?

A demonstration to clarify what I mean with backspace unindent (the vertical bar stands for cursor position and the dots for spaces):

if(bar == 0) {
|foo = 0;
}

Pressing tab will indent 4 spaces:

if(bar == 0) {
....|foo = 0;
}

Pressing backspace only goes back 1 space:

if(bar == 0) {
...|foo = 0;
}

What I want is that it goes back 4 spaces:

if(bar == 0) {
|foo = 0;
}

ContentLicense: CC BY-SA 2.5


问:
Spring boot interceptor return JSON
I Have a spring boot application that is a REST Webservice.

I want to add an interceptor so that each role who doesn't have a permission for a specific action is returned with a 401 error code.

```<code>    @Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

    logger.info("Request URL::" + httpServletRequest.getRequestURL().toString()
            + ":: Start Time=" + System.currentTimeMillis());

    UsernamePasswordAuthenticationToken token  = (UsernamePasswordAuthenticationToken) httpServletRequest.getUserPrincipal();
    String roleStr =  token.getAuthorities().iterator().next().getAuthority();
    String action = httpServletRequest.getServletPath();

    Role role = roleRepository.findOne(Long.parseLong(roleStr));

    if (role.getActions().contains(action)) {
        return true;
    }

    httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return false;
}
</code>```

The problem is that the response is always returning HTML, how to make the response return as JSON like the controllers annotated with @RestController ?

Thanks

答:
```<code>package com.sha.home;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sha.model.Message;

public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter{

    private static final Logger logger = Logger.getLogger(ExecuteTimeInterceptor.class);

    //before the actual handler will be executed
    public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler)
        throws Exception {

        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
  System.out.println("start time"+startTime);

  ObjectMapper mapper = new ObjectMapper();
  Message msg = new Message("invalid","userinvalid");// customised pojo for error json message
  response.setContentType("application/json");
  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  response.getWriter().write(mapper.writeValueAsString(msg));

  return false;

    }

    //after the handler is executed
    public void postHandle(
        HttpServletRequest request, HttpServletResponse response,
        Object handler, ModelAndView modelAndView)
        throws Exception {

        long startTime = (Long)request.getAttribute("startTime");

        long endTime = System.currentTimeMillis();

        long executeTime = endTime - startTime;

        //modified the exisitng modelAndView

        //log it
        if(logger.isDebugEnabled()){
           logger.debug("[" + handler + "] executeTime : " + executeTime + "ms");
        }
    }
}

    enter code here
</code>```

Title: Spring boot interceptor return JSON

Body:
I Have a spring boot application that is a REST Webservice.

I want to add an interceptor so that each role who doesn't have a permission for a specific action is returned with a 401 error code.

    @Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

    logger.info("Request URL::" + httpServletRequest.getRequestURL().toString()
            + ":: Start Time=" + System.currentTimeMillis());

    UsernamePasswordAuthenticationToken token  = (UsernamePasswordAuthenticationToken) httpServletRequest.getUserPrincipal();
    String roleStr =  token.getAuthorities().iterator().next().getAuthority();
    String action = httpServletRequest.getServletPath();

    Role role = roleRepository.findOne(Long.parseLong(roleStr));

    if (role.getActions().contains(action)) {
        return true;
    }

    httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return false;
}

The problem is that the response is always returning HTML, how to make the response return as JSON like the controllers annotated with @RestController ?

Thanks


问:
Create a matrix from a vector such that its height and width are powers of multiples in matlab
I have tried multiple solutions in matlab to convert a vector for example

```<code>A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
</code>```

into

```<code>B= [ 1  2  3  4 ]
     5  6  7  8
     9  10 11 12
     13 14 15 16
     17  0  0  0
      0  0  0  0
      0  0  0  0
      0  0  0  0
</code>```

Here the desired matrix is 8x4 or rather the height or width is any multiple of 4. This would mean the nearest greater multiple of 4 if we keep any one dimension(height or width) fixed for fitting all elements and padding the extra elements with zeroes. I have tried reshape like so

```<code>reshape([c(:) ; zeros(rem(nc - rem(numel(c),nc),nc),1)],nc,[])
</code>```

Here c is the original vector or matrix, nc is the number of columns.

It simply changes the number of rows and cols but does not take into account the possible powers required by the condition for height and width. I don't have the Communications Toolbox which has the vec2mat function.
Another possible alternative thought is to initialize a matrix with all zeroes and then assign. But at this point I'm stuck. So please help me matlab experts.

Body:
I have tried multiple solutions in matlab to convert a vector for example

A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]

into

B= [ 1  2  3  4 ]
     5  6  7  8
     9  10 11 12
     13 14 15 16
     17  0  0  0
      0  0  0  0
      0  0  0  0
      0  0  0  0

Here the desired matrix is 8x4 or rather the height or width is any multiple of 4. This would mean the nearest greater multiple of 4 if we keep any one dimension(height or width) fixed for fitting all elements and padding the extra elements with zeroes. I have tried reshape like so

reshape([c(:) ; zeros(rem(nc - rem(numel(c),nc),nc),1)],nc,[])

Here c is the original vector or matrix, nc is the number of columns.

It simply changes the number of rows and cols but does not take into account the possible powers required by the condition for height and width. I don't have the Communications Toolbox which has the vec2mat function.
Another possible alternative thought is to initialize a matrix with all zeroes and then assign. But at this point I'm stuck. So please help me matlab experts.

Body:
i think this what you mean:

n = 4;
A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
B = zeros(n,ceil(numel(A)/n^2)*n);
B(1:numel(A)) = A;
B = B'

B = [ 1  2  3  4
     5  6  7  8
     9  10 11 12
     13 14 15 16
     17  0  0  0
      0  0  0  0
      0  0  0  0
      0  0  0  0]


问:
C programming--why gets() not taking input?
```<code>#include<stdio.h>
int main()
{
   int choice;
   char sl[10];
   char phn[10];
   printf("Enter choice: ");
   scanf("%d",&choice);
   switch(choice)
   {
   case 1:
       printf("\nEnter Student Details: \n\n");
       printf("\nEnter serial number: ");
       gets(sl);
       printf("Roll number: ");
       gets(phn);
   default:
      break;
   }
   return 0;
}
</code>```

C PROGRAMMING:

I used 2 gets() function here. second one is working but first one is not working. why?? how to make it work?

N.B: I want to take "sl" and "phn" variable as char type and I want to use gets() to take input.
please someone help....

答:
Use fgets for all input. scanf usually leaves a newline in the input stream that will cause problems for fgets. Parse the input for an integer with sscanf and check the return to make sure an integer was input.</p>

```<code>#include  <stdio.h>
int main()
{
    int choice;
    int result = 0;
    char sl[10];
    char phn[10];
    char input[256];
    do {
        printf("Enter choice: ");
        if ( ( fgets ( input, sizeof input, stdin))) {
            result = sscanf( input, "%d", &choice);
            if ( result == 0) {
                printf ( "try again\n");
            }
        }
        else {
            fprintf ( stderr, "problem getting input\n");
            return 1;
        }
    } while ( result != 1);
    switch(choice)
    {
        case 1:
            printf("\nEnter Student Details: \n\n");
            printf("\nEnter serial number: ");
            if ( ( fgets ( sl, sizeof sl, stdin)) == NULL) {
                fprintf ( stderr, "problem getting serial number\n");
                return 1;
            }
            printf("Roll number: ");
            if ( ( fgets ( phn, sizeof phn, stdin)) == NULL) {
                fprintf ( stderr, "problem getting roll number\n");
                return 1;
            }
            break;
        default:
            break;
    }
    return 0;
}
</code>```

Body:
#include<stdio.h>
int main()
{
   int choice;
   char sl[10];
   char phn[10];
   printf("Enter choice: ");
   scanf("%d",&choice);
   switch(choice)
   {
   case 1:
       printf("\nEnter Student Details: \n\n");
       printf("\nEnter serial number: ");
       gets(sl);
       printf("Roll number: ");
       gets(phn);
   default:
      break;
   }
   return 0;
}

C PROGRAMMING:

I used 2 gets() function here. second one is working but first one is not working. why?? how to make it work?

N.B: I want to take "sl" and "phn" variable as char type and I want to use gets() to take input.
please someone help....

Body:
Use fgets for all input. scanf usually leaves a newline in the input stream that will cause problems for fgets. Parse the input for an integer with sscanf and check the return to make sure an integer was input.

#include  <stdio.h>
int main()
{
    int choice;
    int result = 0;
    char sl[10];
    char phn[10];
    char input[256];
    do {
        printf("Enter choice: ");
        if ( ( fgets ( input, sizeof input, stdin))) {
            result = sscanf( input, "%d", &choice);
            if ( result == 0) {
                printf ( "try again\n");
            }
        }
        else {
            fprintf ( stderr, "problem getting input\n");
            return 1;
        }
    } while ( result != 1);
    switch(choice)
    {
        case 1:
            printf("\nEnter Student Details: \n\n");
            printf("\nEnter serial number: ");
            if ( ( fgets ( sl, sizeof sl, stdin)) == NULL) {
                fprintf ( stderr, "problem getting serial number\n");
                return 1;
            }
            printf("Roll number: ");
            if ( ( fgets ( phn, sizeof phn, stdin)) == NULL) {
                fprintf ( stderr, "problem getting roll number\n");
                return 1;
            }
            break;
        default:
            break;
    }
    return 0;
}


问:
MVVM: Where to Place Methods used by Most ViewModels?
I have a few ViewModels which run a process from a simple string parameter. I want them to all use the same method to do it so as to not repeat code.

I was thinking about putting this method in ViewModelBase, however wouldn't that replicate the code anyway?

答:
I was thinking about putting this method in ViewModelBase, however wouldn't that replicate the code anyway?

No. How could defining a method in one single base class lead to code duplication?

If you have a method that may be used by all (or nearly all) of your view models and you also have a common base class that all view models inherit from, defining the common method in the base class sounds like a good idea. This is the main purpose of using a common base class in the first place.


问:
How can i use javascript to split a domain name into two variables on a form before posting?
I have a an input box on my homepage which i want users to input their domain to search for .
E.G.

test.com

or

test.gb.com

etc and i would like it to on submission ( post ) to extract the everything upto the first "." into a variable $domain and everything after the first including "." into $ext

So $domain might now contain "test" and $ext would contain ".gb.com" When the form was posted.

Possible ?

Here is the code for my form so far . What i need is to have everything that is inputted upto the first "." stored in the name="domain" form variable and everything in this line

i.e from the $ext variable stored for the form submission

Code so far :

```<code><form method="post" action="https://www.jms-networks.net/domainchecker.php">
<span class="text"><input value="{php} print $_POST['sld'] ? $_POST['sld'] : 'Search for your domain name'; {/php}" type="text" name="domain" class="searchbox" onfocus="if (this.value == this.defaultValue) this.value = '';" onblur="if (this.value == '') this.value = this.defaultValue;" /></span>
<input type="hidden" name="direct" value="true" />
<!-- This one below should contain the $ext value everythign after including the first "." -->
<input type="hidden" name="tlds[]" value="what goes here???" />
<input type="hidden" name="tlds[]" value=".me.uk" />
<input type="hidden" name="tlds[]" value=".org.uk" />
<input type="hidden" name="tlds[]" value=".com" />
<input type="hidden" name="tlds[]" value=".net" />
<input type="hidden" name="tlds[]" value=".org" />

<input type="submit" value="Go" class="product-headers" />
</form>
</code>```

答:
```<code>var i = $thewhole.indexOf('.');
var $domain = $thewhole.substr(0, i);
var $ext = $thewhole.substr(i);
</code>```

Or with regexp

```<code>var regexp = /([^.]+)(\..*)/;
var match = regexp.exec($thewhole);
var $domain = match[1];
var $ext = match[2];
</code>```

Edit:

```<code><script type="text/javascript">

    function submithelper() {

      // this is why we need the id="xxx" below.
      var $domainInput = document.getElementById("domain");
      var $extInput = document.getElementById("ext");

      var $domain = $domainInput.value;
      var $i = $domain.indexOf('.');
      var $host = $domain.substr(0, $i); // perhaps skip to do this if it isn't used?
      var $ext = $domain.substr($i);

      $extInput.value = $ext;

      return true; // false to stop form from submitting.
    }

</script>

<form onsubmit="return submithelper()" method="post" action="https://www.jms-networks.net/domainchecker.php">

  <!-- Two inputs has been given IDs so we can easily get them from javascript. -->

  <span class="text"><input id="domain" value="{php} print $_POST['sld'] ? $_POST['sld'] : 'Search for your domain name'; {/php}" type="text" name="domain" class="searchbox" onfocus="if (this.value == this.defaultValue) this.value = '';" onblur="if (this.value == '') this.value = this.defaultValue;" /></span>
  <input type="hidden" name="direct" value="true" />
  <input id="ext" type="hidden" name="tlds[]" value="" />
  ...
</code>```

Body:
I have a an input box on my homepage which i want users to input their domain to search for .
E.G.

test.com

or

test.gb.com

etc and i would like it to on submission ( post ) to extract the everything upto the first "." into a variable $domain and everything after the first including "." into $ext

So $domain might now contain "test" and $ext would contain ".gb.com" When the form was posted.

Possible ?

Here is the code for my form so far . What i need is to have everything that is inputted upto the first "." stored in the name="domain" form variable and everything in this line

i.e from the $ext variable stored for the form submission

Code so far :

<form method="post" action="https://www.jms-networks.net/domainchecker.php">
<input value="{php} print $_POST['sld'] ? $_POST['sld'] : 'Search for your domain name'; {/php}" type="text" name="domain" class="searchbox" onfocus="if (this.value == this.defaultValue) this.value = '';" onblur="if (this.value == '') this.value = this.defaultValue;" />
<input type="hidden" name="direct" value="true" />

<input type="hidden" name="tlds[]" value="what goes here???" />
<input type="hidden" name="tlds[]" value=".me.uk" />
<input type="hidden" name="tlds[]" value=".org.uk" />
<input type="hidden" name="tlds[]" value=".com" />
<input type="hidden" name="tlds[]" value=".net" />
<input type="hidden" name="tlds[]" value=".org" />

<input type="submit" value="Go" class="product-headers" />
</form>

Body:
var i = $thewhole.indexOf('.');
var $domain = $thewhole.substr(0, i);
var $ext = $thewhole.substr(i);

Or with regexp

var regexp = /([^.]+)(\..*)/;
var match = regexp.exec($thewhole);
var $domain = match[1];
var $ext = match[2];

Edit:

<script type="text/javascript">

    function submithelper() {

      // this is why we need the id="xxx" below.
      var $domainInput = document.getElementById("domain");
      var $extInput = document.getElementById("ext");

      var $domain = $domainInput.value;
      var $i = $domain.indexOf('.');
      var $host = $domain.substr(0, $i); // perhaps skip to do this if it isn't used?
      var $ext = $domain.substr($i);

      $extInput.value = $ext;

      return true; // false to stop form from submitting.
    }

</script>

<form onsubmit="return submithelper()" method="post" action="https://www.jms-networks.net/domainchecker.php">

  <!-- Two inputs has been given IDs so we can easily get them from javascript. -->

  <span class="text"><input id="domain" value="{php} print $_POST['sld'] ? $_POST['sld'] : 'Search for your domain name'; {/php}" type="text" name="domain" class="searchbox" onfocus="if (this.value == this.defaultValue) this.value = '';" onblur="if (this.value == '') this.value = this.defaultValue;" /></span>
  <input type="hidden" name="direct" value="true" />
  <input id="ext" type="hidden" name="tlds[]" value="" />
  ...


问:
rxjs and angularJS - Referencing Component attributes using this within success callback inline function
I have the following component

```<code>export class SubjectDetailComponent implements OnInit
{
    pageTitle: string = "Subject Detail";
    resultID: number = 0;
    pupilID: number = 0;
    subjectResult: ISubjectResult;
    errorMessage: string = "";
    private sub: Subscription;

    constructor(private _route: ActivatedRoute,
                private _router: Router,
                private _subjectService : SubjectService)
    {

    }

    ngOnInit(): void
    {
        this.sub = this._route.params.subscribe(params => {
        this.resultID = params['result_id'];
        if ('pupil_id' in params)
        {
            this.pupilID = params['pupil_id'];
        }

        this.getSubject(this.resultID);
      });
    }

    getSubject(id: number)
    {
        this._subjectService.getSubject(id).subscribe(
            x => this.subjectResult = x,
            error => this.errorMessage = <any>error);
    }

}
</code>```

And the following service (ignore the longhand map just playing around):

```<code>getSubject(id: number): Observable<ISubjectResult> {
    return this.getSubjects()
        .map(function(srs: ISubjectResult[])
                {
                    let temp = srs.find(s => s.result_id == id);
                    return temp;
                });
}
</code>```

My code works fine to update the subjectResult attribute in SubjectDetailComponent with the code above. However when I try and implement getSubject with an inline function instead of an arrow function (just because I can) like this:

```<code> getSubject(id: number)
    {
        this._subjectService.getSubject(id).subscribe(
            function(x) { this.subjectResult = x; },
            error => this.errorMessage = <any>error);
    }
</code>```

The property subjectResult does not have the desired updated value. This is probably due to the scope and "this". Please can someone tell me how to reference a module/component's attributes from inside an inline function declaration.

Thanks in advance.

答:
You're right, the problem is with "this". An arrow function automatically uses the "this" context of the outer scope, unlike a normal function. Try using bind to access that scope,
    this._subjectService.getSubject(id).bind(this).subscribe....</p>

Body:
I have the following component

export class SubjectDetailComponent implements OnInit
{
    pageTitle: string = "Subject Detail";
    resultID: number = 0;
    pupilID: number = 0;
    subjectResult: ISubjectResult;
    errorMessage: string = "";
    private sub: Subscription;

    constructor(private _route: ActivatedRoute,
                private _router: Router,
                private _subjectService : SubjectService)
    {

    }

    ngOnInit(): void
    {
        this.sub = this._route.params.subscribe(params => {
        this.resultID = params['result_id'];
        if ('pupil_id' in params)
        {
            this.pupilID = params['pupil_id'];
        }

        this.getSubject(this.resultID);
      });
    }

    getSubject(id: number)
    {
        this._subjectService.getSubject(id).subscribe(
            x => this.subjectResult = x,
            error => this.errorMessage = <any>error);
    }

}

And the following service (ignore the longhand map just playing around):

getSubject(id: number): Observable<ISubjectResult> {
    return this.getSubjects()
        .map(function(srs: ISubjectResult[])
                {
                    let temp = srs.find(s => s.result_id == id);
                    return temp;
                });
}

My code works fine to update the subjectResult attribute in SubjectDetailComponent with the code above. However when I try and implement getSubject with an inline function instead of an arrow function (just because I can) like this:

 getSubject(id: number)
    {
        this._subjectService.getSubject(id).subscribe(
            function(x) { this.subjectResult = x; },
            error => this.errorMessage = <any>error);
    }

The property subjectResult does not have the desired updated value. This is probably due to the scope and "this". Please can someone tell me how to reference a module/component's attributes from inside an inline function declaration.

Thanks in advance.


问:
Module pattern context issue
How to access private variable "state" in the delete confirmation function. The "this" keyword points me to the window object.

var usersController = (function() {
  var state = {},

    init = function(defaultState) {
      state = defaultState;

      $(".btn-delete-row").on("click", function() {
        var recordId = $(this).attr("data-record-id");
        showDeleteConfirmation(recordId);
      });
    },

    showDeleteConfirmation = function(recordId) {
      //how to access state private variable here???
    };

  return {
    init: init
  };
}());
```

<p>and I call it like this: </p>

```$(function() {
  usersController.init({
    urls: {
      deleteRecord: "...."
    }
  });
});
```

答:
The variable state is available anywhere inside usersController

Try:

```<code>showDeleteConfirmation = function(recordId) {
      console.log(state);
};
</code>```

DEMO

Title: Module pattern context issue

Body:
How to access private variable "state" in the delete confirmation function. The "this" keyword points me to the window object.

var usersController = (function() {
  var state = {},

    init = function(defaultState) {
      state = defaultState;

      $(".btn-delete-row").on("click", function() {
        var recordId = $(this).attr("data-record-id");
        showDeleteConfirmation(recordId);
      });
    },

    showDeleteConfirmation = function(recordId) {
      //how to access state private variable here???
    };

  return {
    init: init
  };
}());

and I call it like this:

$(function() {
  usersController.init({
    urls: {
      deleteRecord: "...."
    }
  });
});

Body:
The variable state is available anywhere inside usersController

Try:

showDeleteConfirmation = function(recordId) {
      console.log(state);
};

DEMO


问:
How to get the value of the hidden field next to the clicked checkbox?
I've this two elements next to each other. The hidden field contains the ID of the record. When the user check/uncheck the checkbox, I should be able to retrieve the record's ID.

```<code><asp:CheckBox ID="ckEdit" runat="server" CssClass="ckEditClass" />
<asp:HiddenField ID="hfEdit" Value='<%# Eval("ID") %>' runat="server" />
</code>```

This is what I'm trying to do:

```<code>$(".ckEditClass").on("click", function () {
    var hidden = $(this).parent().parent().children(":hidden")
    alert(hidden.val());
 })
</code>```

I'm getting undefined.

EDIT

The above code is from Visual Studio. However, when I look at F12, I see a  around the checkbox. Hope this information will help.

```<code><td>
    <span class="ckEditClass">
          <asp:CheckBox ID="ckEdit" runat="server" CssClass="ckEditClass" />
    </span>
    <asp:HiddenField ID="hfEdit" Value='<%# Eval("ID") %>' runat="server" />
</td>
</code>```

答:
You can use jQuery closest() & find() methods to do it like following.

$(".ckEditClass:checkbox").on("click", function () {
    var hidden = $(this).closest('td').find(':hidden');
    alert(hidden.val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td>
        <span class="ckEditClass">
            <input type="checkbox" id="ckEdit" class="ckEditClass"/>
        </span>
        <input type="hidden" id="hfEdit" value="10" />
    </td>
  </tr>
</table></code>```

Body:
I've this two elements next to each other. The hidden field contains the ID of the record. When the user check/uncheck the checkbox, I should be able to retrieve the record's ID.

<asp:CheckBox ID="ckEdit" runat="server" CssClass="ckEditClass" />
<asp:HiddenField ID="hfEdit" Value='<%# Eval("ID") %>' runat="server" />

This is what I'm trying to do:

$(".ckEditClass").on("click", function () {
    var hidden = $(this).parent().parent().children(":hidden")
    alert(hidden.val());
 })

I'm getting undefined.

EDIT

The above code is from Visual Studio. However, when I look at F12, I see a  around the checkbox. Hope this information will help.

          <asp:CheckBox ID="ckEdit" runat="server" CssClass="ckEditClass" />

    <asp:HiddenField ID="hfEdit" Value='<%# Eval("ID") %>' runat="server" />

Body:
You can use jQuery closest() & find() methods to do it like following.

$(".ckEditClass:checkbox").on("click", function () {
    var hidden = $(this).closest('td').find(':hidden');
    alert(hidden.val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td>
        <span class="ckEditClass">
            <input type="checkbox" id="ckEdit" class="ckEditClass"/>
        </span>
        <input type="hidden" id="hfEdit" value="10" />
    </td>
  </tr>
</table>


问:
How do I add a horizontal line in a html select control?
How do I add a horizontal line (
 tag) in the dropdown control or in select control in HTML?

答:
The select element may only contain optgroup or option elements, and option elements may only contain text. Markup like
 is forbidden.

I would use an element like this to create a separator:

```<code><option disabled role=separator>
</code>```

You may consider markup like this:

```<code><optgroup label="-------"></optgroup>
</code>```

However, the rendering between different browsers varies a little too much to be acceptable.

Body:
The select element may only contain optgroup or option elements, and option elements may only contain text. Markup like <hr> is forbidden.

I would use an element like this to create a separator:

<option disabled role=separator>

You may consider markup like this:

<optgroup label="-------"></optgroup>

However, the rendering between different browsers varies a little too much to be acceptable.


问:
How to get proper relationship between tables in merge statement?
There are two tables in database A.

Table 1:

people:

```<code>person_id,
row1,
row2
</code>```

education:

```<code>education_id PK,
person_id FK,
row3,
row4
</code>```

I want to merge this tables to database B. I use temp tables to save records, but there is a problem with pk key. In tables on database b, primary keys are auto-increment. How to remember a joins between tables in database b, so as to create the same joins but with new primary key numbers.
For example:
education

```<code>education_id person_id
1            3
2            5
3            8
</code>```

First I used merge for people. Excellent all data was merged to database B, with new PK values. Now I want merge education table, but with the same relations(as in database A) to database B, but with new pk values. How to do it? I'm not sure that I explained the problem well. If there are any questions, ask them.

答:
Assumming that you have 2 temp tables INCLUDE source data

```<code>DECLARE @Person AS TABLE (personid int)

DECLARE @Education AS TABLE (educationid int, personid int)

DECLARE @MaxPersonId int ---- max Person ID in database B
</code>```

You could do these steps to insert data into database B.
SET IDENTITY_INSERT dbo.Person ON is the key to update

```<code> -- 1. UPDATE temp table WITH new PersonId
UPDATE personid in temp Table
UPDATE @Person
SET
    personid = personid + @MaxPersonId

UPDATE @Education
SET
    personid = personid + @MaxPersonId

-- 2. INSERT person in to database B
-- SET IDENTITY_INSERT dbo.Person ON would do the trick.
-- You could insert a primary auto-increment field by a fixed value
 SET IDENTITY_INSERT dbo.Person ON
  -- Insert person from temp table @Person
  INSERT INTO dbo.Person (PersonId)
  SELECT p.personid FROM @Person p

 SET IDENTITY_INSERT dbo.Person OFF

-- 3. INSERT INTO dbo.Education from @Education.
</code>```

Body:
There are two tables in database A.

Table 1:

people:

person_id,
row1,
row2

education:

education_id PK,
person_id FK,
row3,
row4

I want to merge this tables to database B. I use temp tables to save records, but there is a problem with pk key. In tables on database b, primary keys are auto-increment. How to remember a joins between tables in database b, so as to create the same joins but with new primary key numbers.
For example:
education

education_id person_id
1            3
2            5
3            8

First I used merge for people. Excellent all data was merged to database B, with new PK values. Now I want merge education table, but with the same relations(as in database A) to database B, but with new pk values. How to do it? I'm not sure that I explained the problem well. If there are any questions, ask them.

Body:
Assumming that you have 2 temp tables INCLUDE source data

DECLARE @Person AS TABLE (personid int)

DECLARE @Education AS TABLE (educationid int, personid int)

DECLARE @MaxPersonId int ---- max Person ID in database B

You could do these steps to insert data into database B.
SET IDENTITY_INSERT dbo.Person ON is the key to update

 -- 1. UPDATE temp table WITH new PersonId
UPDATE personid in temp Table
UPDATE @Person
SET
    personid = personid + @MaxPersonId

UPDATE @Education
SET
    personid = personid + @MaxPersonId

-- 2. INSERT person in to database B
-- SET IDENTITY_INSERT dbo.Person ON would do the trick.
-- You could insert a primary auto-increment field by a fixed value
 SET IDENTITY_INSERT dbo.Person ON
  -- Insert person from temp table @Person
  INSERT INTO dbo.Person (PersonId)
  SELECT p.personid FROM @Person p

 SET IDENTITY_INSERT dbo.Person OFF

-- 3. INSERT INTO dbo.Education from @Education.