问:
Golang Decode a BSON with special character Keys to a struct
I have a Golang struct called Person where all the properties have to be exported:

```<code>type Person struct {
    Id         string
    Name       string
}
</code>```

Now I need to encode my MongoDB BSON response to this Person struct.  The BSON looks like:

```<code>{
  "_id": "ajshJSH78N",
  "Name": "Athavan Kanapuli"
}
</code>```

The Golang code to encode the BSON is:

```<code>    mongoRecord := Person{}
    c := response.session.DB("mydb").C("users")
    err := c.Find(bson.M{"username": Credentials.Username, "password": Credentials.Password}).One(&mongoRecord)
</code>```

The Problem:

_id is not getting encoded into Id

If I change the Person property into _Id, then it won't be exported.

How can I solve this problem?

答:
Define your struct with json tag-

```<code>type Person struct {
    Id         string   `json:"_id"`
    Name       string  // this field match with json, so mapping not need
}
</code>```

Body:
I have a Golang struct called Person where all the properties have to be exported:

type Person struct {
    Id         string
    Name       string
}

Now I need to encode my MongoDB BSON response to this Person struct.  The BSON looks like:

{
  "_id": "ajshJSH78N",
  "Name": "Athavan Kanapuli"
}

The Golang code to encode the BSON is:

    mongoRecord := Person{}
    c := response.session.DB("mydb").C("users")
    err := c.Find(bson.M{"username": Credentials.Username, "password": Credentials.Password}).One(&mongoRecord)

The Problem:

_id is not getting encoded into Id

If I change the Person property into _Id, then it won't be exported.

How can I solve this problem?

Body:
Define your struct with json tag-

type Person struct {
    Id         string   `json:"_id"`
    Name       string  // this field match with json, so mapping not need
}


来源: stackexchange

