问:
Vue.js + Require.js extending parent
I'm new to Vue.js but trying to get to grips with it. So far it has gone well and I've got quite far but I am stuck extending a parents template.

I am trying to make dashboard widgets that extend a default widget layout (in Boostrap). Please note that the below code is using Vue, Require, Underscore & Axios.

Parent file - _Global.vue

```<code><template>
    <div class="panel panel-default">
        <div class="panel-heading">
            <b>{{ widgetTitle }}</b>
            <div class="pull-right">
                <a href="#" v-on:click="toggleMinimized"
                   v-bind:title="(isMinimized ? 'Show widget' : 'Hide widget')">
                    <i class="fa fa-fw" v-bind:class="isMinimized ? 'fa-plus' : 'fa-minus'"></i>
                </a>
            </div>
        </div>
        <div class="panel-body" v-if="!isMinimized">

            <div class="text-center text-muted" v-if="!isLoaded">
                <i class="fa fa-spin fa-circle-o-notch"></i><br />
            </div>

            <parent v-if="isLoaded">
                <!-- parent content should appear here when loaded -->
            </parent>
        </div>
    </div>
</template>
<script>
    export default {

        // setup our widget props
        props: {
            'minimized': {
                'default': false,
                'required': false,
                'type': Boolean
            }
        },

        // define our data
        data: function () {
            return {
                widgetTitle: 'Set widget title in data',
                isLoaded: false,
                isMinimized: this.$props.minimized
            }
        },

        // when vue is mounted, open our widget
        mounted: function () {
            if(!this.isMinimized) {
                this.opened();
            }
        },

        // define our methods
        methods: {

            // store our widget state to database
            storeWidgetState: function () {

                // set our data to send
                let data = {
                    'action' : 'toggleWidget',
                    'widget' : this.$options._componentTag,
                    'state' : !this.isMinimized
                };

                // post our data to our endpoint
                axios.post(axios.endpoint, data);
            },

            // toggle our minimized data
            toggleMinimized: function (e) {

                // prevent default
                e.preventDefault();

                // toggle our minimized state
                this.isMinimized = !this.isMinimized;

                // trigger opened if we aren't minimized
                if(!this.isMinimized) this.opened();

                // save our widget state to database
                this.storeWidgetState();
            },

            // triggered when opened from being minimized
            opened: function () {
                console.log('opened() method is where all widget logic should be placed');
            }
        }

    }
</script>
</code>```

Child file - Example.vue
Should extend _Global.vue using mixins and then display content within .panel-body

```<code><template>
    <div>
        I want this content to appear inside the .panel-body div

        {{ content }}

         <img v-bind:src="image.src" v-bind:alt="image.alt"
             v-if="image.src" class="img-responsive" style="margin: 0 auto" />
    </div>
</template>
<script>

    // import our widgets globals
    import Global from './_Global.vue'

    export default {

        components: {
            'parent': {
                // what can I possibly put here??
            }
        },

        // use our global mixin for all widgets
        mixins: [Global],

        // setup our methods for this widget
        methods: {

            opened: _.debounce(function () {

                // make sure this can only be opened once
                if(this.hasBeenOpened) return;
                this.hasBeenOpened = true;

                // temporarily allow axios to make external requests
                let axiosHeaders = axios.defaults.headers.common;
                let vm = this;
                axios.defaults.headers.common = {};

                axios.get('https://yesno.wtf/api')
                    .then(function (res) {

                        // set our content
                        vm.content = null;

                        // set our image content
                        vm.image.src = res.data.image;
                        vm.image.alt = res.data.answer;

                    })
                    .catch(function (err) {

                        // set our error text
                        vm.content = String(err);

                    })
                    .then(function () {

                        // this will always hit..
                        vm.isLoaded = true;

                    });

                // restore our axios headers for security
                axios.defaults.headers.common = axiosHeaders;
            }, 300)
        },

        // additional data
        data: function () {
            return {

                // set our widgets title
                widgetTitle: 'Test title',

                // logic for the specific widget
                hasBeenOpened: false,
                content: 'Loaded and ready to go...',
                image: {
                    src: false,
                    alt: null
                }
            };
        },

    }
</script>
</code>```

Currently my parent template is just completely overwriting my child view. The only way I can get it to work is by explicitly defining the template parameter inside components -> parent: {} but I don't want to have to do that...?

答:
Ok, thanks to Gerardo Rosciano for pointing me the in right direction. I've used to slots to come up with an eventual solution. We then access parent methods and data attributes just to get everything working as it should.

Example.vue - our example widget

```<code><template>
    <div>
        <widget-wrapper>
            <span slot="header">Example widget</span>
            <div slot="content">
                <img v-bind:src="image.src" v-bind:alt="image.alt"
                     v-if="image.src" class="img-responsive" style="margin: 0 auto" />

                {{ content }}
            </div>
        </widget-wrapper>
    </div>
</template>
<script>

    // import our widgets globals
    import WidgetWrapper from './_Widget.vue'

    export default {

        // setup our components
        components: {
            'widget-wrapper': WidgetWrapper
        },

        // set our elements props
        props: {
            'minimized': {
                'type': Boolean,
                'default': false,
                'required': false
            }
        },

        // setup our methods for this widget
        methods: {

            loadContent: _.debounce(function () {

                // make sure this can only be opened once
                if(this.hasBeenOpened) return;
                this.hasBeenOpened = true;

                // temporarily allow axios to make external requests
                let axiosHeaders = axios.defaults.headers.common;
                let vm = this;
                axios.defaults.headers.common = {};

                axios.get('https://yesno.wtf/api')
                    .then(function (res) {

                        // set our content
                        vm.content = null;

                        // set our image content
                        vm.image.src = res.data.image;
                        vm.image.alt = res.data.answer;

                    })
                    .catch(function (err) {

                        // set our error text
                        vm.content = String(err);

                    })
                    .then(function () {

                        // this will always hit..
                        vm.isLoaded = true;

                    });

                // restore our axios headers for security
                axios.defaults.headers.common = axiosHeaders;
            }, 300)
        },

        // additional data
        data: function () {
            return {

                // global param for parent
                isLoaded: false,

                // logic for the specific widget
                hasBeenOpened: false,
                content: 'Loaded and ready to go...',
                image: {
                    src: false,
                    alt: null
                }
            };
        },

    }
</script>
</code>```

_Widget.vue - our base widget that gets extended

```<code><template>
    <div class="panel panel-default">
        <div class="panel-heading">
            <b><slot name="header">Slot header title</slot></b>
            <div class="pull-right">
                <a href="#" v-on:click="toggleMinimized"
                   v-bind:title="(minimized ? 'Show widget' : 'Hide widget')">
                    <i class="fa fa-fw" v-bind:class="minimized ? 'fa-plus' : 'fa-minus'"></i>
                </a>
            </div>
        </div>
        <div class="panel-body" v-if="!minimized">
            <div class="text-center text-muted" v-if="!isLoaded">
                <i class="fa fa-spin fa-circle-o-notch"></i><br />
                Loading...
            </div>
            <div v-else>
                <slot name="content"></slot>
            </div>
        </div>
    </div>
</template>

<script>
    export default {

        // get loaded state from our parent
        computed: {
            isLoaded: function () {
                return this.$parent.isLoaded;
            }
        },

        // set our data element
        data: function () {
            return {
                minimized: false
            }
        },

        // when the widget is mounted, trigger open state
        mounted: function () {
            this.minimized = this.$parent.minimized;
            if(!this.minimized) this.opened();
        },

        // methods to manipulate our widget
        methods: {

            // save our widget state to database
            storeWidgetState: function () {

                // set our data to send
                let data = {
                    'action' : 'toggleWidget',
                    'widget' : this.$parent.$options._componentTag,
                    'state' : !this.minimized
                };

                // post this data to our endpoint
                axios.post(axios.endpoint, data);
            },

            // toggle our minimized state
            toggleMinimized: function (e) {

                // prevent default
                e.preventDefault();

                // toggle our minimized state
                this.minimized = !this.minimized;

                // trigger opened if we aren't minimized
                if(!this.minimized) this.opened();

                // save our widget state to database
                this.storeWidgetState();
            },

            // when widget is opened, load content
            opened: function () {

                // make sure we have a valid loadContent method
                if(typeof this.$parent.loadContent === "function") {
                    this.$parent.loadContent();
                } else {
                    console.log('You need to define a loadContent() method on the widget');
                }
            }
        }
    }
</script>
</code>```

Title: Vue.js + Require.js extending parent

Body:
I'm new to Vue.js but trying to get to grips with it. So far it has gone well and I've got quite far but I am stuck extending a parents template.

I am trying to make dashboard widgets that extend a default widget layout (in Boostrap). Please note that the below code is using Vue, Require, Underscore & Axios.

Parent file - _Global.vue

<template>

            {{ widgetTitle }}

            <parent v-if="isLoaded">

            </parent>

</template>

Child file - Example.vue
Should extend _Global.vue using mixins and then display content within .panel-body

<template>

        I want this content to appear inside the .panel-body div

        {{ content }}

</template>

Currently my parent template is just completely overwriting my child view. The only way I can get it to work is by explicitly defining the template parameter inside components -> parent: {} but I don't want to have to do that...?

Body:
Ok, thanks to Gerardo Rosciano for pointing me the in right direction. I've used to slots to come up with an eventual solution. We then access parent methods and data attributes just to get everything working as it should.

Example.vue - our example widget

<template>
    <div>
        <widget-wrapper>
            <span slot="header">Example widget</span>
            <div slot="content">
                <img v-bind:src="image.src" v-bind:alt="image.alt"
                     v-if="image.src" class="img-responsive" style="margin: 0 auto" />

                {{ content }}
            </div>
        </widget-wrapper>
    </div>
</template>
<script>

    // import our widgets globals
    import WidgetWrapper from './_Widget.vue'

    export default {

        // setup our components
        components: {
            'widget-wrapper': WidgetWrapper
        },

        // set our elements props
        props: {
            'minimized': {
                'type': Boolean,
                'default': false,
                'required': false
            }
        },

        // setup our methods for this widget
        methods: {

            loadContent: _.debounce(function () {

                // make sure this can only be opened once
                if(this.hasBeenOpened) return;
                this.hasBeenOpened = true;

                // temporarily allow axios to make external requests
                let axiosHeaders = axios.defaults.headers.common;
                let vm = this;
                axios.defaults.headers.common = {};

                axios.get('https://yesno.wtf/api')
                    .then(function (res) {

                        // set our content
                        vm.content = null;

                        // set our image content
                        vm.image.src = res.data.image;
                        vm.image.alt = res.data.answer;

                    })
                    .catch(function (err) {

                        // set our error text
                        vm.content = String(err);

                    })
                    .then(function () {

                        // this will always hit..
                        vm.isLoaded = true;

                    });

                // restore our axios headers for security
                axios.defaults.headers.common = axiosHeaders;
            }, 300)
        },

        // additional data
        data: function () {
            return {

                // global param for parent
                isLoaded: false,

                // logic for the specific widget
                hasBeenOpened: false,
                content: 'Loaded and ready to go...',
                image: {
                    src: false,
                    alt: null
                }
            };
        },

    }
</script>

_Widget.vue - our base widget that gets extended

<template>
    <div class="panel panel-default">
        <div class="panel-heading">
            <b><slot name="header">Slot header title</slot></b>
            <div class="pull-right">
                <a href="#" v-on:click="toggleMinimized"
                   v-bind:title="(minimized ? 'Show widget' : 'Hide widget')">
                    <i class="fa fa-fw" v-bind:class="minimized ? 'fa-plus' : 'fa-minus'"></i>
                </a>
            </div>
        </div>
        <div class="panel-body" v-if="!minimized">
            <div class="text-center text-muted" v-if="!isLoaded">
                <i class="fa fa-spin fa-circle-o-notch"></i><br />
                Loading...
            </div>
            <div v-else>
                <slot name="content"></slot>
            </div>
        </div>
    </div>
</template>

<script>
    export default {

        // get loaded state from our parent
        computed: {
            isLoaded: function () {
                return this.$parent.isLoaded;
            }
        },

        // set our data element
        data: function () {
            return {
                minimized: false
            }
        },

        // when the widget is mounted, trigger open state
        mounted: function () {
            this.minimized = this.$parent.minimized;
            if(!this.minimized) this.opened();
        },

        // methods to manipulate our widget
        methods: {

            // save our widget state to database
            storeWidgetState: function () {

                // set our data to send
                let data = {
                    'action' : 'toggleWidget',
                    'widget' : this.$parent.$options._componentTag,
                    'state' : !this.minimized
                };

                // post this data to our endpoint
                axios.post(axios.endpoint, data);
            },

            // toggle our minimized state
            toggleMinimized: function (e) {

                // prevent default
                e.preventDefault();

                // toggle our minimized state
                this.minimized = !this.minimized;

                // trigger opened if we aren't minimized
                if(!this.minimized) this.opened();

                // save our widget state to database
                this.storeWidgetState();
            },

            // when widget is opened, load content
            opened: function () {

                // make sure we have a valid loadContent method
                if(typeof this.$parent.loadContent === "function") {
                    this.$parent.loadContent();
                } else {
                    console.log('You need to define a loadContent() method on the widget');
                }
            }
        }
    }
</script>


来源: stackexchange

问:
Intent with multiple startactivity paramaters
I want a value to be passed from the first to the last activity when a button is clicked.

At the same time I want this button to bring me to the second activity. Somehow this doesn't work.

```<code>private void imagebutton1 () {
          ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
            btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  //startActivity (new Intent(Akt1.this,Akt2.class));

                  String data1 = "data1";

                  Intent intent = new Intent (Akt1.this,Akt2.class);
                  Intent passdata_intent = new Intent(Akt1.this, Akt6.class);
                  passdata_intent.putExtra("data1",data1);

                 startActivity(passdata_intent);

              }
          });
</code>```

答:
i want a value to be passed from the first to the last activity when a
  button is clicked.

Sorry, it is impossible. You have to follow the activity stack.

To pass data from one to another, one intent had enough, no need to have two.

```<code> Intent intent = new Intent (Akt1.this,Akt2.class);
 intent.putExtra("data1",data1);
 startActivity(intent);
</code>```

Refer from how to directly pass value of a variable from 1st activty to 3rd activity using putextra?

Akt1

```<code> Intent intent = new Intent (Akt1.this,Akt2.class);
 intent.putExtra("data1",data1);
 startActivity(intent);
</code>```

Akt2

After setContentView

```<code>Intent intent = getIntent();
String data1 = intent.getStringExtra("data1");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want a value to be passed from the first to the last activity when a button is clicked.

At the same time I want this button to bring me to the second activity. Somehow this doesn't work.

private void imagebutton1 () {
          ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
            btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  //startActivity (new Intent(Akt1.this,Akt2.class));

                  String data1 = "data1";

                  Intent intent = new Intent (Akt1.this,Akt2.class);
                  Intent passdata_intent = new Intent(Akt1.this, Akt6.class);
                  passdata_intent.putExtra("data1",data1);

                 startActivity(passdata_intent);

              }
          });

Body:
i want a value to be passed from the first to the last activity when a
  button is clicked.

Sorry, it is impossible. You have to follow the activity stack.

To pass data from one to another, one intent had enough, no need to have two.

 Intent intent = new Intent (Akt1.this,Akt2.class);
 intent.putExtra("data1",data1);
 startActivity(intent);

Refer from how to directly pass value of a variable from 1st activty to 3rd activity using putextra?

Akt1

 Intent intent = new Intent (Akt1.this,Akt2.class);
 intent.putExtra("data1",data1);
 startActivity(intent);

Akt2

After setContentView

Intent intent = getIntent();
String data1 = intent.getStringExtra("data1");


问:
How do I print it into an organised json file?
I need help with the output of my json file. I'm trying to print out the keys in a list called keypairs. I have to generate 60 keys, which i have included in the (count<60) part of my code (which isnt here). Im just showing the exporting part of my codes which i have a problem with. Here are my codes:

```<code>with open("/home/pi/Desktop/database.json", 'w+'):
    db = TinyDB('/home/pi/Desktop/database.json')
    table = db.table('Books')
    db.insert({'Book ID' : keypair[bookid], 'Serial No.' : keypair[bookserial] })
</code>```

However, the problem I have right now is that it prints out all the keys in the lists - bookid and bookserial instead of printing a pair of keys in one { }.

Here's an example output where count<2:

```<code>Pillar": {}, "_default":
 {"1":
   {"Bookid": ["b'\\XXXXXX bookid 1 XXXXXXX'", "b'\\AAAAAA bookid 2 AAAAAAA'"],
    "Serial No.": ["b'\\YYYYYserialno 1YYYYY'", "b'BBBBserial no2BBBB'"]
   }
 }
</code>```

This is the output that i intend to get:

in a format like this where a pair of keys are printed everytime it runs again:

```<code>{ Books:
  {
    Book ID: XXXX bookid 1 XXXX
    Serial No.: XXX serialno 1 XXXX
  }
  {
    Book ID: XXX bookid 2 XXXX
    Serial No.: XXX serial no. 2 XXX
   }
 }
</code>```

As you can see, the json file is messy, i have no idea how to make it automatically neat and also, you can see that the keys print out together into one instead of separately. Imagine having to print 60 pairs of these and they are all under one { }.

Help!

答:
I see multiple syntax problems in your code when you are trying to create the json. You could try to do this.

```<code>{ Books:
  {
      {
        Book ID: XXXXXXXX
        Serial No.: XXXXXXX
      },
      {
        Book ID: XXXXXXX
        Serial No.: XXXXXX
       }
  }
 }