问:
Ember app cannot load json data from local file
I have been following the ember quick start guide to create an app that displays some data (https://guides.emberjs.com/v2.13.0/getting-started/quick-start/) but instead of displaying just a javascript array with scientists names, I want to display the products from the following json.

I have placed the json file in the public folder.

It looks like:

```<code>{
  "products": [
    {
      "_id": "58ff60ffcd082f040072305a",
      "slug": "apple-tree-printed-linen-butterfly-bow-tie",
      "name": "Apple Tree Printed Linen Butterfly Bow Tie ",
      "description": "This fun 40 Colori Apple Tree Printed Linen Butterfly Bow Tie features a design of various apple trees built from tiny polka dots. The back of this bow tie features a polka dot print in complementing colours which when the bow tie is tied will pop out from behind making for a subtle yet unique detail. The playful design, stand out natural linen texture, and colourful combinations make this bow tie a perfect accessory for any outfit!\n",
      "standard_manufacturer": "58cbafc55491430300c422ff",
      "details": "Size: Untied (self-tie) bow tie with an easily adjustable neck strap from 13-3/4'' to 19'' (35 to 48 cm)\nHeight: 6 cm\nMaterial: Printed 100% linen\nCare: Dry clean\nMade in Italy",
      "sizes": [
        {
          "value": "Violet",
          "size": "57722c80c8595b0300a11e61",
          "_id": "58ff60ffcd082f0400723070",
          "marked_as_oos_at": null,
          "quantity": -1,
          "stock": true,
          "id": "58ff60ffcd082f0400723070"
        },
</code>```

and so on.

My code for the model of the route for displaying the list is as follows

```<code>import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        //return ['Marie Curie', 'Mae Jemison', 'Albert Hofmann'];
        return Ember.$.getJSON("/products.json");
    }
});
</code>```

I have followed the tutorial exactly except for the

```<code>return Ember.$.getJSON("/products.json");
</code>```

line in scientists.js. My data is not being displayed and the error i get in the ember inspector is

```<code>compiled.js:2 Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
    at E (compiled.js:2)
    at Object.u (compiled.js:25)
    at compiled.js:25
E   @   compiled.js:2
u   @   compiled.js:25
(anonymous) @   compiled.js:25
</code>```

I am very new with ember and fairly new with js. Any help appreciated! Thanks!

答:
Ember comes with Development server(localhost:4200) and it can't be used like a webserver and it can't be used to response ajax request. You can't make this work Ember.$.getJSON("/products.json") with localhost:4200 endpoint.

You need backend any webserver to return response. If you don't have that at present then for development purpose, you need to work with dynamic render data,
then I prefer to use ember-cli-mirage addon.

http://www.ember-cli-mirage.com/docs/v0.3.x/

ContentLicense: CC BY-SA 3.0

Body:
I have been following the ember quick start guide to create an app that displays some data (https://guides.emberjs.com/v2.13.0/getting-started/quick-start/) but instead of displaying just a javascript array with scientists names, I want to display the products from the following json.

I have placed the json file in the public folder.

It looks like:

{
  "products": [
    {
      "_id": "58ff60ffcd082f040072305a",
      "slug": "apple-tree-printed-linen-butterfly-bow-tie",
      "name": "Apple Tree Printed Linen Butterfly Bow Tie ",
      "description": "This fun 40 Colori Apple Tree Printed Linen Butterfly Bow Tie features a design of various apple trees built from tiny polka dots. The back of this bow tie features a polka dot print in complementing colours which when the bow tie is tied will pop out from behind making for a subtle yet unique detail. The playful design, stand out natural linen texture, and colourful combinations make this bow tie a perfect accessory for any outfit!\n",
      "standard_manufacturer": "58cbafc55491430300c422ff",
      "details": "Size: Untied (self-tie) bow tie with an easily adjustable neck strap from 13-3/4'' to 19'' (35 to 48 cm)\nHeight: 6 cm\nMaterial: Printed 100% linen\nCare: Dry clean\nMade in Italy",
      "sizes": [
        {
          "value": "Violet",
          "size": "57722c80c8595b0300a11e61",
          "_id": "58ff60ffcd082f0400723070",
          "marked_as_oos_at": null,
          "quantity": -1,
          "stock": true,
          "id": "58ff60ffcd082f0400723070"
        },

and so on.

My code for the model of the route for displaying the list is as follows

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        //return ['Marie Curie', 'Mae Jemison', 'Albert Hofmann'];
        return Ember.$.getJSON("/products.json");
    }
});

I have followed the tutorial exactly except for the

return Ember.$.getJSON("/products.json");

line in scientists.js. My data is not being displayed and the error i get in the ember inspector is

compiled.js:2 Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
    at E (compiled.js:2)
    at Object.u (compiled.js:25)
    at compiled.js:25
E   @   compiled.js:2
u   @   compiled.js:25
(anonymous) @   compiled.js:25

I am very new with ember and fairly new with js. Any help appreciated! Thanks!


问:
Kafka - Producer Acknowledgement
I saw in a video tutorial that Kafka Broker supports 3 types of acknowledgement when producer posts a message.

0 - Fire and Forget

1 - Leader Ack

2 - Ack of all the brokers

I am using Kafka's Java API to post message. Is this something that has to be set for each broker using server.properties specific to each broker or is it something that has to be set by producer? If it has to be set by the producer , please explain how it can be set using Java API.

```<code>import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;

public class KafkaProducerApp {

    public static void main(String[] args){
        Properties properties = new Properties();
        properties.put("bootstrap.servers","localhost:9092,localhost:9093,localhost:9094");
        properties.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer<String,String> kafkaProducer = new KafkaProducer<String, String>(properties);

        try{
            for(int i=0;i<150;i++) {
                RecordMetadata ack = kafkaProducer.send(new ProducerRecord<String, String>("replicated_topic", Integer.toString(i), "MyMessage" + Integer.toString(i))).get();
                System.out.println(" Offset = " + ack.offset());
                System.out.println(" Partition = " + ack.partition());
            }
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            kafkaProducer.close();
        }

    }

}
</code>```

答:
It's a producer property and is set similar to other properties you have in your code:

```<code>properties.put("acks","all");
</code>```

The list of all configurable producer properties can be found here.

You might want to also look at the broker (or topic) property min.insync.replicas that is related to this producer config.

ContentLicense: CC BY-SA 4.0

Title: Kafka - Producer Acknowledgement

Body:
I saw in a video tutorial that Kafka Broker supports 3 types of acknowledgement when producer posts a message.

0 - Fire and Forget

1 - Leader Ack

2 - Ack of all the brokers

I am using Kafka's Java API to post message. Is this something that has to be set for each broker using server.properties specific to each broker or is it something that has to be set by producer? If it has to be set by the producer , please explain how it can be set using Java API.

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;

public class KafkaProducerApp {

    public static void main(String[] args){
        Properties properties = new Properties();
        properties.put("bootstrap.servers","localhost:9092,localhost:9093,localhost:9094");
        properties.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer<String,String> kafkaProducer = new KafkaProducer<String, String>(properties);

        try{
            for(int i=0;i<150;i++) {
                RecordMetadata ack = kafkaProducer.send(new ProducerRecord<String, String>("replicated_topic", Integer.toString(i), "MyMessage" + Integer.toString(i))).get();
                System.out.println(" Offset = " + ack.offset());
                System.out.println(" Partition = " + ack.partition());
            }
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            kafkaProducer.close();
        }

    }

}

Body:
It's a producer property and is set similar to other properties you have in your code:

properties.put("acks","all");

The list of all configurable producer properties can be found here.

You might want to also look at the broker (or topic) property min.insync.replicas that is related to this producer config.


问:
Django problem: problem with choice fields
I seem to have problem in Django when looking for a field which has a choice parameter. I do not get the field name but instead I get the number for some odd reason.

My forms.py:

```<code>from django import forms

CONTRACT_TYPE_CHOICES = (
                 (1, 'Annual'),
                 (2, 'Ad-hoc'),
                 )

CONTRACT_STATUS_CHOICES = (
  (1, 'Active'),
  (2, 'In-Active'),
  )

class ContractForm(forms.ModelForm):
  contract_type = forms.ChoiceField(choices=CONTRACT_TYPE_CHOICES)
  contract_status = forms.ChoiceField(choices=CONTRACT_STATUS_CHOICES)

  class Meta:
    model = Contract
</code>```

In my template. I have the following

```<code>{% for contracts in contracts_list %}
  {{contracts.client_contract_number}}<br/>
  {{contracts.contract_type}}<br/>
  {{contracts.contract_status}}<br/>
{% endfor %}
</code>```

They all return a value. But contact_type and contract_status returns numbers. I do not to make it return numbers but the names. How do I do this?

答:
Model fields that take a choices kwarg automagically get a get_FIELD_NAME_display method. So for example, you could should put this in your template:

```<code>{{ contracts.get_contract_type_display }}
{{ contracts.get_contract_status_display }}
</code>```

See the documentation.

Good luck,
Justin

ContentLicense: CC BY-SA 2.5

Body:
I seem to have problem in Django when looking for a field which has a choice parameter. I do not get the field name but instead I get the number for some odd reason.

My forms.py:

from django import forms

CONTRACT_TYPE_CHOICES = (
                 (1, 'Annual'),
                 (2, 'Ad-hoc'),
                 )

CONTRACT_STATUS_CHOICES = (
  (1, 'Active'),
  (2, 'In-Active'),
  )

class ContractForm(forms.ModelForm):
  contract_type = forms.ChoiceField(choices=CONTRACT_TYPE_CHOICES)
  contract_status = forms.ChoiceField(choices=CONTRACT_STATUS_CHOICES)

  class Meta:
    model = Contract

In my template. I have the following

{% for contracts in contracts_list %}
  {{contracts.client_contract_number}}

  {{contracts.contract_type}}

  {{contracts.contract_status}}

{% endfor %}

They all return a value. But contact_type and contract_status returns numbers. I do not to make it return numbers but the names. How do I do this?

Body:
Model fields that take a choices kwarg automagically get a get_FIELD_NAME_display method. So for example, you could should put this in your template:

{{ contracts.get_contract_type_display }}
{{ contracts.get_contract_status_display }}

See the documentation.

Good luck,
Justin


问:
Add the same event handler to radio buttons and checkboxes
I am trying to have a function add the values of selected check boxes and radio buttons.  I have created a function that can add the values of the check boxes and a function for the radio buttons but am having trouble combining the two into one working function.  I think my issue is with having both radio and checkbox elements associated with the .click()

My code can be seen here:
https://jsfiddle.net/Buleria28/nz43u7x8/2/

The HTML is:

```<code><input type="checkbox" value="1" />test 1<br/>
<input type="checkbox" value="2" />test 2<br/>
<input type="checkbox" value="3" />test 3<br/>

<input type="radio" name="test" value="1" />test 4
<input type="radio" name="test" value="2" />test 5
<div id='sum'></div>
</code>```

The jQuery is:

```<code>jQuery(document).ready(function($) {
var sum = 0;

$("input:checkbox"),$("input:radio").click(function() {
   sum = 0;
    $("input:checkbox:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });

   sum = 0;
    $("input:radio:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });
    $('#sum').html(sum);
  });
});
</code>```

答:
You're actually using the comma operator and only adding the event handler to the second jQuery object. Instead combine the actual selectors by using a comma in the jQuery constructor's first argument, similar to a CSS selector:</p>

```<code>$("input:checkbox, input:radio").click(function() {
  …
});
</code>```

Body:
I am trying to have a function add the values of selected check boxes and radio buttons.  I have created a function that can add the values of the check boxes and a function for the radio buttons but am having trouble combining the two into one working function.  I think my issue is with having both radio and checkbox elements associated with the .click()

My code can be seen here:
https://jsfiddle.net/Buleria28/nz43u7x8/2/

The HTML is:

<input type="checkbox" value="1" />test 1

<input type="checkbox" value="2" />test 2

<input type="checkbox" value="3" />test 3

<input type="radio" name="test" value="1" />test 4
<input type="radio" name="test" value="2" />test 5

The jQuery is:

jQuery(document).ready(function($) {
var sum = 0;

$("input:checkbox"),$("input:radio").click(function() {
   sum = 0;
    $("input:checkbox:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });

   sum = 0;
    $("input:radio:checked").each(function(idx, elm) {
        sum += parseInt(elm.value, 10);
    });
    $('#sum').html(sum);
  });
});

Body:
You're actually using the comma operator and only adding the event handler to the second jQuery object. Instead combine the actual selectors by using a comma in the jQuery constructor's first argument, similar to a CSS selector:

$("input:checkbox, input:radio").click(function() {
  …
});


问:
range function with step size of power of 2 and increase number of zeros in tens position
Plot the performance of your program scale with N? For this, run your program multiple times and take the minimum time taken for a given value of N for the plot. You can use the value range of N = 10,20,40,80, 100, 200, 400, 800, 1000, 2000, 4000, 8000, 10000 and so on.
How can use the value range() of python for N = 10,20,40,80, 100, 200, 400, 800, 1000, 2000, 4000, 8000, 10000 and so on.

```<code>numbers_sizes = (i*exp for exp in range(2, 10,2) for i in range(10, 10000,10*2))
</code>```

but this not provide the required answer

答:
integer division and some modulo arithmetic

```<code>[10**(1+i//4)*2**(i%4) for i in range(15)]
Out[179]:
[10,
 20,
 40,
 80,
 100,
 200,
 400,
 800,
 1000,
 2000,
 4000,
 8000,
 10000,
 20000,
 40000]
</code>```

if you are really 'racing' and doing math with powers of 2 then sometimes binary ops are compiled slightly more compactly, may execute faster

```<code>import timeit
>>> timeit.timeit('[10**(1+i//4)*2**(i%4) for i in range(100)]', number=1000)
Out[197]: 0.06518084562951763

[10**(1+(i>>2))<<(i & 3) for i in range(15)]

timeit.timeit('[10**(1+(i>>2))<<(i & 3) for i in range(100)]', number=1000)
Out[199]: 0.04540084575825176
</code>```

Body:
Plot the performance of your program scale with N? For this, run your program multiple times and take the minimum time taken for a given value of N for the plot. You can use the value range of N = 10,20,40,80, 100, 200, 400, 800, 1000, 2000, 4000, 8000, 10000 and so on.
How can use the value range() of python for N = 10,20,40,80, 100, 200, 400, 800, 1000, 2000, 4000, 8000, 10000 and so on.

numbers_sizes = (i*exp for exp in range(2, 10,2) for i in range(10, 10000,10*2))

but this not provide the required answer

Body:
integer division and some modulo arithmetic

[10**(1+i//4)*2**(i%4) for i in range(15)]
Out[179]:
[10,
 20,
 40,
 80,
 100,
 200,
 400,
 800,
 1000,
 2000,
 4000,
 8000,
 10000,
 20000,
 40000]

if you are really 'racing' and doing math with powers of 2 then sometimes binary ops are compiled slightly more compactly, may execute faster

import timeit
>>> timeit.timeit('[10**(1+i//4)*2**(i%4) for i in range(100)]', number=1000)
Out[197]: 0.06518084562951763

[10**(1+(i>>2))<<(i & 3) for i in range(15)]

timeit.timeit('[10**(1+(i>>2))<<(i & 3) for i in range(100)]', number=1000)
Out[199]: 0.04540084575825176


问:
What is a nested loop and how do I use it in example below?
I was given the following problem for my beginning python coding class. I have reached out to the professor, but he hasn't gotten back to me and this is due in 3.5 hours. If someone has a tutorial/guidance of how to start, that would be amazing. I do NOT expect anyone to write this code! I just need a bit of guidance! Thanks :)

Write a program in Python to prompt user to enter an integer between 10 and 3 inclusive and also a character. Then use these two values to display a box using the character entered with size of box determined by the number entered.

Here is a sample output:

```<code>Enter size of box:  4

Enter a character: %

%%%%

%%%%

%%%%

%%%%
</code>```

Here is another possible output:

```<code>Enter size of box:  3

Enter a character: &

&&&

&&&

&&&
</code>```

Your program will run only once but you must used repetition construct to draw the box using values entered.

Hint: It should be a nested loop. Each line printed is a loop so you will have loop inside loop construct; nested loop.

As before, you must test for invalid values and if so, display an error message and proceed to get a valid number.

Use your own test values here.

答:
Solution

Let's break the problem down into steps.

First, we need to get an integer from the input, and make sure that the integer is either 3, 10, or any number in between. That's what 3 to 10 inclusive means.

We then need to ask a user for a single character that will be used to print a box.

After we've gotten the integer, and the character, we need to display a box made up of the character whose width and height are determined by the integer.

For step one, we need to get input from the user. This can be done using the builtin function input(). It takes an optionally prompt as an argument, and returns the input as a string. So let's write that down:

```<code>integer = input()
</code>```

Great. Now we need to convert the input to an integer, so it can be used in the rest of our program. This can be accomplished using the built-in function int(). We'll pass in your string, and it will convert it to an integer:

```<code>integer = int(input('Enter a number: '))
</code>```

Step two is to get a character from the user. That's easy. We'll use input() once again to get a single character from the user. but since the input need to be a character, we shouldn't convert this value:

```<code>character = input('Enter a character: ')
</code>```

Alright. This is what we have so far:

```<code>integer = int(input('Enter a number: '))
character = input('Enter a character: ')
</code>```

The last step is to print a box made of the value of character that has a width of integer and a height of integer. Now all we need to do is to print a row with integer number of characters integer number of times. This is where the nested for loop comes in.

We know each row must be the width of integer. So we need to print character that many times. We can use the range() built-in function to do this. We pass in integer as an argument, and it will generate all of the numbers from 0 to integer:

```<code>for _ in range(integer):
    print(character, end="")
</code>```

The the reason we used the underscore in our for loop instead of an actual readable variable name, is because we don't need to use the values that the for loops would give us. We only care about repeating our code.

The end="" part is  telling the print() builtin function not to print a newline each time it is called, because we want all the character to be in one row. The print() before the for loop is to add some space between our prompts and the program output. Let's see what our program outputs so far:

```<code>Enter a number: 5
Enter a character: @

@@@@@
>>>
</code>```

Great. The last thing to do is to print each row integer number of times. Since we know that executing the for loop above prints one row, we just need to execute it integer number of times to print integer rows. So we'll wrap that for loop inside of another for loop and use range() to execute the nested for loop integer number of times. We'll use print() once again, to add a newline between each row:

```<code>print()
for _ in range(integer):
    for _ in range(integer):
        print(character, end="")
    print()
</code>```

And that's it! Were done. Let's test our program:

```<code>Enter a number: 7
Enter a character: #

#######
#######
#######
#######
#######
#######
#######
>>>
</code>```

As you can see, we're getting our expected output. Here is the final program:

```<code>integer = int(input('Enter a number: '))
character = input('Enter a character: ')

print()
for _ in range(integer):
    for _ in range(integer):
        print(character, end="")
    print()
</code>```

Error handling

You may also need to implement error handling. This means making your program recover from the user entering invalid input. In this case, the only time invalid input could really be enetered is when we are asking the user for an integer. We need to:

make sure the user enetered a valid number. And

make sure that number is either 3, 10 or any number in between.

To do this, we'll need a loop. This is so we can continue to ask the user for valid input, until they do so. We can use a while True loop. This means we'll keep looping until we break from the loop.

```<code>while True:
</code>```

Now we need to make sure the user entered a valid number. We can use a try/except block. The way a try/except block works is that we put a block of code in the try portation that may raise an error. if no error is raised, we continue in the program normally. If an error is raised however, Python will jump to the except block and the code in there will be executed.

In our case we'll try to convert the users input to an integer. If this fails a ValueError will be raised. So we need to catch that error message and print it to the user:

```<code>integer = int(input('Enter a number: '))
</code>```0

All that's left is to test if the integer entered is in the correct range. If so, we'll break from our loop and continue with the program. If not, we'll display an error message and try again. Here is how that would look:

```<code>integer = int(input('Enter a number: '))
</code>```1

Here is how the above would look in the full program:

And here is a demo:

```<code>integer = int(input('Enter a number: '))
</code>```2

For more resources about error handling in a program, see the question: Asking the user for input until they give a valid response.

Body:
I was given the following problem for my beginning python coding class. I have reached out to the professor, but he hasn't gotten back to me and this is due in 3.5 hours. If someone has a tutorial/guidance of how to start, that would be amazing. I do NOT expect anyone to write this code! I just need a bit of guidance! Thanks :)

Write a program in Python to prompt user to enter an integer between 10 and 3 inclusive and also a character. Then use these two values to display a box using the character entered with size of box determined by the number entered.

Here is a sample output:

Enter size of box:  4

Enter a character: %

%%%%

%%%%

%%%%

%%%%

Here is another possible output:

Enter size of box:  3

Enter a character: &

&&&

&&&

&&&

Your program will run only once but you must used repetition construct to draw the box using values entered.

Hint: It should be a nested loop. Each line printed is a loop so you will have loop inside loop construct; nested loop.

As before, you must test for invalid values and if so, display an error message and proceed to get a valid number.

Use your own test values here.

Body:
Solution

Let's break the problem down into steps.

First, we need to get an integer from the input, and make sure that the integer is either 3, 10, or any number in between. That's what 3 to 10 inclusive means.

We then need to ask a user for a single character that will be used to print a box.

After we've gotten the integer, and the character, we need to display a box made up of the character whose width and height are determined by the integer.

For step one, we need to get input from the user. This can be done using the builtin function input(). It takes an optionally prompt as an argument, and returns the input as a string. So let's write that down:

integer = input()

Great. Now we need to convert the input to an integer, so it can be used in the rest of our program. This can be accomplished using the built-in function int(). We'll pass in your string, and it will convert it to an integer:

integer = int(input('Enter a number: '))

Step two is to get a character from the user. That's easy. We'll use input() once again to get a single character from the user. but since the input need to be a character, we shouldn't convert this value:

character = input('Enter a character: ')

Alright. This is what we have so far:

integer = int(input('Enter a number: '))
character = input('Enter a character: ')

The last step is to print a box made of the value of character that has a width of integer and a height of integer. Now all we need to do is to print a row with integer number of characters integer number of times. This is where the nested for loop comes in.

We know each row must be the width of integer. So we need to print character that many times. We can use the range() built-in function to do this. We pass in integer as an argument, and it will generate all of the numbers from 0 to integer:

for _ in range(integer):
    print(character, end="")

The the reason we used the underscore in our for loop instead of an actual readable variable name, is because we don't need to use the values that the for loops would give us. We only care about repeating our code.

The end="" part is  telling the print() builtin function not to print a newline each time it is called, because we want all the character to be in one row. The print() before the for loop is to add some space between our prompts and the program output. Let's see what our program outputs so far:

Enter a number: 5
Enter a character: @

@@@@@
>>>

Great. The last thing to do is to print each row integer number of times. Since we know that executing the for loop above prints one row, we just need to execute it integer number of times to print integer rows. So we'll wrap that for loop inside of another for loop and use range() to execute the nested for loop integer number of times. We'll use print() once again, to add a newline between each row:

print()
for _ in range(integer):
    for _ in range(integer):
        print(character, end="")
    print()

And that's it! Were done. Let's test our program:

Enter a number: 7
Enter a character: #

#######
#######
#######
#######
#######
#######
#######
>>>

As you can see, we're getting our expected output. Here is the final program:

integer = int(input('Enter a number: '))
character = input('Enter a character: ')

print()
for _ in range(integer):
    for _ in range(integer):
        print(character, end="")
    print()

Error handling

You may also need to implement error handling. This means making your program recover from the user entering invalid input. In this case, the only time invalid input could really be enetered is when we are asking the user for an integer. We need to:

make sure the user enetered a valid number. And

make sure that number is either 3, 10 or any number in between.

To do this, we'll need a loop. This is so we can continue to ask the user for valid input, until they do so. We can use a while True loop. This means we'll keep looping until we break from the loop.

while True:

Now we need to make sure the user entered a valid number. We can use a try/except block. The way a try/except block works is that we put a block of code in the try portation that may raise an error. if no error is raised, we continue in the program normally. If an error is raised however, Python will jump to the except block and the code in there will be executed.

In our case we'll try to convert the users input to an integer. If this fails a ValueError will be raised. So we need to catch that error message and print it to the user:

while True:
    try:
        integer = int(input())
    except ValueError:
        print('Please enter a number')

All that's left is to test if the integer entered is in the correct range. If so, we'll break from our loop and continue with the program. If not, we'll display an error message and try again. Here is how that would look:

while True:
    try:
        integer = int(input('Enter a number: '))
        if integer >= 3 and integer <= 10:
            break
        print('Please enter a number between 3 and 10 inclusive')
    except ValueError:
        print('Please enter a number')

character = input('Enter a character: ')

print()
for _ in range(integer):
    for _ in range(integer):
        print(character, end="")
    print()

Here is how the above would look in the full program:

And here is a demo:

Enter a number: -23
Please enter a number between 3 and 10 inclusive
Enter a number: a
Please enter a number
Enter a number: 11
Please enter a number between 3 and 10 inclusive
Enter a number: 10
Enter a character: #

##########
##########
##########
##########
##########
##########
##########
##########
##########
##########
>>>

For more resources about error handling in a program, see the question: Asking the user for input until they give a valid response.


问:
Please find the error in below written code for asp + JavaScript
```<code><script type=text/javascript>
function abc()
{
   return confirm('Are u sure');
}
</script>

<asp: Button id="btnSubmit" runat="server" onClick="btnSubmit_Click" onClientClick="abc" Text="Submit/>
</code>```

When I click the button the message box appears if I hit the cancel Button still the function for onClick is called instead it should not.
But if I write JavaScript code directly in the tag it works properly.

答:
```<code>onClientClick="return abc()"
</code>```

the return is the essential bit.

Body:
<asp: Button id="btnSubmit" runat="server" onClick="btnSubmit_Click" onClientClick="abc" Text="Submit/>

When I click the button the message box appears if I hit the cancel Button still the function for onClick is called instead it should not.
But if I write JavaScript code directly in the tag it works properly.

Body:
onClientClick="return abc()"

the return is the essential bit.


问:
What exactly are WordNet lexicographer files? Understanding how WordNet works
I'm trying to understand the file formats of the WordNet, and the main documents are WNDB and WNINPUT. As I understood in WNDB, there are the files called index.something and data.something, where this something can be noun, adv, vrb, adj.

So, if I want to know something about the word dog as a noun, I'd look into the index.noun, search for the word dog, which gives me the line:

```<code>dog n 7 5 @ ~ #m #p %p 7 1 02086723 10133978 10042764 09905672 07692347 03907626 02712903
</code>```

According to the WNDB documment, this line represents these data:

```<code>lemma  pos  synset_cnt  p_cnt  [ptr_symbol...]  sense_cnt  tagsense_cnt   synset_offset  [synset_offset...]
</code>```

Where lemma is the word, pos is the identifier that tells it's a noun, synset_cnt tells us in how many synsets this word is included, p_cnt tells us how many pointers to these synsets we have, [ptr_symbol] is an array of pointers, sense_cnt and tagsense_cnt I didn't understand and would like an explanation, and synset_offset is one or more synsets to be looked into the data.noun file

Ok, so I know those pointers point to something, and here are their descriptions, as written in WNINPUT:

```<code>@    Hypernym
 ~    Hyponym
#m    Member holonym
#p    Part holonym
%p    Part meronym
</code>```

I don't know how to find a Hypernym for this noun, but let's continue:

The other important data are the synset_offsets, which are:

```<code>02086723 10133978 10042764 09905672 07692347 03907626 02712903
</code>```

Let's look at the first one, 02086723, in data.noun:

```<code>02086723 05 n 03 dog 0 domestic_dog 0 Canis_familiaris 0 023 @ 02085998 n 0000 @ 01320032 n 0000 #m 02086515 n 0000 #m 08011383 n 0000 ~ 01325095 n 0000 ~ 02087384 n 0000 ~ 02087513 n 0000 ~ 02087924 n 0000 ~ 02088026 n 0000 ~ 02089774 n 0000 ~ 02106058 n 0000 ~ 02112993 n 0000 ~ 02113458 n 0000 ~ 02113610 n 0000 ~ 02113781 n 0000 ~ 02113929 n 0000 ~ 02114152 n 0000 ~ 02114278 n 0000 ~ 02115149 n 0000 ~ 02115478 n 0000 ~ 02115987 n 0000 ~ 02116630 n 0000 %p 02161498 n 0000 | a member of the genus Canis (probably descended from the common wolf) that has been domesticated by man since prehistoric times; occurs in many breeds; "the dog barked all night"
</code>```

As you can see, we've found the line that begins with 02086723. The contents of this line are described in WNDB as:

```<code>synset_offset  lex_filenum  ss_type  w_cnt  word  lex_id  [word  lex_id...]  p_cnt  [ptr...]  [frames...]  |   gloss
</code>```

synset_offset we already know,

lex_filenum says in which of the lexicographers file is our word (this is the part that I don't understand the most),

ss_type is n which tells us that it's a noun,

w_cnt: two digit hexadecimal integer indicating the number of words in the synset, which in this case is 03, which means we have 3 words in this synset: dog 0 domestic_dog 0 Canis_familiaris 0, each one followed by a number called:

lex_id: one digit hexadecimal integer that, when appended onto lemma , uniquely identifies a sense within a lexicographer file

```<code>p_cnt: counts the number of pointers, which in our case is `023`, so we have 23 pointers, wow
</code>```

After p_cnt, then comes the pointers, each one in the format:

```<code>pointer_symbol  synset_offset  pos  source/target
</code>```

Where pointer_symbol is about the symbols like the ones I showed (@, ~, ...),

synset_offset: is the byte offset of the target synset in the data file corresponding to pos

source/target: field distinguishes lexical and semantic pointers. It is a four byte field, containing two two-digit hexadecimal integers. The first two digits indicates the word number in the current (source) synset, the last two digits indicate the word number in the target synset. A value of 0000 means that pointer_symbol represents a semantic relation between the current (source) synset and the target synset indicated by synset_offset .

Ok, so let's examine the first pointer:

```<code>@ 02085998 n 0000
</code>```

It's a pointer with symbol @, indicating it's a Hypernym, and points to the synset wiuth offset 02085998 of type n (noun), and source/target is 0000

When I search for  in data.noun, I get

```<code>02085998 05 n 02 canine 0 canid 0 011 @ 02077948 n 0000 #m 02085690 n 0000 + 02688440 a 0101 ~ 02086324 n 0000 ~ 02086723 n 0000 ~ 02116752 n 0000 ~ 02117748 n 0000 ~ 02117987 n 0000 ~ 02119787 n 0000 ~ 02120985 n 0000 %p 02442560 n 0000 | any of various fissiped mammals with nonretractile claws and typically long muzzles
</code>```

which is an Hypernym of dog. So that's how you find relations betweet synsets. I guess the pointer symbols in the line for dog were just to inform which types of relations I could find for the word dog? Isn't it redundant? Because these pointer symbols are already in each of the synset_offsets as we seen. When we look at each synset_offset in data.noun, we can see those pointer symbols, so why they're necessary in the index.noun file?

Also, see that I didn't use the lexicographers file at all. I know that in data.noun, specifically in the field lex_filenum, I can know where the data structure for dog is located, but what is this structure for? As you can see, I could find hypernym, and many other relations, just by looking at the index and data files, I didn't use any of the so called lexicographer files

答:
What is useful in this information is the relationship that exists between them, and (sometimes), the type of information. Everybody uses Wordnet! Some even link it to RDF notation. But...
I have used Wordnet a few years ago, as I wanted to build a hypertree of words, their superclass(es) and subclass(es), plus a few other types of relationships that are absent in WN, I had to drop Wordnet and its jargon.
I needed a 'less simplified' organization of "the real world". I came up with my own, with a mix of Wiktionary, lots of regular expressions, some YAGO, a few other ontologies that let me build hierarchies and other relationships, some ML. I have also looked at Roger Schank's classification, the Roget thesaurus, and various attempts to identify and classify (typologies) concepts, such as Wierzbicka's and other.
If you want something serious, diy.</p>

Body:
I'm trying to understand the file formats of the WordNet, and the main documents are WNDB and WNINPUT. As I understood in WNDB, there are the files called index.something and data.something, where this something can be noun, adv, vrb, adj.

So, if I want to know something about the word dog as a noun, I'd look into the index.noun, search for the word dog, which gives me the line:

dog n 7 5 @ ~ #m #p %p 7 1 02086723 10133978 10042764 09905672 07692347 03907626 02712903

According to the WNDB documment, this line represents these data:

lemma  pos  synset_cnt  p_cnt  [ptr_symbol...]  sense_cnt  tagsense_cnt   synset_offset  [synset_offset...]

Where lemma is the word, pos is the identifier that tells it's a noun, synset_cnt tells us in how many synsets this word is included, p_cnt tells us how many pointers to these synsets we have, [ptr_symbol] is an array of pointers, sense_cnt and tagsense_cnt I didn't understand and would like an explanation, and synset_offset is one or more synsets to be looked into the data.noun file

Ok, so I know those pointers point to something, and here are their descriptions, as written in WNINPUT:

@    Hypernym
 ~    Hyponym
#m    Member holonym
#p    Part holonym
%p    Part meronym

I don't know how to find a Hypernym for this noun, but let's continue:

The other important data are the synset_offsets, which are:

02086723 10133978 10042764 09905672 07692347 03907626 02712903

Let's look at the first one, 02086723, in data.noun:

02086723 05 n 03 dog 0 domestic_dog 0 Canis_familiaris 0 023 @ 02085998 n 0000 @ 01320032 n 0000 #m 02086515 n 0000 #m 08011383 n 0000 ~ 01325095 n 0000 ~ 02087384 n 0000 ~ 02087513 n 0000 ~ 02087924 n 0000 ~ 02088026 n 0000 ~ 02089774 n 0000 ~ 02106058 n 0000 ~ 02112993 n 0000 ~ 02113458 n 0000 ~ 02113610 n 0000 ~ 02113781 n 0000 ~ 02113929 n 0000 ~ 02114152 n 0000 ~ 02114278 n 0000 ~ 02115149 n 0000 ~ 02115478 n 0000 ~ 02115987 n 0000 ~ 02116630 n 0000 %p 02161498 n 0000 | a member of the genus Canis (probably descended from the common wolf) that has been domesticated by man since prehistoric times; occurs in many breeds; "the dog barked all night"

As you can see, we've found the line that begins with 02086723. The contents of this line are described in WNDB as:

synset_offset  lex_filenum  ss_type  w_cnt  word  lex_id  [word  lex_id...]  p_cnt  [ptr...]  [frames...]  |   gloss

synset_offset we already know,

lex_filenum says in which of the lexicographers file is our word (this is the part that I don't understand the most),

ss_type is n which tells us that it's a noun,

w_cnt: two digit hexadecimal integer indicating the number of words in the synset, which in this case is 03, which means we have 3 words in this synset: dog 0 domestic_dog 0 Canis_familiaris 0, each one followed by a number called:

lex_id: one digit hexadecimal integer that, when appended onto lemma , uniquely identifies a sense within a lexicographer file

p_cnt: counts the number of pointers, which in our case is `023`, so we have 23 pointers, wow

After p_cnt, then comes the pointers, each one in the format:

pointer_symbol  synset_offset  pos  source/target

Where pointer_symbol is about the symbols like the ones I showed (@, ~, ...),

synset_offset: is the byte offset of the target synset in the data file corresponding to pos

source/target: field distinguishes lexical and semantic pointers. It is a four byte field, containing two two-digit hexadecimal integers. The first two digits indicates the word number in the current (source) synset, the last two digits indicate the word number in the target synset. A value of 0000 means that pointer_symbol represents a semantic relation between the current (source) synset and the target synset indicated by synset_offset .

Ok, so let's examine the first pointer:

@ 02085998 n 0000

It's a pointer with symbol @, indicating it's a Hypernym, and points to the synset wiuth offset 02085998 of type n (noun), and source/target is 0000

When I search for  in data.noun, I get

02085998 05 n 02 canine 0 canid 0 011 @ 02077948 n 0000 #m 02085690 n 0000 + 02688440 a 0101 ~ 02086324 n 0000 ~ 02086723 n 0000 ~ 02116752 n 0000 ~ 02117748 n 0000 ~ 02117987 n 0000 ~ 02119787 n 0000 ~ 02120985 n 0000 %p 02442560 n 0000 | any of various fissiped mammals with nonretractile claws and typically long muzzles

which is an Hypernym of dog. So that's how you find relations betweet synsets. I guess the pointer symbols in the line for dog were just to inform which types of relations I could find for the word dog? Isn't it redundant? Because these pointer symbols are already in each of the synset_offsets as we seen. When we look at each synset_offset in data.noun, we can see those pointer symbols, so why they're necessary in the index.noun file?

Also, see that I didn't use the lexicographers file at all. I know that in data.noun, specifically in the field lex_filenum, I can know where the data structure for dog is located, but what is this structure for? As you can see, I could find hypernym, and many other relations, just by looking at the index and data files, I didn't use any of the so called lexicographer files


问:
Python flickrapi search.photos returns the same picture on every page
I'm testing the flickrapi for python and have some code that randomly chooses a picture of Chinese food. It does this by getting 1 result on 1 page and using the total number of pages in that result to choose 1 result on 1 random page. Here is the code I'm using to get the images:

```<code>flickr = flickrapi.FlickrAPI(api_key='mykey', secret='mysecret', format='parsed-json', cache=False)
data1 = flickr.photos.search(tags='Chinese Food',
                            page=1,
                            per_page=1,
                            tag_mode='all',
                            media='photos',
                            content_type=1)

data2 = flickr.photos.search(tags='Chinese Food',
                            page=randint(1, data1['photos']['pages']),
                            per_page=1,
                            tag_mode='all',
                            media='photos',
                            content_type=1,
                            extras='url_l')
</code>```

No matter what I do the result in data2 is always the exact same image returned in data1, I could get the first result from page 1 and the first result from page 3472 and the image is exactly the same every time.

Here is a sample of the data returned

```<code>//From data1
{'photos': {'page': 1, 'pages': 70007, 'perpage': 1, 'total': '70007', 'photo': [{'id': '35800805325', 'owner': '24171591@N06', 'secret': '408928a034', 'server': '4261', 'farm': 5, 'title': 'Personalized Maple Wood Chopsticks', 'ispublic': 1, 'isfriend': 0, 'isfamily': 0}]}, 'stat': 'ok'}

//From data2
{'photos': {'page': 41043, 'pages': 70007, 'perpage': 1, 'total': '70007', 'photo': [{'id': '35800805325', 'owner': '24171591@N06', 'secret': '408928a034', 'server': '4261', 'farm': 5, 'title': 'Personalized Maple Wood Chopsticks', 'ispublic': 1, 'isfriend': 0, 'isfamily': 0, 'url_l': 'https://farm5.staticflickr.com/4261/35800805325_408928a034_b.jpg', 'height_l': '859', 'width_l': '1024'}]}, 'stat': 'ok'}
</code>```

Notice the id and title in both sets of data are exactly the same and the page numbers are different. I've tested this in the Flickr API explorer with the exact same parameters and I do get the same image when I specify page 1 but I also get a completely different image if I specify any other page, so this seems to be an issue with the python flickrapi implementation or one of its dependencies maybe?

I can't seem to find the issue. What is going on?

答: Looks like other people have been having this issue with Flickr's API since 2011 and it still hasn't been fixed. So, it doesn't seem to be related to Python or the Python Flickr module. I was able to improve the "randomness" by increasing the number of results per page which is something I didn't want to do but it's the only thing that works.</p>

Body:
I'm testing the flickrapi for python and have some code that randomly chooses a picture of Chinese food. It does this by getting 1 result on 1 page and using the total number of pages in that result to choose 1 result on 1 random page. Here is the code I'm using to get the images:

flickr = flickrapi.FlickrAPI(api_key='mykey', secret='mysecret', format='parsed-json', cache=False)
data1 = flickr.photos.search(tags='Chinese Food',
                            page=1,
                            per_page=1,
                            tag_mode='all',
                            media='photos',
                            content_type=1)

data2 = flickr.photos.search(tags='Chinese Food',
                            page=randint(1, data1['photos']['pages']),
                            per_page=1,
                            tag_mode='all',
                            media='photos',
                            content_type=1,
                            extras='url_l')

No matter what I do the result in data2 is always the exact same image returned in data1, I could get the first result from page 1 and the first result from page 3472 and the image is exactly the same every time.

Here is a sample of the data returned

//From data1
{'photos': {'page': 1, 'pages': 70007, 'perpage': 1, 'total': '70007', 'photo': [{'id': '35800805325', 'owner': '24171591@N06', 'secret': '408928a034', 'server': '4261', 'farm': 5, 'title': 'Personalized Maple Wood Chopsticks', 'ispublic': 1, 'isfriend': 0, 'isfamily': 0}]}, 'stat': 'ok'}

//From data2
{'photos': {'page': 41043, 'pages': 70007, 'perpage': 1, 'total': '70007', 'photo': [{'id': '35800805325', 'owner': '24171591@N06', 'secret': '408928a034', 'server': '4261', 'farm': 5, 'title': 'Personalized Maple Wood Chopsticks', 'ispublic': 1, 'isfriend': 0, 'isfamily': 0, 'url_l': 'https://farm5.staticflickr.com/4261/35800805325_408928a034_b.jpg', 'height_l': '859', 'width_l': '1024'}]}, 'stat': 'ok'}

Notice the id and title in both sets of data are exactly the same and the page numbers are different. I've tested this in the Flickr API explorer with the exact same parameters and I do get the same image when I specify page 1 but I also get a completely different image if I specify any other page, so this seems to be an issue with the python flickrapi implementation or one of its dependencies maybe?

I can't seem to find the issue. What is going on?


问:
Using memory allocated pointer inside the function
I have created the pointer, and allocated memory to it. This memory should contain the number, that I'm passing inside in array style (1 number = 1 element), also, the 0 element is the size of the number. However, I'm facing the problem of changing data inside the allocated memory, using a pointer. If I'm using my code in the main function, everything goes perfect, but when I created another function and passed a pointer value inside, I can't save it back (if the number is bigger then 99999 and takes 6 elements to be stored).

The main function:

```<code>int *convNum=NULL;

int main() {
int num;
convNum = malloc(sizeof(int));
if (convNum==NULL){
    printf("Allocation error\n");
    exit(0);
}

scanf("%d", &num);
convNum[0] = numLength(num);
printf("%d\n", convNum[0]);
convertNum(num, convNum);

for (int i = 1; i<=convNum[0]; i++){
    printf("%d", convNum[i]);
}

printf("\n");

return 0;
}
</code>```

The function, that I'm trying to use

```<code>int convertNum(int num, int * convNum){
int temp = num;
int size = convNum[0];
convNum = realloc(convNum, sizeof(int)*(size+1));
if (convNum==NULL){
    printf("Allocation error\n");
    exit(0);
}
for (int i=size;i>0;i--){
    convNum[i] = temp % 10;
    temp = temp / 10;
}
return 0;
}
</code>```

EDITED
The output with the number size less, than 6 gives me the result I needed. The output with other numbers gives me broken size (something like -10349945820) and no proper result.

答:
Your reallocation is not surviving your function call to convertNum. See this topic in the C-Faq:

Pointer to pointer clarification

You should pass the convNum pointer by-reference.

Body:
I have created the pointer, and allocated memory to it. This memory should contain the number, that I'm passing inside in array style (1 number = 1 element), also, the 0 element is the size of the number. However, I'm facing the problem of changing data inside the allocated memory, using a pointer. If I'm using my code in the main function, everything goes perfect, but when I created another function and passed a pointer value inside, I can't save it back (if the number is bigger then 99999 and takes 6 elements to be stored).

The main function:

int *convNum=NULL;

int main() {
int num;
convNum = malloc(sizeof(int));
if (convNum==NULL){
    printf("Allocation error\n");
    exit(0);
}

scanf("%d", &num);
convNum[0] = numLength(num);
printf("%d\n", convNum[0]);
convertNum(num, convNum);

for (int i = 1; i<=convNum[0]; i++){
    printf("%d", convNum[i]);
}

printf("\n");

return 0;
}

The function, that I'm trying to use

int convertNum(int num, int * convNum){
int temp = num;
int size = convNum[0];
convNum = realloc(convNum, sizeof(int)*(size+1));
if (convNum==NULL){
    printf("Allocation error\n");
    exit(0);
}
for (int i=size;i>0;i--){
    convNum[i] = temp % 10;
    temp = temp / 10;
}
return 0;
}

EDITED
The output with the number size less, than 6 gives me the result I needed. The output with other numbers gives me broken size (something like -10349945820) and no proper result.


问:
How to bitshift an array of ints?
I have an int array of size 50 and the first 49 'slots' are filled and I want to move each of the 49 elements of the array one position along so that the first element in the array is now free.

Is there a way to bit shift the entire array 32 bits? like:

array[0] >(49)> 32;

some random made up notation... but I hope it conveys what I am looking for

答:
If you want to take the long way home...</p>

```<code>#include <stdio.h>

int main(void)
{
    int array_size = 5;
    int array[] = {5, 1, 2, 3, 4};
    int i;
    for (i = array_size - 2; i >= 0; i--)
    {
        array[i+1] = array[i];

        if (i == 0)
            array[i] = 0; //whatever you want
    }

    // not necessary, just print the change
    int j;
    for (j = 0; j < array_size; j++)
        printf("%d ", array[j]);
    printf("\n");

    return 0;
}
</code>```

Title: How to bitshift an array of ints?

Body:
If you want to take the long way home...

#include <stdio.h>

int main(void)
{
    int array_size = 5;
    int array[] = {5, 1, 2, 3, 4};
    int i;
    for (i = array_size - 2; i >= 0; i--)
    {
        array[i+1] = array[i];

        if (i == 0)
            array[i] = 0; //whatever you want
    }

    // not necessary, just print the change
    int j;
    for (j = 0; j < array_size; j++)
        printf("%d ", array[j]);
    printf("\n");

    return 0;
}


问:
Why C++ doesn't allow derived class to use base class member in initialization list?
I've got following program:

```<code>#include<iostream>
using namespace std;
struct Base01{
    int m;
    Base01():m(2){}
    void p(){cout<<m<<endl;}
};
struct Derived01:public Base01{
    Derived01():m(3){}
};
struct Derived02:virtual public Base01{
    Derived01():m(4){}
};
struct my: Derived01,Derived02{
    my():m(5){}
};
int main(){
    return 0;
}
</code>```

Both gcc/clang reports compilation error.

I just wish to know what's the language design consideration here, why derived class can only call base class ctor in initialization list, but cannot use base class members directly?

答:
What you do in the constructor initializer list is initialization. It is something that has to be done only once in the lifetime of the object. In general case, that's what starts the objects lifetime.

Base class's constructor (which finished working before your derived class's constructor-proper became active) has already initialized all direct subobjects of the base class. It has already started their lifetimes. If you attempt to reach-in and initialize a direct subobject of base class from the derived class's constructor, that will obviously be the second initialization of the same object. This is completely unacceptable in C++. The language design generally does not allow you to initialize something the second time.

In your case the subobject in question has fundamental type int, so it is hard to see the harm in such "re-initialization". But consider something less trivial, like an std::string object. How do you suggest the derived class should "undo and redo" the initialization already performed by the base class? And while formally it is possible to do it properly, constructor initializer lists are not intended for that purpose.

In general case doing something like that would require a language feature that would allow user to tell base class's constructor something along the lines of "please, leave this subobject of yours uninitialized, I will reach-in and initialize it later from the derived class". However, C++ does not provide users with such capability. A vaguely similar feature exists in virtual base class initialization, but it serves a very specific (and different) purpose.

Body:
I've got following program:

#include<iostream>
using namespace std;
struct Base01{
    int m;
    Base01():m(2){}
    void p(){cout<<m<<endl;}
};
struct Derived01:public Base01{
    Derived01():m(3){}
};
struct Derived02:virtual public Base01{
    Derived01():m(4){}
};
struct my: Derived01,Derived02{
    my():m(5){}
};
int main(){
    return 0;
}

Both gcc/clang reports compilation error.

I just wish to know what's the language design consideration here, why derived class can only call base class ctor in initialization list, but cannot use base class members directly?


问:
How do I initialize a value that's based on a Recursive Type Alias?
How do I initialize a value that's based on a Recursive Type Alias?

```<code>type alias ContentProvider =
    { profile : Profile
    , topics : List Topic
    , links : Links
    , subscribers : Subscribers
    }

type Subscribers
    = Subscribers (List ContentProvider)
</code>```

My attempt to initialize the value fails:

```<code>contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider profile1 topics contentProvider1Links (Subscribers [ contentProvider2, contentProvider3 ])
</code>```

Note that the last argument is causing the error:

```<code>(Subscribers [ contentProvider2, contentProvider3 ])
</code>```

contentProvider1 is defined in terms of itself in a sneaky way,
  causing an infinite loop. - The following definitions depend directly
  on each other:

```<code>┌─────┐
│    contentProvider1
│     ↓
│    contentProvider2
│     ↓
│    contentProvider3
└─────┘
</code>```

I'm referencing this documentation. However, I do not understand why I am still getting a compiler error.

Appendix:

```<code>contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider profile1 topics contentProvider1Links (Subscribers [ contentProvider2 ])

contentProvider2 : ContentProvider
contentProvider2 =
    ContentProvider profile2 topics contentProvider2Links (Subscribers [ contentProvider1, contentProvider3 ])

contentProvider3 : ContentProvider
contentProvider3 =
    ContentProvider profile3 topics contentProvider3Links (Subscribers [ contentProvider1, contentProvider2 ])
</code>```

答:
contentProvider2 and contentProvider3 need to be defined like Chad Gilbert said, but the issue here isn't your mutually recursive type alias, it is the circular value reference that is not possible. Here is a simplified example that compiles:</p>

```<code>type alias ContentProvider =
    { profile : String
    , topics : List String
    , links : String
    , subscribers : Subscribers
    }

type Subscribers =
    Subscribers (List ContentProvider)

contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider "profile" ["art", "science"] "test" (Subscribers [contentProvider2])

contentProvider2 : ContentProvider
contentProvider2 =
    ContentProvider "profile" ["art", "science"] "test" (Subscribers [])
</code>```

Body:
How do I initialize a value that's based on a Recursive Type Alias?

type alias ContentProvider =
    { profile : Profile
    , topics : List Topic
    , links : Links
    , subscribers : Subscribers
    }

type Subscribers
    = Subscribers (List ContentProvider)

My attempt to initialize the value fails:

contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider profile1 topics contentProvider1Links (Subscribers [ contentProvider2, contentProvider3 ])

Note that the last argument is causing the error:

(Subscribers [ contentProvider2, contentProvider3 ])

contentProvider1 is defined in terms of itself in a sneaky way,
  causing an infinite loop. - The following definitions depend directly
  on each other:

┌─────┐
│    contentProvider1
│     ↓
│    contentProvider2
│     ↓
│    contentProvider3
└─────┘

I'm referencing this documentation. However, I do not understand why I am still getting a compiler error.

Appendix:

contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider profile1 topics contentProvider1Links (Subscribers [ contentProvider2 ])

contentProvider2 : ContentProvider
contentProvider2 =
    ContentProvider profile2 topics contentProvider2Links (Subscribers [ contentProvider1, contentProvider3 ])

contentProvider3 : ContentProvider
contentProvider3 =
    ContentProvider profile3 topics contentProvider3Links (Subscribers [ contentProvider1, contentProvider2 ])

Body:
contentProvider2 and contentProvider3 need to be defined like Chad Gilbert said, but the issue here isn't your mutually recursive type alias, it is the circular value reference that is not possible. Here is a simplified example that compiles:

type alias ContentProvider =
    { profile : String
    , topics : List String
    , links : String
    , subscribers : Subscribers
    }

type Subscribers =
    Subscribers (List ContentProvider)

contentProvider1 : ContentProvider
contentProvider1 =
    ContentProvider "profile" ["art", "science"] "test" (Subscribers [contentProvider2])

contentProvider2 : ContentProvider
contentProvider2 =
    ContentProvider "profile" ["art", "science"] "test" (Subscribers [])


问:
Application as Service Win server 2003
I want to make a service from a .exe file.

To do this i can use software like FireDaemon or ExeToServices but i want to do it with sc.exe.

But I don't know how to do this, i have to add a paramater afther the specific .exe path

like: "C:\Program Files\Server1\example.exe" +set fs_game 1

How can i do this?

答: PROBLEM SOLVED, Firedaemon fixes my problem.</p>

Title: Application as Service Win server 2003


问:
How to set up browserify?
I installed the modules(browserify, react, reactify) and try to process jsx file using browserify.

var React = require("react");
var App = React.createClass({
    render: function () {
        return
111

    }
});
React.render(
    <App/>,
    document.body
)```

C:\dev\React.js>browserify app.js -o buld.js Error: Parsing file
  C:\dev\React.js\app.js: Unexpected token (4:15)
      at Deps.parseDeps (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\module-deps\index.js:481:28)
      at getDeps (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\module-deps\index.js:414:40)
      at C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\module-deps\index.js:398:32
      at ConcatStream. (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\concat-stream\index.js:36:43)
      at emitNone (events.js:91:20)
      at ConcatStream.emit (events.js:185:7)
      at finishMaybe (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\concat-stream\node_modules\readable-stream\lib_stream_writable.js:475:14
  )
      at endWritable (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\concat-stream\node_modules\readable-stream\lib_stream_writable.js:485:3)
      at ConcatStream.Writable.end (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\concat-stream\node_modules\readable-stream\lib_stream_writ
  able.js:455:41)
      at DuplexWrapper.onend (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\readable-stream\lib_stream_readable.js:570:10)

Where is the mistake?

答:
Your error is the result of the trying to load JSX into the browserfy compiler.

Specifically:

```<code>return <h1>111</h1>
</code>```

and

```<code><App/>,
</code>```

You need to include reactify in your resolution chain: https://www.npmjs.com/package/reactify
then your CLI command will look a little like this:
browserify -t reactify app.js -o build.js

As someone who does a lot of React you should consider using Babel and Webpack. They provide a lot of great additional development tooling and I think is easier to expand but thats just one guys opinion.

Title: How to set up browserify?

Body:
I installed the modules(browserify, react, reactify) and try to process jsx file using browserify.

var React = require("react");
var App = React.createClass({
    render: function () {
        return
111

    }
});
React.render(
    <App/>,
    document.body
)

C:\dev\React.js>browserify app.js -o buld.js Error: Parsing file
  C:\dev\React.js\app.js: Unexpected token (4:15)
      at Deps.parseDeps (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\module-deps\index.js:481:28)
      at getDeps (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\module-deps\index.js:414:40)
      at C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\module-deps\index.js:398:32
      at ConcatStream. (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\concat-stream\index.js:36:43)
      at emitNone (events.js:91:20)
      at ConcatStream.emit (events.js:185:7)
      at finishMaybe (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\concat-stream\node_modules\readable-stream\lib_stream_writable.js:475:14
  )
      at endWritable (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\concat-stream\node_modules\readable-stream\lib_stream_writable.js:485:3)
      at ConcatStream.Writable.end (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\concat-stream\node_modules\readable-stream\lib_stream_writ
  able.js:455:41)
      at DuplexWrapper.onend (C:\Users\admin\AppData\Roaming\npm\node_modules\browserify\node_modules\readable-stream\lib_stream_readable.js:570:10)

Where is the mistake?

Body:
Your error is the result of the trying to load JSX into the browserfy compiler.

Specifically:

return <h1>111</h1>

and

<App/>,

You need to include reactify in your resolution chain: https://www.npmjs.com/package/reactify
then your CLI command will look a little like this:
browserify -t reactify app.js -o build.js

As someone who does a lot of React you should consider using Babel and Webpack. They provide a lot of great additional development tooling and I think is easier to expand but thats just one guys opinion.


问:
How to debug in HTML
I am trying to implement a little code in HTML; calling a PHP onclick in HTML using the solution here and it just runs to a blank page. Upon inspection, I noticed a typo in my code but after i corrected it the output is still the same i.e. it opens a blank page with no echo or anything.

My question: Is there a way to debug my code so my browser (i suspect) can notify me as to what part or line of my code the error is coming from, like in Java IDEs?

```<code><?php
function working(){
    echo 'WORKED ';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Game</title>
</head>
<body>
<div>
<div>
    <h1 id="player1" onclick="document.write('<?php working(); ?>')">
        ENTER PLAYER 1 NAME
    </h1>
</div>
</div>
</body>
</html>
</code>```

Note: I use Chrome

答:
You are "implementing a little code in HTML; calling a PHP onclick in HTML"

Firstly if your are using a php code in html, So extension of file should .php and there should be a server(ex. wamp,xamp,lamp) to run it. if it having  extension  .html then it will not show any error, because html files is compiled at browser lever and php is server side language. So if make right extension of your file means make ext .php then run you file, then if there will be any error then you will got message on browser also hinting line number of error.

Title: How to debug in HTML

Body:
I am trying to implement a little code in HTML; calling a PHP onclick in HTML using the solution here and it just runs to a blank page. Upon inspection, I noticed a typo in my code but after i corrected it the output is still the same i.e. it opens a blank page with no echo or anything.

My question: Is there a way to debug my code so my browser (i suspect) can notify me as to what part or line of my code the error is coming from, like in Java IDEs?

<?php
function working(){
    echo 'WORKED ';
}
?>
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Dice Game</title>

    <h1 id="player1" onclick="document.write('<?php working(); ?>')">
        ENTER PLAYER 1 NAME

Note: I use Chrome


问:
Tried to create a local server to broadcast data but got ConnectionRefusedError
Tried to create a local server to broadcast messages in python using the websocket module. (Mac OSX)

```<code>from websocket import create_connection

url = 'ws://localhost:8888/'

ws = create_connection(url)
ws.send("helloworld")
ws.close()
</code>```

Saw this error: ConnectionRefusedError: [Errno 61] Connection refused

答:
Your port 8888 is either closed or filtered. You most port forward it in your router.

Refer to this guide.

Body:
Tried to create a local server to broadcast messages in python using the websocket module. (Mac OSX)

from websocket import create_connection

url = 'ws://localhost:8888/'

ws = create_connection(url)
ws.send("helloworld")
ws.close()

Saw this error: ConnectionRefusedError: [Errno 61] Connection refused


问:
MySQL database and ASP.NET global connection
I have developed a website in which I have used ASP.NET with VB.NET as the backend programming language and a MySQL database. I have used ASP.NET and the MySQL database connector to run the website on my local computer, and it is working fine. The code of web.config file is given below:

```<code><?xml version="1.0"?>
<!--
    For more information on how to configure your ASP.NET application, please
    visit
    http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
    <system.web>
        <trust level="Medium"/>
        <customErrors mode="Off" defaultRedirect="Home.aspx"/>
        <compilation debug="true" strict="false" explicit="true"
                     targetFramework="4.0">
            <assemblies>
                <add assembly="MySql.Data, Version=6.9.9.0, Culture=neutral,
                     PublicKeyToken=C5687FC88969C44D"/>
            </assemblies>
        </compilation>
    </system.web>
</configuration>
</code>```

But now I have uploaded this website and database on the global server and have put the global database connection in my code. now the code of web.config file is

```<code><?xml version="1.0"?>
<!--
    For more information on how to configure your ASP.NET application, please
    visit
    http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
    <connectionStrings>
        <add name="myConnectionString" connectionString= "Server=globalservername;
             Database=databasename; Uid=userid; Pwd=passwd;"
             providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
    <system.web>
        <trust level="Medium"/>
        <customErrors mode="Off" defaultRedirect="Home.aspx"/>
        <compilation debug="true" strict="false" explicit="true"
                     targetFramework="4.0">
        </compilation>
    </system.web>
</configuration>
</code>```

And when I open any page then it is showing the following error

Compiler Error Message: BC30002: Type 'MySqlConnection' is not defined.

in this line which is in every Visual Basic file of my project (connection string):

```<code>Dim SQLConnection As New MySqlConnection("Server=globalservername;
Database=databasename; Uid=userid; Pwd=passwd;")
</code>```

What should I add or remove in the web.config file to remove this error?

答:
Do this first:

```<code>Mysqlopen("db")
</code>```

It should work. If not, then make sure you have VB 2005. It will not work with Visual Basic 6.0. If that doesn't work then you can just run the SQL as a separate process and use Visual Basic to to call it.

Body:
I have developed a website in which I have used ASP.NET with VB.NET as the backend programming language and a MySQL database. I have used ASP.NET and the MySQL database connector to run the website on my local computer, and it is working fine. The code of web.config file is given below:

<?xml version="1.0"?>

<configuration>
    <system.web>
        <trust level="Medium"/>
        <customErrors mode="Off" defaultRedirect="Home.aspx"/>
        <compilation debug="true" strict="false" explicit="true"
                     targetFramework="4.0">
            <assemblies>
                <add assembly="MySql.Data, Version=6.9.9.0, Culture=neutral,
                     PublicKeyToken=C5687FC88969C44D"/>
            </assemblies>
        </compilation>
    </system.web>
</configuration>

But now I have uploaded this website and database on the global server and have put the global database connection in my code. now the code of web.config file is

<?xml version="1.0"?>

<configuration>
    <connectionStrings>
        <add name="myConnectionString" connectionString= "Server=globalservername;
             Database=databasename; Uid=userid; Pwd=passwd;"
             providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
    <system.web>
        <trust level="Medium"/>
        <customErrors mode="Off" defaultRedirect="Home.aspx"/>
        <compilation debug="true" strict="false" explicit="true"
                     targetFramework="4.0">
        </compilation>
    </system.web>
</configuration>

And when I open any page then it is showing the following error

Compiler Error Message: BC30002: Type 'MySqlConnection' is not defined.

in this line which is in every Visual Basic file of my project (connection string):

Dim SQLConnection As New MySqlConnection("Server=globalservername;
Database=databasename; Uid=userid; Pwd=passwd;")

What should I add or remove in the web.config file to remove this error?

Body:
Do this first:

Mysqlopen("db")

It should work. If not, then make sure you have VB 2005. It will not work with Visual Basic 6.0. If that doesn't work then you can just run the SQL as a separate process and use Visual Basic to to call it.


问:
How to get jQuery to submit a form to a post
I have a form that I am validating with jQuery.

```<code><form id="target" class="center-block" action="/" method="POST">
    <textarea class="form-control" id="name" rows="3" name="name" placeholder="Enter a burger you would like to devour!"></textarea>
    <button type="button" id="submit" class="center-block btn btn-default top">Submit</button>
</form>
</code>```

After validation I am also trying to submit the form via jQuery.

```<code>if (validateForm() == true) {
   $("#target").submit();
}
</code>```

The validation is working however, it doesn't seem like the form is submitting to the post route.  I was able to get the form to post using ajax, but the post wouldn't redirect after finishing.  Was hoping this method would give the desired effect.

The app is running on Express and using MySQL.

答:
Use Ajax and if you want to redirect to the current page, on success reload the current page

```<code>$.ajax({
    url: yourUrl,
    type: "post",
    data: $("#target").serialize(),
    success: function(r){
        //form posted successfully
        window.location.reload();
    },
    error: function(error){
      alert(error);
    }
});
</code>```

Body:
I have a form that I am validating with jQuery.

<form id="target" class="center-block" action="/" method="POST">
    <textarea class="form-control" id="name" rows="3" name="name" placeholder="Enter a burger you would like to devour!"></textarea>
    <button type="button" id="submit" class="center-block btn btn-default top">Submit</button>
</form>

After validation I am also trying to submit the form via jQuery.

if (validateForm() == true) {
   $("#target").submit();
}

The validation is working however, it doesn't seem like the form is submitting to the post route.  I was able to get the form to post using ajax, but the post wouldn't redirect after finishing.  Was hoping this method would give the desired effect.

The app is running on Express and using MySQL.

Body:
Use Ajax and if you want to redirect to the current page, on success reload the current page

$.ajax({
    url: yourUrl,
    type: "post",
    data: $("#target").serialize(),
    success: function(r){
        //form posted successfully
        window.location.reload();
    },
    error: function(error){
      alert(error);
    }
});


问:
SQLiteConstraintException: error code 19: constraint failed
I'm getting that exception when I do an insert in my SQLite database

The following code gives me the exception:

```<code>mDbHelper.createUser("pablo","a","a","a","a");
</code>```

The code from mDbHelper (MyDbAdapter):

```<code>private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";

public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }
</code>```

The exception is created on the last line: return mDb.insert("user", null, initialValues);

答:
You are inserting a duplicate email.

Plus the recommended way is to have a _ID column as primary key, even if you don't use it. This way on future uses, like use in a Adapter or List, you won't have to workaround.

Body:
I'm getting that exception when I do an insert in my SQLite database

The following code gives me the exception:

mDbHelper.createUser("pablo","a","a","a","a");

The code from mDbHelper (MyDbAdapter):

private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";

public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }

The exception is created on the last line: return mDb.insert("user", null, initialValues);


问:
The folder of eclipse-plugin in JCDK 3.0.5u1 not found?
I am new to Java Card development.
 I want to install the eclipse-plugin for Java Card Classic Development Kit 3.0.5u1 followed by http://blog.csdn.net/chenxu6/article/details/50731125
and download the java_card_kit-classic-3_0_5-u1-win32-do-b35-24_may_2017.msi from
http://www.oracle.com/technetwork/java/embedded/javacard/downloads/javacard-sdk-2043229.html.

after installed the msi, I can't find the folder eclipse-plugin to install the new feature of Java Card.

Anybody can tell me how to do?

答:
New msi installer file is available now.
'java_card_kit-classic-3_0_5-u1-win32-do-b36-03_jul_2017.msi'

http://www.oracle.com/technetwork/java/embedded/javacard/downloads/javacard-sdk-2043229.html

This file contains 'eclipse-plugin' directory and files.
You should be able to install with it correctly.

I have installed previous version of msi installer java_card_kit-classic-3_0_5-u1-win32-do-b35-24_may_2017.msi
    then this installer got same result with yours. Actually I could not use this.

I think this problem is relative to msi installer package.


问:
pthread_kill to a GCD-managed thread
I am attempting to send a signal to a specific thread with pthread_kill. I use pthread_from_mach_thread_np() to get a handle and then use pthread_kill to send the signal.

This worked well in my other testing, but now I see that when attempting to signal a thread internally created by GCD, I get a return code of 45 from pthread_kill.

GCD API that spawned that thread:

```<code>dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ ... });
</code>```

Any reason this is happening?

—-

To add some further information, I am not attempting to kill threads. pthread_kill() is the standard POSIX API to send signals to threads. If a signal handler is installed, the thread’s context is switched with a trampoline to the handler.

While what I attempt to achieve using my signal handler can be achieved in better ways, this is not in question here. Even if for purely academic reasons, I would like to understand what is going on here internally.

答:
The pthread_kill() API is specifically disallowed on workqueue threads (the worker threads underlying GCD) and returns ENOTSUP for such threads.

This is primarily intended to prevent execution of arbitrary signal handlers in the context of code that may not expect it (since these threads are a shared resource used by many independent subsystems in a process), as well as to abstract away that execution context so that the system has the freedom to change it in the future.

You can see the details of how this is achieved in the implementation.

Title: pthread_kill to a GCD-managed thread

Body:
I am attempting to send a signal to a specific thread with pthread_kill. I use pthread_from_mach_thread_np() to get a handle and then use pthread_kill to send the signal.

This worked well in my other testing, but now I see that when attempting to signal a thread internally created by GCD, I get a return code of 45 from pthread_kill.

GCD API that spawned that thread:

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ ... });

Any reason this is happening?

—-

To add some further information, I am not attempting to kill threads. pthread_kill() is the standard POSIX API to send signals to threads. If a signal handler is installed, the thread’s context is switched with a trampoline to the handler.

While what I attempt to achieve using my signal handler can be achieved in better ways, this is not in question here. Even if for purely academic reasons, I would like to understand what is going on here internally.


问:
Overriding Grails config for plugins
I am trying to figure out how to separate deployment specific config from my Grails 3 app. In Grails 2 I could setup a config location lookup which would load my dev specific config file. And in Grails 3 I have found that I can provide additional spring configs when running the app, i.e.:

```<code>./grailsw -Dspring.config.location=classpath:application.yml,file:///home/nigel/src/app/dev.yml run-app
</code>```

However, this doesn't work if I'm using plugins, such as below, where it will just used the config in grails-app/conf/application.yml:

```<code>./grailsw -Dspring.config.location=classpath:application.yml,file:///home/nigel/src/app/dev.yml url-mappings-report
</code>```

So my question is, how do I provide deployment/dev specific config files to grails so that it works with the grails plugins.

答:
Try to use the Grails 3 external config plugin for this task.

This plugin mimics Grails 2 way of handling external configurations defined in grails.config.locations

Steps:

Add dependency to the build.gradle.

Create a new local config Groovy script and add the configutation you want to override.

Add the external configuration property in your application.yml or application.groovy and provide the path to your local config file within it.

That's it.

Title: Overriding Grails config for plugins

Body:
I am trying to figure out how to separate deployment specific config from my Grails 3 app. In Grails 2 I could setup a config location lookup which would load my dev specific config file. And in Grails 3 I have found that I can provide additional spring configs when running the app, i.e.:

./grailsw -Dspring.config.location=classpath:application.yml,file:///home/nigel/src/app/dev.yml run-app

However, this doesn't work if I'm using plugins, such as below, where it will just used the config in grails-app/conf/application.yml:

./grailsw -Dspring.config.location=classpath:application.yml,file:///home/nigel/src/app/dev.yml url-mappings-report

So my question is, how do I provide deployment/dev specific config files to grails so that it works with the grails plugins.