</code>```

As you can see i wrapped the book items in brackets as well and the items are comma separated now.

This could help you with your problem.

Body:
I need help with the output of my json file. I'm trying to print out the keys in a list called keypairs. I have to generate 60 keys, which i have included in the (count<60) part of my code (which isnt here). Im just showing the exporting part of my codes which i have a problem with. Here are my codes:

with open("/home/pi/Desktop/database.json", 'w+'):
    db = TinyDB('/home/pi/Desktop/database.json')
    table = db.table('Books')
    db.insert({'Book ID' : keypair[bookid], 'Serial No.' : keypair[bookserial] })

However, the problem I have right now is that it prints out all the keys in the lists - bookid and bookserial instead of printing a pair of keys in one { }.

Here's an example output where count<2:

Pillar": {}, "_default":
 {"1":
   {"Bookid": ["b'\\XXXXXX bookid 1 XXXXXXX'", "b'\\AAAAAA bookid 2 AAAAAAA'"],
    "Serial No.": ["b'\\YYYYYserialno 1YYYYY'", "b'BBBBserial no2BBBB'"]
   }
 }

This is the output that i intend to get:

in a format like this where a pair of keys are printed everytime it runs again:

{ Books:
  {
    Book ID: XXXX bookid 1 XXXX
    Serial No.: XXX serialno 1 XXXX
  }
  {
    Book ID: XXX bookid 2 XXXX
    Serial No.: XXX serial no. 2 XXX
   }
 }

As you can see, the json file is messy, i have no idea how to make it automatically neat and also, you can see that the keys print out together into one instead of separately. Imagine having to print 60 pairs of these and they are all under one { }.

Help!

Body:
I see multiple syntax problems in your code when you are trying to create the json. You could try to do this.

{ Books:
  {
      {
        Book ID: XXXXXXXX
        Serial No.: XXXXXXX
      },
      {
        Book ID: XXXXXXX
        Serial No.: XXXXXX
       }
  }
 }

As you can see i wrapped the book items in brackets as well and the items are comma separated now.

This could help you with your problem.


问:
unable to insert users registration details into the database
i cannot insert users into database after registration, i have done all i can but was not successful, i really neddd help here, please i want to know and what am doing wrong in my script.

this is my registration html script:

```<code><span class='details' ><h1><bold>ENTER YOUR DETAILS HERE</bold></h1></span>

  <form action="trotle.php"  method="POST">

              <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">
              <input type="hidden" class="form-control" name="id" placeholder="enter your id" required />
                </div><br>

               <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">

              <label>fullname</label>

                  <input type="text" class="form-control" name="fullname" placeholder="Enter your fullname" required />
                </div><br>

                <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">

              <label>username</label>

                  <input type="username" class="form-control" name="username" placeholder="Enter your username" required />
                </div><br>

                <div class="form-group" >
                   <label>password</label>

                 <input type="password" class="form-control" name="password"  placeholder="type in your password" required />
                </div>

              <br>
              <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;" />
                <label>email</label>

                  <input type="email" class="form-control" name="email"  placeholder="Enter your email" required />
                </div><br>

                <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">
                <label>country</label>

                  <input type="text" class="form-control" name="country"  placeholder="Enter your country" required />
                </div><br>

                <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">
                <label>phone number</label>

                  <input type="number" class="form-control" name="phonenumber"  placeholder="Enter your phonenumber" required />
                </div><br>

                <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">
                <label>Alternative phone number</label>

                  <input type="number" class="form-control" name="alternativephonenumber"  placeholder="Enter your alternative phonenumber" required />
                </div><br>

              <div class="form-group"  style="margin-left:50px;color:#000099; font-family:times;">
                <label>referrer</label>
                  <input type="text" class="form-control" name="referrer" placeholder="type in who referred you here" required />
                </div><br>

              <div class="form-group"  style="margin-left:50px;color:#000099; font-family:times;"">
                <label>paymentmode</label>

                  <select name="paymentmode" class="form-control" required />
<option value="">Select your paymentmode</option>
<option value="bitcoin">bitcoin</option>
<option value="perfectmoney">perfectmoney</option>
<option value="naira">naira</option>

                  </select>

                </div>
                <br>

           <div class="form-group" style='text-align: center;padding-top: 30px;'>

              <input type="checkbox" style=" vertical-align: sub; margin-left: 120px;margin-bottom: -15px; " required><a href="homepage.php">  I agree with </a><a href='../terms' target="_blank">Terms and conditions</a><br>
              <input type="submit" class="btn btn-success" name="submit_signup" value='REGISTER' style="margin-left:145px;border:none; margin-bottom: -10px; background-color: green; font-weight: bold;border-style: dotted;">
              <a href="trotle.php"><input type="post" class="btn btn-success" value='LOGIN' style="margin-left:140px;background-color: green; font-weight: bold;border-style: dotted; border-color:black ;padding: 5px; size:20px; margin-bottom:-10px;"></a>
              </div>
              <br>
              <?php

              ?>
              </form>
</code>```

my php script for inserting users into database is below;

```<code><?php
$id=$fullname=$username=$password=$email=$country= $phonenumber=$alternativephonenumber=$referrer=$paymentmode="";
if(isset($_POST) && array_key_exists('submit_signup',$_POST))
{
$id= $_POST['id'];
if(isset($_POST['id'])){
$id= $_POST['id'];

}
$fullname=$_POST['fullname'];
if(isset($_POST['fullname'])){
$fullname= $_POST['fullname'];
}
else{
    echo 'please enter your fullname';
}
$username= $_POST['username'];
if(isset($_POST['username'])){
$username= $_POST['username'];
}
else{
    echo 'enter your username';
}
$password= $_POST['password'];
if(isset($_POST['password'])){
$password= $_POST['password'];
}
else{
    echo 'enter your password';
}
$email= $_POST['email'];
if(isset($_POST['email'])){
$email= $_POST['email'];
}
else{
    echo 'enter your email';
}
$country= $_POST['country'];
if(isset($_POST['country'])){
$country= $_POST['country'];
}
else{
    echo 'enter your country';
}
$phonenumber= $_POST['phonenumber'];
if(isset($_POST['phonenumber'])){
$phonenumber= $_POST['phonenumber'];
}
else{
    echo 'enter your phonenumber';
}
$alternativephonenumber= $_POST['alternativephonenumber'];
if(isset($_POST['alternativephonenumber'])){
$alternativephonenumber= $_POST['alternativephonenumber'];
}
else{
    echo 'enter your alternativephonenumber';
}
$referrer= $_POST['referrer'];
if(isset($_POST['referrer'])){
$referrer= $_POST['referrer'];
}
else{
    echo 'enter your referrer';
}
$paymentmode= $_POST['paymentmode'];
if(isset($_POST['paymentmode'])){
$paymentmode= $_POST['paymentmode'];
}
else{var_dump($_POST['id']);
    echo 'enter your paymentmode';
}
}
    else {
        echo 'nah';

    }

    $serverhost='localhost';
$serverdb='charles';
$serveruser='root';
$serverpassword='';

try{
    $connect= new PDO("mysql:host=$serverhost;dbname=charles;" , $serveruser, $serverpassword);
 $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     }
      catch( PDOException $e)
        {
            echo $e->getmessage();
        }

     if($connect){
        echo 'database successful!';
     }

$sql="INSERT INTO users(id, fullname, username, password, email, country, phonenumber, alternativephonenumber, referrer, paymentmode)VALUES(:id, :fullname, :username, :password, :email, :country, :phonenumber, :alternativephonenumber, :referrer, :paymentmode)";

$query=$connect->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->bindParam(':fullname', $fullname, PDO::PARAM_STR);
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':country', $country, PDO::PARAM_STR);
$query->bindParam(':phonenumber', $phonenumber, PDO::PARAM_INT);
$query->bindParam(':alternativephonenumber', $alternativephonenumber, PDO::PARAM_INT);
$query->bindParam(':referrer', $referrer, PDO::PARAM_STR);
$query->bindParam(':paymentmode', $paymentmode, PDO::PARAM_STR);
$query->execute();

?>
</code>```

答:
Rather than unmanagable, inline styles, use css and assign the styles with classes, ids or parent>child selectors etc.

DIV elements do not use the / at the end of the tag ( see the email section in original code )

There is no input type POST ( <input type="post" class="btn btn-success" value='LOGIN'... /> ) - presumably a button would be better?

The id field is hidden in the HTML but presumably the db uses an auto-increment field ( Primary Key ) for this so it is not necessary to send this value - the user would not know this before submitting the form and there would be nothing to prevent them using any number they wanted potentially,

```<code><style>
    .form-group{margin-left:50px;color:#000099; font-family:times;}
    .form-control{}
    input[type='checkbox']{vertical-align: sub; margin-left: 120px;margin-bottom: -15px;}
    input[type='submit']{margin-left:145px;border:none; margin-bottom: -10px; background-color: green; font-weight: bold;border-style: dotted;}
    input[type='button']{margin-left:140px;background-color: green; font-weight: bold;border-style: dotted; border-color:black ;padding: 5px; size:20px; margin-bottom:-10px;}
</style>

<span class='details' >
   <h1>
      <bold>ENTER YOUR DETAILS HERE</bold>
   </h1>
</span>

<form action='trotle.php' method='POST'>

   <!-- HOW does a user enter a value here if it is HIDDEN??? Removed `required` attribute -->
   <div class='form-group'>
      <input type='hidden' class='form-control' name='id' placeholder='enter your id' />
   </div>
   <br>

   <div class='form-group'>
      <label>fullname</label>
      <input type='text' class='form-control' name='fullname' placeholder='Enter your fullname' required />
   </div>
   <br>
   <div class='form-group'>
      <label>username</label>
      <input type='username' class='form-control' name='username' placeholder='Enter your username' required />
   </div>
   <br>
   <div class='form-group' >
      <label>password</label>
      <input type='password' class='form-control' name='password' placeholder='type in your password' required />
   </div>
   <br>
   <div class='form-group'>
      <label>email</label>
      <input type='email' class='form-control' name='email'  placeholder='Enter your email' required />
   </div>
   <br>
   <div class='form-group'>
      <label>country</label>
      <input type='text' class='form-control' name='country' placeholder='Enter your country' required />
   </div>
   <br>
   <div class='form-group'>
      <label>phone number</label>
      <input type='number' class='form-control' name='phonenumber' placeholder='Enter your phonenumber' required />
   </div>
   <br>
   <div class='form-group'>
      <label>Alternative phone number</label>
      <input type='number' class='form-control' name='alternativephonenumber' placeholder='Enter your alternative phonenumber' required />
   </div>
   <br>
   <div class='form-group'>
      <label>referrer</label>
      <input type='text' class='form-control' name='referrer' placeholder='type in who referred you here' required />
   </div>
   <br>
   <div class='form-group'>
      <label>paymentmode</label>
      <select name='paymentmode' class='form-control' required />
         <option value=''>Select your paymentmode</option>
         <option value='bitcoin'>bitcoin</option>
         <option value='perfectmoney'>perfectmoney</option>
         <option value='naira'>naira</option>
      </select>
   </div>
   <br>
   <div class='form-group'>
      <!-- this checkbox needs a name!! Assign name `terms` -->
      <input type='checkbox' name='terms' required />
      <a href='homepage.php'>  I agree with </a><a href='../terms' target='_blank'>Terms and conditions</a>
      <br>
      <input type='submit' class='btn btn-success' name='submit_signup' value='REGISTER' />
      <a href='trotle.php'>
        <input type='button' class='btn btn-success' value='LOGIN' />
      </a>
   </div>
   <br>
</form>

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit_signup'] ) ){
        /* id should be an auto-increment field in the db */
        $id = isset( $_POST['id'] ) ? $_POST['id'] : false;
        $fullname = isset( $_POST['fullname'] ) ? $_POST['fullname'] : false;
        $username = isset( $_POST['username'] ) ? $_POST['username'] : false;
        $password = isset( $_POST['password'] ) ? $_POST['password'] : false;
        $email = isset( $_POST['email'] ) ? $_POST['email'] : false;
        $country = isset( $_POST['country'] ) ? $_POST['country'] : false;
        $phonenumber = isset( $_POST['phonenumber'] ) ? $_POST['phonenumber'] : false;
        $alternativephonenumber = isset( $_POST['alternativephonenumber'] ) ? $_POST['alternativephonenumber'] : false;
        $referrer = isset( $_POST['referrer'] ) ? $_POST['referrer'] : false;
        $paymentmode = isset( $_POST['paymentmode'] ) ? $_POST['paymentmode'] : false;

        $errors=array();
        if( !$fullname )$errors[]='please enter your fullname';
        if( !$username )$errors[]='enter your username';
        if( !$password )$errors[]='enter your password';
        if( !$email )$errors[]='enter your email';
        if( !$country )$errors[]='enter your country';
        if( !$phonenumber )$errors[]='enter your phonenumber';
        if( !$alternativephonenumber )$errors[]='enter your alternativephonenumber';
        if( !$referrer )$errors[]='enter your referrer';
        if( !$paymentmode )$errors[]='enter your paymentmode';

        if( !empty( $errors ) ){

            /* display any errors with form submission */
            foreach( $errors as $error ){
                echo $error . '<br />';
            }

        } else {

            try{

                $serverhost='localhost';
                $serverdb='charles';
                $serveruser='root';
                $serverpassword='';

                $connect=new PDO("mysql:host={$serverhost};dbname={$serverdb};" , $serveruser, $serverpassword);
                $connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

                if( $connect ){

                    $sql="insert into `users`
                            ( `fullname`, `username`, `password`, `email`, `country`, `phonenumber`, `alternativephonenumber`, `referrer`, `paymentmode` )
                            values
                            ( :fullname, :username, :password, :email, :country, :phonenumber, :alternativephonenumber, :referrer, :paymentmode )";

                    $stmt=$connect->prepare( $sql );

                    if( $stmt ){

                        $stmt->bindParam(':fullname', $fullname, PDO::PARAM_STR);
                        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
                        $stmt->bindParam(':password', $password, PDO::PARAM_STR);
                        $stmt->bindParam(':email', $email, PDO::PARAM_STR);
                        $stmt->bindParam(':country', $country, PDO::PARAM_STR);
                        $stmt->bindParam(':phonenumber', $phonenumber );
                        $stmt->bindParam(':alternativephonenumber', $alternativephonenumber );
                        $stmt->bindParam(':referrer', $referrer, PDO::PARAM_STR);
                        $stmt->bindParam(':paymentmode', $paymentmode, PDO::PARAM_STR);

                        $result = $stmt->execute();
                        echo $result ? 'success' : 'fail';
                    }
                }
            } catch( PDOException $e ) {
                echo $e->getMessage();
            }
        }
    }

?>
</code>```

Body:
i cannot insert users into database after registration, i have done all i can but was not successful, i really neddd help here, please i want to know and what am doing wrong in my script.

this is my registration html script:

<bold>ENTER YOUR DETAILS HERE</bold>

  <form action="trotle.php"  method="POST">

              <input type="hidden" class="form-control" name="id" placeholder="enter your id" required />

              fullname

                  <input type="text" class="form-control" name="fullname" placeholder="Enter your fullname" required />

              username

                  <input type="username" class="form-control" name="username" placeholder="Enter your username" required />

                   password

                 <input type="password" class="form-control" name="password"  placeholder="type in your password" required />

                email

                  <input type="email" class="form-control" name="email"  placeholder="Enter your email" required />

                country

                  <input type="text" class="form-control" name="country"  placeholder="Enter your country" required />

                phone number

                  <input type="number" class="form-control" name="phonenumber"  placeholder="Enter your phonenumber" required />

                Alternative phone number

                  <input type="number" class="form-control" name="alternativephonenumber"  placeholder="Enter your alternative phonenumber" required />

                referrer
                  <input type="text" class="form-control" name="referrer" placeholder="type in who referred you here" required />

                paymentmode

                  <select name="paymentmode" class="form-control" required />
<option value="">Select your paymentmode</option>
<option value="bitcoin">bitcoin</option>
<option value="perfectmoney">perfectmoney</option>
<option value="naira">naira</option>

                  </select>

              <input type="checkbox" style=" vertical-align: sub; margin-left: 120px;margin-bottom: -15px; " required>  I agree with Terms and conditions

              <input type="submit" class="btn btn-success" name="submit_signup" value='REGISTER' style="margin-left:145px;border:none; margin-bottom: -10px; background-color: green; font-weight: bold;border-style: dotted;">
              <input type="post" class="btn btn-success" value='LOGIN' style="margin-left:140px;background-color: green; font-weight: bold;border-style: dotted; border-color:black ;padding: 5px; size:20px; margin-bottom:-10px;">

              <?php

              ?>
              </form>

my php script for inserting users into database is below;

<?php
$id=$fullname=$username=$password=$email=$country= $phonenumber=$alternativephonenumber=$referrer=$paymentmode="";
if(isset($_POST) && array_key_exists('submit_signup',$_POST))
{
$id= $_POST['id'];
if(isset($_POST['id'])){
$id= $_POST['id'];

}
$fullname=$_POST['fullname'];
if(isset($_POST['fullname'])){
$fullname= $_POST['fullname'];
}
else{
    echo 'please enter your fullname';
}
$username= $_POST['username'];
if(isset($_POST['username'])){
$username= $_POST['username'];
}
else{
    echo 'enter your username';
}
$password= $_POST['password'];
if(isset($_POST['password'])){
$password= $_POST['password'];
}
else{
    echo 'enter your password';
}
$email= $_POST['email'];
if(isset($_POST['email'])){
$email= $_POST['email'];
}
else{
    echo 'enter your email';
}
$country= $_POST['country'];
if(isset($_POST['country'])){
$country= $_POST['country'];
}
else{
    echo 'enter your country';
}
$phonenumber= $_POST['phonenumber'];
if(isset($_POST['phonenumber'])){
$phonenumber= $_POST['phonenumber'];
}
else{
    echo 'enter your phonenumber';
}
$alternativephonenumber= $_POST['alternativephonenumber'];
if(isset($_POST['alternativephonenumber'])){
$alternativephonenumber= $_POST['alternativephonenumber'];
}
else{
    echo 'enter your alternativephonenumber';
}
$referrer= $_POST['referrer'];
if(isset($_POST['referrer'])){
$referrer= $_POST['referrer'];
}
else{
    echo 'enter your referrer';
}
$paymentmode= $_POST['paymentmode'];
if(isset($_POST['paymentmode'])){
$paymentmode= $_POST['paymentmode'];
}
else{var_dump($_POST['id']);
    echo 'enter your paymentmode';
}
}
    else {
        echo 'nah';

    }

    $serverhost='localhost';
$serverdb='charles';
$serveruser='root';
$serverpassword='';

try{
    $connect= new PDO("mysql:host=$serverhost;dbname=charles;" , $serveruser, $serverpassword);
 $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     }
      catch( PDOException $e)
        {
            echo $e->getmessage();
        }

     if($connect){
        echo 'database successful!';
     }

$sql="INSERT INTO users(id, fullname, username, password, email, country, phonenumber, alternativephonenumber, referrer, paymentmode)VALUES(:id, :fullname, :username, :password, :email, :country, :phonenumber, :alternativephonenumber, :referrer, :paymentmode)";

$query=$connect->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->bindParam(':fullname', $fullname, PDO::PARAM_STR);
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':country', $country, PDO::PARAM_STR);
$query->bindParam(':phonenumber', $phonenumber, PDO::PARAM_INT);
$query->bindParam(':alternativephonenumber', $alternativephonenumber, PDO::PARAM_INT);
$query->bindParam(':referrer', $referrer, PDO::PARAM_STR);
$query->bindParam(':paymentmode', $paymentmode, PDO::PARAM_STR);
$query->execute();

?>

Body:
Rather than unmanagable, inline styles, use css and assign the styles with classes, ids or parent>child selectors etc.

DIV elements do not use the / at the end of the tag ( see the email section in original code )

There is no input type POST ( <input type="post" class="btn btn-success" value='LOGIN'... /> ) - presumably a button would be better?

The id field is hidden in the HTML but presumably the db uses an auto-increment field ( Primary Key ) for this so it is not necessary to send this value - the user would not know this before submitting the form and there would be nothing to prevent them using any number they wanted potentially,

<style>
    .form-group{margin-left:50px;color:#000099; font-family:times;}
    .form-control{}
    input[type='checkbox']{vertical-align: sub; margin-left: 120px;margin-bottom: -15px;}
    input[type='submit']{margin-left:145px;border:none; margin-bottom: -10px; background-color: green; font-weight: bold;border-style: dotted;}
    input[type='button']{margin-left:140px;background-color: green; font-weight: bold;border-style: dotted; border-color:black ;padding: 5px; size:20px; margin-bottom:-10px;}
</style>

<span class='details' >
   <h1>
      <bold>ENTER YOUR DETAILS HERE</bold>
   </h1>
</span>

<form action='trotle.php' method='POST'>

   <!-- HOW does a user enter a value here if it is HIDDEN??? Removed `required` attribute -->
   <div class='form-group'>
      <input type='hidden' class='form-control' name='id' placeholder='enter your id' />
   </div>
   <br>

   <div class='form-group'>
      <label>fullname</label>
      <input type='text' class='form-control' name='fullname' placeholder='Enter your fullname' required />
   </div>
   <br>
   <div class='form-group'>
      <label>username</label>
      <input type='username' class='form-control' name='username' placeholder='Enter your username' required />
   </div>
   <br>
   <div class='form-group' >
      <label>password</label>
      <input type='password' class='form-control' name='password' placeholder='type in your password' required />
   </div>
   <br>
   <div class='form-group'>
      <label>email</label>
      <input type='email' class='form-control' name='email'  placeholder='Enter your email' required />
   </div>
   <br>
   <div class='form-group'>
      <label>country</label>
      <input type='text' class='form-control' name='country' placeholder='Enter your country' required />
   </div>
   <br>
   <div class='form-group'>
      <label>phone number</label>
      <input type='number' class='form-control' name='phonenumber' placeholder='Enter your phonenumber' required />
   </div>
   <br>
   <div class='form-group'>
      <label>Alternative phone number</label>
      <input type='number' class='form-control' name='alternativephonenumber' placeholder='Enter your alternative phonenumber' required />
   </div>
   <br>
   <div class='form-group'>
      <label>referrer</label>
      <input type='text' class='form-control' name='referrer' placeholder='type in who referred you here' required />
   </div>
   <br>
   <div class='form-group'>
      <label>paymentmode</label>
      <select name='paymentmode' class='form-control' required />
         <option value=''>Select your paymentmode</option>
         <option value='bitcoin'>bitcoin</option>
         <option value='perfectmoney'>perfectmoney</option>
         <option value='naira'>naira</option>
      </select>
   </div>
   <br>
   <div class='form-group'>
      <!-- this checkbox needs a name!! Assign name `terms` -->
      <input type='checkbox' name='terms' required />
      <a href='homepage.php'>  I agree with </a><a href='../terms' target='_blank'>Terms and conditions</a>
      <br>
      <input type='submit' class='btn btn-success' name='submit_signup' value='REGISTER' />
      <a href='trotle.php'>
        <input type='button' class='btn btn-success' value='LOGIN' />
      </a>
   </div>
   <br>
</form>

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit_signup'] ) ){
        /* id should be an auto-increment field in the db */
        $id = isset( $_POST['id'] ) ? $_POST['id'] : false;
        $fullname = isset( $_POST['fullname'] ) ? $_POST['fullname'] : false;
        $username = isset( $_POST['username'] ) ? $_POST['username'] : false;
        $password = isset( $_POST['password'] ) ? $_POST['password'] : false;
        $email = isset( $_POST['email'] ) ? $_POST['email'] : false;
        $country = isset( $_POST['country'] ) ? $_POST['country'] : false;
        $phonenumber = isset( $_POST['phonenumber'] ) ? $_POST['phonenumber'] : false;
        $alternativephonenumber = isset( $_POST['alternativephonenumber'] ) ? $_POST['alternativephonenumber'] : false;
        $referrer = isset( $_POST['referrer'] ) ? $_POST['referrer'] : false;
        $paymentmode = isset( $_POST['paymentmode'] ) ? $_POST['paymentmode'] : false;

        $errors=array();
        if( !$fullname )$errors[]='please enter your fullname';
        if( !$username )$errors[]='enter your username';
        if( !$password )$errors[]='enter your password';
        if( !$email )$errors[]='enter your email';
        if( !$country )$errors[]='enter your country';
        if( !$phonenumber )$errors[]='enter your phonenumber';
        if( !$alternativephonenumber )$errors[]='enter your alternativephonenumber';
        if( !$referrer )$errors[]='enter your referrer';
        if( !$paymentmode )$errors[]='enter your paymentmode';

        if( !empty( $errors ) ){

            /* display any errors with form submission */
            foreach( $errors as $error ){
                echo $error . '<br />';
            }

        } else {

            try{

                $serverhost='localhost';
                $serverdb='charles';
                $serveruser='root';
                $serverpassword='';

                $connect=new PDO("mysql:host={$serverhost};dbname={$serverdb};" , $serveruser, $serverpassword);
                $connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

                if( $connect ){

                    $sql="insert into `users`
                            ( `fullname`, `username`, `password`, `email`, `country`, `phonenumber`, `alternativephonenumber`, `referrer`, `paymentmode` )
                            values
                            ( :fullname, :username, :password, :email, :country, :phonenumber, :alternativephonenumber, :referrer, :paymentmode )";

                    $stmt=$connect->prepare( $sql );

                    if( $stmt ){

                        $stmt->bindParam(':fullname', $fullname, PDO::PARAM_STR);
                        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
                        $stmt->bindParam(':password', $password, PDO::PARAM_STR);
                        $stmt->bindParam(':email', $email, PDO::PARAM_STR);
                        $stmt->bindParam(':country', $country, PDO::PARAM_STR);
                        $stmt->bindParam(':phonenumber', $phonenumber );
                        $stmt->bindParam(':alternativephonenumber', $alternativephonenumber );
                        $stmt->bindParam(':referrer', $referrer, PDO::PARAM_STR);
                        $stmt->bindParam(':paymentmode', $paymentmode, PDO::PARAM_STR);

                        $result = $stmt->execute();
                        echo $result ? 'success' : 'fail';
                    }
                }
            } catch( PDOException $e ) {
                echo $e->getMessage();
            }
        }
    }

?>


问:
What MS SQL Server types map to Types.VARCHAR
I'm working on a statement scanner for our updater (looking for statements that will cause problems with synchronized data) and I need to know which TSQL data types get resolved as Types.VARCHAR and which ones resolve to Types.LONGVARCHAR when you invoke DatabaseMetaData.getColumns()?

答:
check out: Understanding the JDBC Driver Data Types in BOL:

Using basic data types

Using advanced data types

So basically:

LONGVARCHAR: text, ntext, varchar(max), nvarchar(max), xml

VARCHAR: varchar, nvarchar

OwnerDisplayName: sblundy

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: kristof

OwnerDisplayName: kristof


问:
Extracting value from Form Date Element on Submit
I'm writing a Drupal module and have run into what should be a trivial problem;

Consider a 'Person' type node which includes a 'Date of Birth' property. I've configured the database table to use an int field to store the date in UNIX format (same as Drupal Core) but of course I need to provide a method for the user to specify the value in a more friendly format, i.e. dd/mm/yyyy.

In my modules Person_form function I have configured the date element thus:

```<code>$form['dob'] = array(
    '#type' => 'date',
    '#title' => 'Date of Birth',
    '#required' => TRUE,
    '#default_value' => array(
       'day' => format_date($node->dob, 'custom', 'j'),
       'month' => format_date($node->dob, 'custom', 'n'),
       'year' => format_date($node->dob, 'custom', 'Y'),
    ),
);
</code>```

which displays the UNIX date in the database in three dropdown lists, oneeach for day, month and year - this is just what I wanted, so far so good.

Now I need to be able to access this elements values when the user clicks on the 'Save' button - but I now have two problems:

The signature of the _form function is Person_form($node) so how do I access the $form['dob']['day'/'month'/'year'] values. $form is not passed as an argument to the function.

Once I have the values, what is the best way of generating a UNIX date value?

I've Googled about for a while but the terms 'drupal' and 'date' just seem to point me to the Date module extension - surely I don't need an extension to handle simple dates like this :-o

Thanks in advance

Body:
I'm writing a Drupal module and have run into what should be a trivial problem;

Consider a 'Person' type node which includes a 'Date of Birth' property. I've configured the database table to use an int field to store the date in UNIX format (same as Drupal Core) but of course I need to provide a method for the user to specify the value in a more friendly format, i.e. dd/mm/yyyy.

In my modules Person_form function I have configured the date element thus:

$form['dob'] = array(
    '#type' => 'date',
    '#title' => 'Date of Birth',
    '#required' => TRUE,
    '#default_value' => array(
       'day' => format_date($node->dob, 'custom', 'j'),
       'month' => format_date($node->dob, 'custom', 'n'),
       'year' => format_date($node->dob, 'custom', 'Y'),
    ),
);

which displays the UNIX date in the database in three dropdown lists, oneeach for day, month and year - this is just what I wanted, so far so good.

Now I need to be able to access this elements values when the user clicks on the 'Save' button - but I now have two problems:

The signature of the _form function is Person_form($node) so how do I access the $form['dob']['day'/'month'/'year'] values. $form is not passed as an argument to the function.

Once I have the values, what is the best way of generating a UNIX date value?

I've Googled about for a while but the terms 'drupal' and 'date' just seem to point me to the Date module extension - surely I don't need an extension to handle simple dates like this :-o

Thanks in advance

Body:
$d = $form_state['values']['dob'];
$mydateval = $d['year'].'-'.$d['month'].'-'.$d['day'];


问:
Singleton with parameter in Kotlin
I am trying to convert an Android app from Java to Kotlin. There are a few singletons in the app. I used a companion object for the singletons without constructor parameters. There is another singleton that takes a constructor parameter.

Java code:

```<code>public class TasksLocalDataSource implements TasksDataSource {

    private static TasksLocalDataSource INSTANCE;

    private TasksDbHelper mDbHelper;

    // Prevent direct instantiation.
    private TasksLocalDataSource(@NonNull Context context) {
        checkNotNull(context);
        mDbHelper = new TasksDbHelper(context);
    }

    public static TasksLocalDataSource getInstance(@NonNull Context context) {
        if (INSTANCE == null) {
            INSTANCE = new TasksLocalDataSource(context);
        }
        return INSTANCE;
    }
}
</code>```

My solution in kotlin:

```<code>class TasksLocalDataSource private constructor(context: Context) : TasksDataSource {

    private val mDbHelper: TasksDbHelper

    init {
        checkNotNull(context)
        mDbHelper = TasksDbHelper(context)
    }

    companion object {
        lateinit var INSTANCE: TasksLocalDataSource
        private val initialized = AtomicBoolean()

        fun getInstance(context: Context) : TasksLocalDataSource {
            if(initialized.getAndSet(true)) {
                INSTANCE = TasksLocalDataSource(context)
            }
            return INSTANCE
        }
    }
}
</code>```

Am I missing anything? Thread safety? Laziness ?

There were a few similar questions but I don't like the answers :)

答:
```<code>Singletons
</code>```

Singletons are used often enough for a simpler way of creating them to exist. Instead of the usual static instance, getInstance() method and a private constructor, Kotlin uses the object notation.
For consistency, object notation is also used to define static methods.

```<code> object CommonApiConfig {
private var commonApiConfig: CommonApiConfig? = null
fun getInstance(): CommonApiConfig {
    if (null == commonApiConfig) {
        commonApiConfig = CommonApiConfig
       }
    return CommonApiConfig.commonApiConfig!!
   }
}
</code>```

Title: Singleton with parameter in Kotlin

Body:
I am trying to convert an Android app from Java to Kotlin. There are a few singletons in the app. I used a companion object for the singletons without constructor parameters. There is another singleton that takes a constructor parameter.

Java code:

public class TasksLocalDataSource implements TasksDataSource {

    private static TasksLocalDataSource INSTANCE;

    private TasksDbHelper mDbHelper;

    // Prevent direct instantiation.
    private TasksLocalDataSource(@NonNull Context context) {
        checkNotNull(context);
        mDbHelper = new TasksDbHelper(context);
    }

    public static TasksLocalDataSource getInstance(@NonNull Context context) {
        if (INSTANCE == null) {
            INSTANCE = new TasksLocalDataSource(context);
        }
        return INSTANCE;
    }
}

My solution in kotlin:

class TasksLocalDataSource private constructor(context: Context) : TasksDataSource {

    private val mDbHelper: TasksDbHelper

    init {
        checkNotNull(context)
        mDbHelper = TasksDbHelper(context)
    }

    companion object {
        lateinit var INSTANCE: TasksLocalDataSource
        private val initialized = AtomicBoolean()

        fun getInstance(context: Context) : TasksLocalDataSource {
            if(initialized.getAndSet(true)) {
                INSTANCE = TasksLocalDataSource(context)
            }
            return INSTANCE
        }
    }
}

Am I missing anything? Thread safety? Laziness ?

There were a few similar questions but I don't like the answers :)

Body:
Singletons

Singletons are used often enough for a simpler way of creating them to exist. Instead of the usual static instance, getInstance() method and a private constructor, Kotlin uses the object notation.
For consistency, object notation is also used to define static methods.

 object CommonApiConfig {
private var commonApiConfig: CommonApiConfig? = null
fun getInstance(): CommonApiConfig {
    if (null == commonApiConfig) {
        commonApiConfig = CommonApiConfig
       }
    return CommonApiConfig.commonApiConfig!!
   }
}


问:
upload_max_filesize from php.ini doesn't work
I want to import a database which size is 11 MB. I installed xampp local server. it was set in php.ini to 2M.
I set it to upload_max_filesize=128M and also max_file_uploads=128. After that i used the phpinfo() function, which show me that is set to 128 MB, BUT in phpmyadmin it shows me 8MB and i got this message after import: You probably tried to upload a file that is too large. Please refer to documentation for a workaround for this limit.

YES, I restarted the server many times!

I tried to find and answer from another posts but with no results. Can anyone help me with this ? thx

答:
Click on the MySQL config button (see image below) then click my.ini and change: myisam_sort_buffer_size = 8M to myisam_sort_buffer_size = 1888M.

Increase your M size according to your own then click apply.


问:
Pipeline fails when using try/catch in parallel
I'm quite new to the pipelines and have been reading some official tutorials. I have been trying to figure out how to use try/catch in a node which is running in parallel. I'm following the official example. Here is some code:

```<code>stage('Test') {
    parallel linux: {
        node('linux') {
            checkout scm
            try {
                unstash 'app'
                sh 'make check'
            }
            finally {
                junit '**/target/*.xml'
            }
        }
    }
}
</code>```

Running pretty much the same code with only node labels changed. However I received the following error:

```<code>org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 23: Expected a step @ line 23, column 29.
                           try {
                           ^
</code>```

Anybody has an idea what's wrong here?

答:
Try to replace 'script' to 'steps', its work well in my side

```<code>stage('Test') {
parallel linux: {
    node('linux') {
        script {
            checkout scm
            try {
                unstash 'app'
                sh 'make check'
            }
            finally {
                junit '**/target/*.xml'
            }
      }
    }
}
</code>```

}

Body:
I'm quite new to the pipelines and have been reading some official tutorials. I have been trying to figure out how to use try/catch in a node which is running in parallel. I'm following the official example. Here is some code:

stage('Test') {
    parallel linux: {
        node('linux') {
            checkout scm
            try {
                unstash 'app'
                sh 'make check'
            }
            finally {
                junit '**/target/*.xml'
            }
        }
    }
}

Running pretty much the same code with only node labels changed. However I received the following error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 23: Expected a step @ line 23, column 29.
                           try {
                           ^

Anybody has an idea what's wrong here?

Body:
Try to replace 'script' to 'steps', its work well in my side

stage('Test') {
parallel linux: {
    node('linux') {
        script {
            checkout scm
            try {
                unstash 'app'
                sh 'make check'
            }
            finally {
                junit '**/target/*.xml'
            }
      }
    }
}

}


问:
Submit form is not triggger in jquery
Here is the form:

```<code><form name="frmSelect" id="frmSelect" method="post" action="./abc.php">
  <input type="submit" value="To Confirm" name="To-Confirm" />
  <span>Click</span>
</form>
</code>```

Jquery:

```<code>span.onclick = function() {
  alert($('#frmSelect').length);

  $('#frmSelect').submit(function() {
    alert('abc');
    //var data = $("#frmSelect :input").serializeArray();
    //alert('Handler for .submit() called.');
    //OR
    //document.frmSelect.submit(); <-- Not Working Too
    //var x = document.getElementsByName("To-Confirm").value; <-- Always "undefined".
  });
}
</code>```

When I clicked on a  element, I am able to get the first alert with "1" (the length of form), but I am not able to get the second alert (which is abc).

p.s. there are many form elements but different name.

答:
I think you shouldn't do it this way.
Declare the comportement for the submit() function, and then raise the event submit as below...

```<code>$('#frmSelect').submit(function() {
    alert('abc');
});

span.onclick = function() {
    alert($('#frmSelect').length);
    $('#frmSelect').submit();
}
</code>```

my 2 cents ;)

regards.

Title: Submit form is not triggger in jquery

Body:
Here is the form:

<form name="frmSelect" id="frmSelect" method="post" action="./abc.php">
  <input type="submit" value="To Confirm" name="To-Confirm" />
  Click
</form>

Jquery:

span.onclick = function() {
  alert($('#frmSelect').length);

  $('#frmSelect').submit(function() {
    alert('abc');
    //var data = $("#frmSelect :input").serializeArray();
    //alert('Handler for .submit() called.');
    //OR
    //document.frmSelect.submit(); <-- Not Working Too
    //var x = document.getElementsByName("To-Confirm").value; <-- Always "undefined".
  });
}

When I clicked on a  element, I am able to get the first alert with "1" (the length of form), but I am not able to get the second alert (which is abc).

p.s. there are many form elements but different name.

Body:
I think you shouldn't do it this way.
Declare the comportement for the submit() function, and then raise the event submit as below...

$('#frmSelect').submit(function() {
    alert('abc');
});

span.onclick = function() {
    alert($('#frmSelect').length);
    $('#frmSelect').submit();
}

my 2 cents ;)

regards.


问:
How can I disable jobs in the Quartz JDBCJobStore?
What is the best way to disable a job in the JDBCJobStore without deleting it's job or trigger records and without wiping the cron expression?</p>

答: Use the pauseJob or pauseJobGroup methods of JobStore.


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

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

Would you rewrite everything?

Would you refactor piece per piece?

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

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

Thanks

答:
I would try to rewrite the parts that just don't seem to work or are the most difficult to understand.

Try to let your team explain the code, they made it, so they know how it works :)
If there are any problems ask them they might sure know how to solve them.

Errors are also made by humans, but we try to learn from it..


问:
Android displaying textView instead of toast only showing last part of toast
I am already able to show the json splitted nicely in an toast like this:
Key: Value
Key: Value

Defining the textview in the public class:

```<code>private TextView resultaat;
</code>```

This is the declaration of my TextView:

```<code>resultaat = (TextView) findViewById(R.id.resultaat);
</code>```

This is the part where it make's the toast(s) and now the setText of the textView:

```<code>public void parseJson (String jsonString) throws JSONException{
    Toast.makeText(this, jsonString, Toast.LENGTH_LONG).show();
    JSONObject obj=new JSONObject(jsonString);
    //Getting all the keys inside json object with key- pages
    Iterator<String> keys= obj.keys();
    while (keys.hasNext())
    {
        String keyValue = (String)keys.next();
        Toast.makeText(this, keyValue+":"+obj.getString(keyValue), Toast.LENGTH_LONG).show();
        resultaat.setText(keyValue+":"+obj.getString(keyValue));
    }

}
</code>```

What i want it now just as it does with the toast show everytime key: value but with this line of code:

```<code>resultaat.setText(keyValue+":"+obj.getString(keyValue));
</code>```

it only displays the last key: value of the json how can i make it that it will show all the key: value like the toast?

BTW this is an old post so dont watch the comments!!

答:
Update your code like this</p>

```<code>while (keys.hasNext())
{
    String keyValue = (String)keys.next();
    Toast.makeText(this, keyValue+":"+obj.getString(keyValue), Toast.LENGTH_LONG).show();
    resultaat.setText( resultaat.getText().toString()+ keyValue+":"+obj.getString(keyValue));
}
</code>```

Body:
I am already able to show the json splitted nicely in an toast like this:
Key: Value
Key: Value

Defining the textview in the public class:

private TextView resultaat;

This is the declaration of my TextView:

resultaat = (TextView) findViewById(R.id.resultaat);

This is the part where it make's the toast(s) and now the setText of the textView:

public void parseJson (String jsonString) throws JSONException{
    Toast.makeText(this, jsonString, Toast.LENGTH_LONG).show();
    JSONObject obj=new JSONObject(jsonString);
    //Getting all the keys inside json object with key- pages
    Iterator<String> keys= obj.keys();
    while (keys.hasNext())
    {
        String keyValue = (String)keys.next();
        Toast.makeText(this, keyValue+":"+obj.getString(keyValue), Toast.LENGTH_LONG).show();
        resultaat.setText(keyValue+":"+obj.getString(keyValue));
    }

}

What i want it now just as it does with the toast show everytime key: value but with this line of code:

resultaat.setText(keyValue+":"+obj.getString(keyValue));

it only displays the last key: value of the json how can i make it that it will show all the key: value like the toast?

BTW this is an old post so dont watch the comments!!

Body:
Update your code like this

while (keys.hasNext())
{
    String keyValue = (String)keys.next();
    Toast.makeText(this, keyValue+":"+obj.getString(keyValue), Toast.LENGTH_LONG).show();
    resultaat.setText( resultaat.getText().toString()+ keyValue+":"+obj.getString(keyValue));
}


问:
NSString with XML to NSArray with NSDictionary
I have a small problem I can't seem to solve. I have a XML page with the following content:

```<code><?xml version="1.0" encoding="utf-8"?>
<ArrayOfCategory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://api.tradera.com">
  <Category Id="1612" Name="Category 1">
    <Category Id="161213" Name="Category 1 subcat 1">
      <Category Id="340761" Name="Category 1, subcat 1, subcat 1" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 2" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 3" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 4" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 5" />
    </Category>
    <Category Id="161213" Name="Category 1 subcat 2"></category>
    <Category Id="161213" Name="Category 1 subcat 3">
      <Category Id="340761" Name="Category 1, subcat 3, subcat 1" />
    </category>
  </Category>
  <Category Id="1612" Name="Category 1">
    [...]
  </category>
</ArrayOfCategory>
</code>```

What I want to do is to convert this into an array with dictionaries.
So, this sould be an array with key 0 = dictorionary with items Id, Name and subcats. Subcats should be an array with the same keys.

So far I have the following code:

```<code>- (void)viewDidLoad
{
    [super viewDidLoad];

    [self startParsing];
}

- (void)startParsing {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"categories" ofType:@"xml"];

    NSData *xmlData = [[NSData alloc] initWithContentsOfFile:path];
    NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:xmlData] autorelease];
    [parser setDelegate:self];
    [parser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    NSLog(@"Started %@, attribute: %@", elementName, attributeDict);
}
</code>```

But I can't seem to figure out how to create this array using NSXMLParser, any suggestions?

Best regards,
Paul Peelen

答:
A little lib allowing you to easily convert XML to NSDictionary:

https://github.com/bcaccinolo/XML-to-NSDictionary

Have fun !

Body:
I have a small problem I can't seem to solve. I have a XML page with the following content:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCategory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://api.tradera.com">
  <Category Id="1612" Name="Category 1">
    <Category Id="161213" Name="Category 1 subcat 1">
      <Category Id="340761" Name="Category 1, subcat 1, subcat 1" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 2" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 3" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 4" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 5" />
    </Category>
    <Category Id="161213" Name="Category 1 subcat 2"></category>
    <Category Id="161213" Name="Category 1 subcat 3">
      <Category Id="340761" Name="Category 1, subcat 3, subcat 1" />
    </category>
  </Category>
  <Category Id="1612" Name="Category 1">
    [...]
  </category>
</ArrayOfCategory>

What I want to do is to convert this into an array with dictionaries.
So, this sould be an array with key 0 = dictorionary with items Id, Name and subcats. Subcats should be an array with the same keys.

So far I have the following code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self startParsing];
}

- (void)startParsing {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"categories" ofType:@"xml"];

    NSData *xmlData = [[NSData alloc] initWithContentsOfFile:path];
    NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:xmlData] autorelease];
    [parser setDelegate:self];
    [parser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    NSLog(@"Started %@, attribute: %@", elementName, attributeDict);
}

But I can't seem to figure out how to create this array using NSXMLParser, any suggestions?

Best regards,
Paul Peelen


问:
calculation of month as per Julian Calendar
I'm a beginner in QT C++, and I'm trying to print Julian day on a label_j with respect the value mentioned in array list. I'm unable to do that. Please could you see and correct it. Thanks a lot in advance.

Current month is been fetch from the UTC,
  if month equal jan then print 0,
  month equal then print 31,
  month equal  March then print 59 and so on until it reach December.

```<code>void MainWindow::getJulianDay()
</code>```

{

```<code>  int month_arr[]={0,31,59,90,120,151,181,212,243,273,304,334};
  QString January, February, March, April, May, June, July, August, September, October, November, December;

  QDateTime local(QDateTime::currentDateTimeUtc());
QDateTime UTC(local.toUTC());
QString month=UTC.toString("MMMM");

switch (month)
{

    case January:
        month=month_arr[0];
        break;
    case February:
         month=month_arr[1];
        break;
    case March:
        month=month_arr[2];
        break;
    case April:
        month=month_arr[3];
        break;
    case May:
        month=month_arr[4];
        break;
    case June:
        month=month_arr[5];
        break;
    case July:
        month=month_arr[6];
        break;
    case August:
        month=month_arr[7];
        break;
    case September:
        month=month_arr[8];
        break;
    case October:
        month=month_arr[9];
        break;
    case November:
        month=month_arr[10];
        break;
    case December:
        month=month_arr[11];
        break;
    default: month=invalid;
    break;

    ui->label_j->setText(month);

}
</code>```

答:
I see two main mistakes :

First of all, your case statement conditions are empty. You should do :

```<code>switch(variable) {
    case condition1:
        ...
        break;
    case condition2:
        ...
        break;

    ...

    default:
        ...
        break;
}
</code>```

So, your code becomes :

```<code>switch (month);
{
    case 1:
        month="January";
        answer=month_arr[0];
        break;
    case 2:
        month="February";
        answer=month_arr[1];
        break;

    ...

    default:
        month="invalid";
        break;
}
</code>```

The second main problem is that ui->label_j->setText(answer); should be out of the switch loop. As it is currently, this statement will never be executed.

Edit : As noticed by m7913d, you have a lot of type errors. Review the type of your variables !

Body:
I'm a beginner in QT C++, and I'm trying to print Julian day on a label_j with respect the value mentioned in array list. I'm unable to do that. Please could you see and correct it. Thanks a lot in advance.

Current month is been fetch from the UTC,
  if month equal jan then print 0,
  month equal then print 31,
  month equal  March then print 59 and so on until it reach December.

void MainWindow::getJulianDay()

{

  int month_arr[]={0,31,59,90,120,151,181,212,243,273,304,334};
  QString January, February, March, April, May, June, July, August, September, October, November, December;

  QDateTime local(QDateTime::currentDateTimeUtc());
QDateTime UTC(local.toUTC());
QString month=UTC.toString("MMMM");

switch (month)
{

    case January:
        month=month_arr[0];
        break;
    case February:
         month=month_arr[1];
        break;
    case March:
        month=month_arr[2];
        break;
    case April:
        month=month_arr[3];
        break;
    case May:
        month=month_arr[4];
        break;
    case June:
        month=month_arr[5];
        break;
    case July:
        month=month_arr[6];
        break;
    case August:
        month=month_arr[7];
        break;
    case September:
        month=month_arr[8];
        break;
    case October:
        month=month_arr[9];
        break;
    case November:
        month=month_arr[10];
        break;
    case December:
        month=month_arr[11];
        break;
    default: month=invalid;
    break;

    ui->label_j->setText(month);

}

Body:
I see two main mistakes :

First of all, your case statement conditions are empty. You should do :

switch(variable) {
    case condition1:
        ...
        break;
    case condition2:
        ...
        break;

    ...

    default:
        ...
        break;
}

So, your code becomes :

switch (month);
{
    case 1:
        month="January";
        answer=month_arr[0];
        break;
    case 2:
        month="February";
        answer=month_arr[1];
        break;

    ...

    default:
        month="invalid";
        break;
}

The second main problem is that ui->label_j->setText(answer); should be out of the switch loop. As it is currently, this statement will never be executed.

Edit : As noticed by m7913d, you have a lot of type errors. Review the type of your variables !


问:
jQuery-File-Upload used in IE8: cannot get response
I will give my code first.

```<code>$("#file-upload").fileupload({
        url: "/api/org/importOrg", //I get send the data to this url and expect to get response

        add: function(e, data) {
               //some operation here

                $("#file-upload").fileupload({
                    formData: {
                        name: $("#fileInput").val()
                    }
                });
                console.log('before submit');//log: before submit
                data.submit();
                console.log("after submit");
            });
        },
        done: function(e, rep) {
            console.log("done"); //log nothing
            var myResult=JSON.parse(rep.result);
       //some unimportant operation here
        },
        fail: function() {
            console.log("fail");//log nothing

            //some unimportant operation
        }
    });
</code>```

Firstly, I have to tell that I have made this program run successfully on IE9+ and other modern browsers but fail on IE8.  Although the code doesn't make any error on IE8.

And this bug is not the famous bug about downloading response of json formating on IE browsers.( I have solved that problem in IE9.) Because I can't see network response in IE8 at all.

This is the screenshot of IE8's network which is achieved by IE11's emulation.
I can only see the response of  'loading.gif'

enter image description here

I expect to see the response in the picture below which exists in Chrome and IE9+.

enter image description here

And from the result this program logs, we can see that  none of function done and fail is executed.

Thanks a lot for paying attention to my question.

答:
I am the person who ask the question.

In fact, the key is my code of HTML. Below is my HTML code which cause the problem.

```<code><button class="btn btn-icon btn-blue" style="width:90px;height:32px" onclick="$(this).next().click()">
    <span class="icon-zcy icon-shangchuan mr" style="height:20px"></span>Upload
</button>
<input type="file" name="files" style="display:none" class="btn-upload" id="file-upload" >
</code>```

We can see from the code that  input[type='file'] is clicked through click event of button. And the input[type='file'] is hidden.

This method is widely used because it's difficult to customize input[type='file']. This method can help us avoid this question.

However this trick can't work in IE8 because of one security restrict in IE8.

IE doesn't allow manipulation of the type="file" input element from javascript due to security reasons. Setting the filename or invoking a click event to show the browser dialog will result in an "Access is denied" error on the form submit.

So it doesn't work in IE8.

I have found the solution from a Chinese blog. I'll give the solution here.

HTML code

```<code><div class="uploadFile">
     <input type="text" class="input input-medium" id="fileInput">
     <span>
        <a href="javascript:void(0)" class="btn btn-icon btn-blue"  > <span class="icon-zcy icon-shangchuan mr" style="height:20px"></span>上传</a>
        <input type="file" name="files" class="btn-upload" id="file-upload" >
     </span>
 </div>
</code>```

sass code

```<code>.uploadFile{
    span{
        position: relative;
        display: inline-block;
    }
    #file-upload { //
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        right: 0;
        opacity: 0;
        filter: alpha(opacity=0);//works in IE
    }
}
</code>```

The principle of the question: It seems like you click the button but in fact you click the input[type='file']. And you avoid customizing the input[type='file'].

This is my question.

ContentLicense: CC BY-SA 4.0

Body:
I will give my code first.

$("#file-upload").fileupload({
        url: "/api/org/importOrg", //I get send the data to this url and expect to get response

        add: function(e, data) {
               //some operation here

                $("#file-upload").fileupload({
                    formData: {
                        name: $("#fileInput").val()
                    }
                });
                console.log('before submit');//log: before submit
                data.submit();
                console.log("after submit");
            });
        },
        done: function(e, rep) {
            console.log("done"); //log nothing
            var myResult=JSON.parse(rep.result);
       //some unimportant operation here
        },
        fail: function() {
            console.log("fail");//log nothing

            //some unimportant operation
        }
    });

Firstly, I have to tell that I have made this program run successfully on IE9+ and other modern browsers but fail on IE8.  Although the code doesn't make any error on IE8.

And this bug is not the famous bug about downloading response of json formating on IE browsers.( I have solved that problem in IE9.) Because I can't see network response in IE8 at all.

This is the screenshot of IE8's network which is achieved by IE11's emulation.
I can only see the response of  'loading.gif'

enter image description here

I expect to see the response in the picture below which exists in Chrome and IE9+.

enter image description here

And from the result this program logs, we can see that  none of function done and fail is executed.

Thanks a lot for paying attention to my question.

Body:
I am the person who ask the question.

In fact, the key is my code of HTML. Below is my HTML code which cause the problem.

<button class="btn btn-icon btn-blue" style="width:90px;height:32px" onclick="$(this).next().click()">
    <span class="icon-zcy icon-shangchuan mr" style="height:20px"></span>Upload
</button>
<input type="file" name="files" style="display:none" class="btn-upload" id="file-upload" >

We can see from the code that  input[type='file'] is clicked through click event of button. And the input[type='file'] is hidden.

This method is widely used because it's difficult to customize input[type='file']. This method can help us avoid this question.

However this trick can't work in IE8 because of one security restrict in IE8.

IE doesn't allow manipulation of the type="file" input element from javascript due to security reasons. Setting the filename or invoking a click event to show the browser dialog will result in an "Access is denied" error on the form submit.

So it doesn't work in IE8.

I have found the solution from a Chinese blog. I'll give the solution here.

HTML code

<div class="uploadFile">
     <input type="text" class="input input-medium" id="fileInput">
     <span>
        <a href="javascript:void(0)" class="btn btn-icon btn-blue"  > <span class="icon-zcy icon-shangchuan mr" style="height:20px"></span>上传</a>
        <input type="file" name="files" class="btn-upload" id="file-upload" >
     </span>
 </div>

sass code

.uploadFile{
    span{
        position: relative;
        display: inline-block;
    }
    #file-upload { //
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        right: 0;
        opacity: 0;
        filter: alpha(opacity=0);//works in IE
    }
}

The principle of the question: It seems like you click the button but in fact you click the input[type='file']. And you avoid customizing the input[type='file'].

This is my question.


问:
Shebang and Groovy
Is it possible to declare at the start of a file that it should be executed as a Groovy script?

Examples for other scripting languages:

```<code>#!/bin/sh
#!/usr/bin/python
#!/usr/bin/perl
</code>```

答:
A common trick is to write a script that has meaning in more than one language, also known as a "polyglot" script.

In the case of Bash and Groovy, this is particularly easy:

```<code>#!/bin/sh
//bin/true; exec groovy -cp .. "$0"

println "Hello from Groovy"
</code>```

The first line is a shebang (#!) that tells the OS to run the script as a regular shell script.

The second line, when executed by the shell, invokes the /bin/true command (a no-op); then finds the groovy executable in the PATH and runs it on the script file itself ("$0") plus additional arguments, replacing the current shell process (exec)

Groovy will ignore the first line, because it's a shebang; it will ignore the second line because it's a comment (//) and will run the rest of the script.

If you need a more elaborate shell part, maybe to set up environment variables, or discover where Groovy is installed, you can use a different trick:

```<code>#!/bin/sh
'''':
echo Hello from Shell
exec groovy -cp .. "$0"
'''

println "Hello from Groovy"
</code>```

Again, the shebang signals the OS to start executing this files as a shell script.

The shell parses '''': as two empty strings '' followed by a colon, which is a no-op.

The shell will execute the rest of the file, line by line, until it find an exec or an exit

If everything is ok, the shell will run the Groovy command on the script file itself ("$0")

Groovy will skip the shebang line, then it will parse '''': as the beginning of a long string ''', thus skipping all the shell commands, and then run the rest of the script.

Title: Shebang and Groovy

Body:
Is it possible to declare at the start of a file that it should be executed as a Groovy script?

Examples for other scripting languages:

#!/bin/sh
#!/usr/bin/python
#!/usr/bin/perl

Body:
A common trick is to write a script that has meaning in more than one language, also known as a "polyglot" script.

In the case of Bash and Groovy, this is particularly easy:

#!/bin/sh
//bin/true; exec groovy -cp .. "$0"

println "Hello from Groovy"

The first line is a shebang (#!) that tells the OS to run the script as a regular shell script.

The second line, when executed by the shell, invokes the /bin/true command (a no-op); then finds the groovy executable in the PATH and runs it on the script file itself ("$0") plus additional arguments, replacing the current shell process (exec)

Groovy will ignore the first line, because it's a shebang; it will ignore the second line because it's a comment (//) and will run the rest of the script.

If you need a more elaborate shell part, maybe to set up environment variables, or discover where Groovy is installed, you can use a different trick:

#!/bin/sh
'''':
echo Hello from Shell
exec groovy -cp .. "$0"
'''

println "Hello from Groovy"

Again, the shebang signals the OS to start executing this files as a shell script.

The shell parses '''': as two empty strings '' followed by a colon, which is a no-op.

The shell will execute the rest of the file, line by line, until it find an exec or an exit

If everything is ok, the shell will run the Groovy command on the script file itself ("$0")

Groovy will skip the shebang line, then it will parse '''': as the beginning of a long string ''', thus skipping all the shell commands, and then run the rest of the script.