问:
Two different variables getting same value
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

```<code>public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}
</code>```

Here I am using the variables:

```<code>MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());
</code>```

The output is the following: http://imgur.com/a/Nu3N6

答:
You problem is second file path is overlap of first file path. So, check this code:</p>

```<code>    MyFile modelFile = new MyFile("res\\model.dae");
    MyFile textureFile = new MyFile("res\\diffuse.png");

    System.out.println(new MyFile("res\\model.dae"));
    System.out.println(new MyFile("res\\diffuse.png"));
</code>```

Body:
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}

Here I am using the variables:

MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());

The output is the following: http://imgur.com/a/Nu3N6

Body:
You problem is second file path is overlap of first file path. So, check this code:

    MyFile modelFile = new MyFile("res\\model.dae");
    MyFile textureFile = new MyFile("res\\diffuse.png");

    System.out.println(new MyFile("res\\model.dae"));
    System.out.println(new MyFile("res\\diffuse.png"));


来源: stackexchange

问:
Where does the space from the top-margin came from?
I started to learn CSS, and I got to that example in the internet:
https://www.w3schools.com/css/tryit.asp?filename=trycss_margin_shorthand

But I tried to play with it, and changed some things. Now the code looks like:

 div#my {
        border: 8px solid black;
        margin-left: 0%;
        margin-right: 0%;

        height: 500px;

        background-color: red;
    }

    div {
        border: 5px solid black;
        margin: inherit;
        background-color: lightblue;
    }

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="my">
   <div>This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.</div>
</div></code>```

What I see is a big blue block inside a big red block. The blue block collapse with his left and right sides to the red block's border, but from the top I have margin for some reason.

I think its because I chose inherit in the css element. But that says that I have a default margin to the page. Please, help here to understand.

答:
There is a default margin on the body which is also inherited in your case (with margin: inherit), you can reset it like this:

html,
body {
  margin: 0;
}

div#my {
  border: 8px solid black;
  margin-left: 0%;
  margin-right: 0%;
  height: 500px;
  background-color: red;
}

div {
  border: 5px solid black;
  margin: inherit;
  background-color: lightblue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="my">
  <div>This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.</div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I started to learn CSS, and I got to that example in the internet:
https://www.w3schools.com/css/tryit.asp?filename=trycss_margin_shorthand

But I tried to play with it, and changed some things. Now the code looks like:

 div#my {
        border: 8px solid black;
        margin-left: 0%;
        margin-right: 0%;

        height: 500px;

        background-color: red;
    }

    div {
        border: 5px solid black;
        margin: inherit;
        background-color: lightblue;
    }

This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.

What I see is a big blue block inside a big red block. The blue block collapse with his left and right sides to the red block's border, but from the top I have margin for some reason.

I think its because I chose inherit in the css element. But that says that I have a default margin to the page. Please, help here to understand.

Body:
There is a default margin on the body which is also inherited in your case (with margin: inherit), you can reset it like this:

html,
body {
  margin: 0;
}

div#my {
  border: 8px solid black;
  margin-left: 0%;
  margin-right: 0%;
  height: 500px;
  background-color: red;
}

div {
  border: 5px solid black;
  margin: inherit;
  background-color: lightblue;
}

<div id="my">
  <div>This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.</div>
</div>


问:
ModelForm in Django - select is not populating with appropriate data?
I've got a model form in Django that displays nicely - but it's not pulling the appropriate information.

The select dropdowns appear, but are not populated with the options and I am struggling to figure out why.

My models look like this:

```<code>class Mileage(models.Model):
    start_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='start_locations')
    end_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='end_locations')
    miles = models.DecimalField(max_digits=8, decimal_places=2)
    user_id = models.IntegerField(null=True)

    def __str__(self):
        return self.miles

class Location(models.Model):
    name = models.CharField(max_length=255)
    address = models.CharField(max_length=255, null=True)
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True)
    user_id = models.IntegerField(null=True)

    def __str__(self):
        return self.id

class Trip(models.Model):
    start_location = models.CharField(max_length=255)
    end_location = models.CharField(max_length=255)
    miles = models.DecimalField(max_digits=7, decimal_places=2)
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    trip_date = models.DateTimeField('trip date')

    def __str__(self):
        return self.id
</code>```

My ModelForm looks like this:

```<code>class TripsForm(ModelForm):
    class Meta:
        model = Trip
        fields = ['start_location', 'end_location', 'miles', 'trip_date']
        widgets = {
            'start_location': forms.Select(
                attrs={
                    'class': 'form-control',
                    'id': 'start_location'
                }
            ),
            'end_location': forms.Select(
                attrs={
                    'class': 'form-control',
                    'id': 'end_location'
                }
            ),
            'miles': forms.NumberInput(
                attrs={
                    'class': 'form-control',
                    'id': 'miles',
                    'readonly': 'readonly'
                }
            ),
            'trip_date': forms.TextInput(
                attrs={
                    'class': 'form-control monthpicker datepicker',
                    'id': 'trip_date'
                }
            ),
        }
</code>```

In my view I'm calling it like this from view.py:

```<code># Create trip
def trip_create(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        form = TripsForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # Save the form -- will handle this all later
            trip.save()
            return HttpResponseRedirect('/thanks/')
    # if a GET (or any other method) we'll create a blank form
    else:
        form = TripsForm()
        # Return to trips with list of date
    return render(request, 'trips/create.html', {'form': form})
</code>```

The 'start_locations' and 'end_locations' selects should be populated with all of locations - currently the selects are totally empty.

I've been looking through documentation: would a modelformset_factory() be something to dig into more in this case?

I'm just not sure how to proceed to get it to populate those dropdowns.

答:
Currently you are using a CharField for Trip.start_location and Trip.end_location. If you use a select widget, it's up to you to create the choices to populate it.

If you use a ForeignKey for your start_location and end_location fields, then Django will populate the choices for you.

```<code>class Trip(models.Model):
    start_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='trip_start_locations')
    end_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='trip_end_locations')
</code>```

After making the change in your models, you'll have to make a migration, then migrate.

Note that I've included trip in the related_name, since the related name is used to take you from the Location model back to Trip. You might want to update the related_name for your Mileage model to include mileage.

Body:
I've got a model form in Django that displays nicely - but it's not pulling the appropriate information.

The select dropdowns appear, but are not populated with the options and I am struggling to figure out why.

My models look like this:

class Mileage(models.Model):
    start_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='start_locations')
    end_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='end_locations')
    miles = models.DecimalField(max_digits=8, decimal_places=2)
    user_id = models.IntegerField(null=True)

    def __str__(self):
        return self.miles

class Location(models.Model):
    name = models.CharField(max_length=255)
    address = models.CharField(max_length=255, null=True)
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True)
    user_id = models.IntegerField(null=True)

    def __str__(self):
        return self.id

class Trip(models.Model):
    start_location = models.CharField(max_length=255)
    end_location = models.CharField(max_length=255)
    miles = models.DecimalField(max_digits=7, decimal_places=2)
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    trip_date = models.DateTimeField('trip date')

    def __str__(self):
        return self.id

My ModelForm looks like this:

class TripsForm(ModelForm):
    class Meta:
        model = Trip
        fields = ['start_location', 'end_location', 'miles', 'trip_date']
        widgets = {
            'start_location': forms.Select(
                attrs={
                    'class': 'form-control',
                    'id': 'start_location'
                }
            ),
            'end_location': forms.Select(
                attrs={
                    'class': 'form-control',
                    'id': 'end_location'
                }
            ),
            'miles': forms.NumberInput(
                attrs={
                    'class': 'form-control',
                    'id': 'miles',
                    'readonly': 'readonly'
                }
            ),
            'trip_date': forms.TextInput(
                attrs={
                    'class': 'form-control monthpicker datepicker',
                    'id': 'trip_date'
                }
            ),
        }

In my view I'm calling it like this from view.py:

# Create trip
def trip_create(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        form = TripsForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # Save the form -- will handle this all later
            trip.save()
            return HttpResponseRedirect('/thanks/')
    # if a GET (or any other method) we'll create a blank form
    else:
        form = TripsForm()
        # Return to trips with list of date
    return render(request, 'trips/create.html', {'form': form})

The 'start_locations' and 'end_locations' selects should be populated with all of locations - currently the selects are totally empty.

I've been looking through documentation: would a modelformset_factory() be something to dig into more in this case?

I'm just not sure how to proceed to get it to populate those dropdowns.

Body:
Currently you are using a CharField for Trip.start_location and Trip.end_location. If you use a select widget, it's up to you to create the choices to populate it.

If you use a ForeignKey for your start_location and end_location fields, then Django will populate the choices for you.

class Trip(models.Model):
    start_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='trip_start_locations')
    end_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='trip_end_locations')

After making the change in your models, you'll have to make a migration, then migrate.

Note that I've included trip in the related_name, since the related name is used to take you from the Location model back to Trip. You might want to update the related_name for your Mileage model to include mileage.


问:
Make text boxes different sizes
I have some fields (such as name, phone number, company) a user can fill out. The text boxes are good sizes, except for one, which is a "note" field. I want the note text box to be very large when compared to the other text box fields, but I am only able to make all the text boxes the same size.

_form.html.erb/vendors

```<code><%= form_for @vendor do |f| %>

#this text field will be a regular size
  <p>
    <%= f.label :company %><br>
    <%= f.text_field :company %>
  </p>

#more code...

#I want this text field to be large
 <body>
     <div class = "notes">
         <p>
             <%= f.label :notes %><br>
             <%= f.text_field :notes %>
        </p>
     </div>
 </body>

  <p>
    <%= f.submit %>
  </p>

</div>

<% end %>
</code>```

my css file

```<code>input[type=text]{
    width: 40%;
    padding: 12px 12px;
    border: 2px solid #ccc;
    background-color: white;
}

textarea {
    width: 20%;
    height: 10px;
    padding: 12px 12px;
    border: 2px solid #ccc;
    background-color: white;
    resize: none
}

#more code...
</code>```

答:
You can add a class with the style (width) you want for that input:

```<code>.large-box {
  width: 60% !important;
}
</code>```

Then, add it to your input:

```<code><%= f.text_field :notes, class: "large-box" %>
</code>```

Title: Make text boxes different sizes

Body:
I have some fields (such as name, phone number, company) a user can fill out. The text boxes are good sizes, except for one, which is a "note" field. I want the note text box to be very large when compared to the other text box fields, but I am only able to make all the text boxes the same size.

_form.html.erb/vendors

<%= form_for @vendor do |f| %>

#this text field will be a regular size

    <%= f.label :company %>

    <%= f.text_field :company %>

#more code...

#I want this text field to be large

             <%= f.label :notes %>

             <%= f.text_field :notes %>

    <%= f.submit %>

<% end %>

my css file

input[type=text]{
    width: 40%;
    padding: 12px 12px;
    border: 2px solid #ccc;
    background-color: white;
}

textarea {
    width: 20%;
    height: 10px;
    padding: 12px 12px;
    border: 2px solid #ccc;
    background-color: white;
    resize: none
}

#more code...

Body:
You can add a class with the style (width) you want for that input:

.large-box {
  width: 60% !important;
}

Then, add it to your input:

<%= f.text_field :notes, class: "large-box" %>


问:
Read Mathematica generated text file
I have a text file generated by mathematica. I want to convert the text file python readable.The main problem is that the file stores the array with curly bracket("{......}"). Another problem is that mathematica uses I as an imaginary number where as python uses j. What is the solution? </p>

答:
example of complex number exchange:

mathematica:

```<code>  Export["cmplx.csv",RandomComplex[{-1-I,1+I} , {3,3}]
</code>```

python:

```<code>  import csv
  reader=csv.reader(open('cmplx.csv','r'))
  complexarray=[complex(item.replace('*I','j'))
        for row in reader for item in row]
</code>```

This is suitable really for small amounts of data. For large arrays I'd split off the real and imaginary parts to separate arrays , use the binary exchange shown here https://stackoverflow.com/a/44184067/1004168 and reassemble to complex with numpy.

mathematica:

```<code>m = Table[RandomComplex[], {3}, {3}]
f = OpenWrite["test.bin", BinaryFormat -> True];
BinaryWrite[f, ArrayDepth[m], "Integer32"];
BinaryWrite[f, Dimensions[m], "Integer32"];
BinaryWrite[f, Re[m], "Real64"];
BinaryWrite[f, Im[m], "Real64"];
Close[f]
</code>```

python:

```<code>import numpy as np
with open('test.bin','rb') as f:
 depth=np.fromfile(f,dtype=np.dtype('int32'),count=1)
 dims=np.fromfile(f,dtype=np.dtype('int32'),count=depth)
 count=reduce(lambda x,y:x*y,dims)
 complexarray=np.reshape(np.fromfile(f,dtype=np.dtype('float64'),
    count=count),dims)
 complexarray=complexarray+
    1j*np.reshape(np.fromfile(f,dtype=np.dtype('float64'),
    count=count),dims)
</code>```

Title: Read Mathematica generated text file

Body:
example of complex number exchange:

mathematica:

  Export["cmplx.csv",RandomComplex[{-1-I,1+I} , {3,3}]

python:

  import csv
  reader=csv.reader(open('cmplx.csv','r'))
  complexarray=[complex(item.replace('*I','j'))
        for row in reader for item in row]

This is suitable really for small amounts of data. For large arrays I'd split off the real and imaginary parts to separate arrays , use the binary exchange shown here https://stackoverflow.com/a/44184067/1004168 and reassemble to complex with numpy.

mathematica:

m = Table[RandomComplex[], {3}, {3}]
f = OpenWrite["test.bin", BinaryFormat -> True];
BinaryWrite[f, ArrayDepth[m], "Integer32"];
BinaryWrite[f, Dimensions[m], "Integer32"];
BinaryWrite[f, Re[m], "Real64"];
BinaryWrite[f, Im[m], "Real64"];
Close[f]

python:

import numpy as np
with open('test.bin','rb') as f:
 depth=np.fromfile(f,dtype=np.dtype('int32'),count=1)
 dims=np.fromfile(f,dtype=np.dtype('int32'),count=depth)
 count=reduce(lambda x,y:x*y,dims)
 complexarray=np.reshape(np.fromfile(f,dtype=np.dtype('float64'),
    count=count),dims)
 complexarray=complexarray+
    1j*np.reshape(np.fromfile(f,dtype=np.dtype('float64'),
    count=count),dims)


问:
Second argument to std::vector
Looking at vector, I realized that I have never used the second argument when creating vectors.

```<code>std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?
</code>```

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?

答:
Custom allocators are rarely used in general case. Some examples of where they can be useful:

Optimization for a specific pattern of allocations. For example, a concurrent program can pre-allocate a large chunk of memory via standard means at the beginning of task execution and then shave off pieces off it without blocking on the global heap mutex. When task is completed, entire memory block can be disposed of. To use this technique with STL containers, a custom allocator can be employed.

Embedded software, where a device has several ranges of memory with different properties (cached/noncached, fast/slow, volatile/persistent etc). A custom allocator can be used to place objects stored in an STL container in a specific memory region.

ContentLicense: CC BY-SA 2.5

Title: Second argument to std::vector

Body:
Looking at vector, I realized that I have never used the second argument when creating vectors.

std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?


问:
correct usage of reduce-reducers
I don't understand what reduce-reducers is meant for. Should it be used in the case that I have 2 reducer functions containing the same action?

```<code>function reducerA(state, action){
   switch(action.type):
       ...
       case 'SAME_ACTION': {...state, field: state.field+1}
}

function reducerB(state, action){
   switch(action.type):
       ...
       case 'SAME_ACTION': {...state, field: state.field*2}
}
</code>```

So if I call reduceReducer on reducerA and reducerB and action 'SAME_ACTION' is invoked for {field: 0} then I would have a next state {field: 2}?

Also it seems to me that it kind of concatenates reducers (meaning merging them under one key).

Am I right or does reduceReducer serve a different purpose?

答:
The difference is:

combineReducers creates nested state

reduceReducers creates flat state

Consider following reducers. There are no action types to make things simpler:

// this reducer adds a payload to state.sum
// and tracks total number of operations
function reducerAdd(state, payload) {
  if (!state) state = { sum: 0, totalOperations: 0 }
  if (!payload) return state

  return {
    ...state,
    sum: state.sum + payload,
    totalOperations: state.totalOperations + 1
  }
}

// this reducer multiplies state.product by payload
// and tracks total number of operations
function reducerMult(state, payload) {
  if (!state) state = { product: 1, totalOperations: 0 }
  if (!payload) return state

  // `product` might be undefined because of
  // small caveat in `reduceReducers`, see below
  const prev = state.product || 1

  return {
    ...state,
    product: prev * payload,
    totalOperations: state.totalOperations + 1
  }
}
```

<h2>combineReducers</h2>

<p>Each reducer gets an independent piece of state (see also http://redux.js.org/docs/api/combineReducers.html):</p>

<pre class="lang-js prettyprint-override"><code>const rootReducer = combineReducers({
  add: reducerAdd,
  mult: reducerMult
})

const initialState = rootReducer(undefined)
/*
 * {
 *   add:  { sum: 0, totalOperations: 0 },
 *   mult: { product: 1, totalOperations: 0 },
 * }
 */

const first = rootReducer(initialState, 4)
/*
 * {
 *   add:  { sum: 4, totalOperations: 1 },
 *   mult: { product: 4, totalOperations: 1 },
 * }
 */
// This isn't interesting, let's look at second call...

const second = rootReducer(first, 4)
/*
 * {
 *   add:  { sum: 8, totalOperations: 2 },
 *   mult: { product: 16, totalOperations: 2 },
 * }
 */
// Now it's obvious, that both reducers get their own
// piece of state to work with
</code>```

reduceReducers

All reducers share the same state

const addAndMult = reduceReducers(reducerAdd, reducerMult)

const initial = addAndMult(undefined)
/*
 * {
 *   sum: 0,
 *   totalOperations: 0
 * }
 *
 * First, reducerAdd is called, which gives us initial state { sum: 0 }
 * Second, reducerMult is called, which doesn't have payload, so it
 * just returns state unchanged.
 * That's why there isn't any `product` prop.
 */

const next = addAndMult(initial, 4)
/*
 * {
 *   sum: 4,
 *   product: 4,
 *   totalOperations: 2
 * }
 *
 * First, reducerAdd is called, which changes `sum` = 0 + 4 = 4
 * Second, reducerMult is called, which changes `product` = 1 * 4 = 4
 * Both reducers modify `totalOperations`
 */

const final = addAndMult(next, 4)
/*
 * {
 *   sum: 8,
 *   product: 16,
 *   totalOperations: 4
 * }
 */
```

Use cases

combineReducers - each reducer manage own slice of state (e.g. state.todos and state.logging). This is useful when creating a root reducer.

reduceReducers - each reducer manage the same state. This is useful when chaining several reducers which are supposed to operate over the same state (this might happen for example when combining several reducer created using handleAction from redux-actions)

The difference is obvious from the final state shape.

ContentLicense: CC BY-SA 4.0

Title: correct usage of reduce-reducers

Body:
I don't understand what reduce-reducers is meant for. Should it be used in the case that I have 2 reducer functions containing the same action?

function reducerA(state, action){
   switch(action.type):
       ...
       case 'SAME_ACTION': {...state, field: state.field+1}
}

function reducerB(state, action){
   switch(action.type):
       ...
       case 'SAME_ACTION': {...state, field: state.field*2}
}

So if I call reduceReducer on reducerA and reducerB and action 'SAME_ACTION' is invoked for {field: 0} then I would have a next state {field: 2}?

Also it seems to me that it kind of concatenates reducers (meaning merging them under one key).

Am I right or does reduceReducer serve a different purpose?

Body:
The difference is:

combineReducers creates nested state

reduceReducers creates flat state

Consider following reducers. There are no action types to make things simpler:

// this reducer adds a payload to state.sum
// and tracks total number of operations
function reducerAdd(state, payload) {
  if (!state) state = { sum: 0, totalOperations: 0 }
  if (!payload) return state

  return {
    ...state,
    sum: state.sum + payload,
    totalOperations: state.totalOperations + 1
  }
}

// this reducer multiplies state.product by payload
// and tracks total number of operations
function reducerMult(state, payload) {
  if (!state) state = { product: 1, totalOperations: 0 }
  if (!payload) return state

  // `product` might be undefined because of
  // small caveat in `reduceReducers`, see below
  const prev = state.product || 1

  return {
    ...state,
    product: prev * payload,
    totalOperations: state.totalOperations + 1
  }
}

combineReducers

Each reducer gets an independent piece of state (see also http://redux.js.org/docs/api/combineReducers.html):

const rootReducer = combineReducers({
  add: reducerAdd,
  mult: reducerMult
})

const initialState = rootReducer(undefined)
/*
 * {
 *   add:  { sum: 0, totalOperations: 0 },
 *   mult: { product: 1, totalOperations: 0 },
 * }
 */

const first = rootReducer(initialState, 4)
/*
 * {
 *   add:  { sum: 4, totalOperations: 1 },
 *   mult: { product: 4, totalOperations: 1 },
 * }
 */
// This isn't interesting, let's look at second call...

const second = rootReducer(first, 4)
/*
 * {
 *   add:  { sum: 8, totalOperations: 2 },
 *   mult: { product: 16, totalOperations: 2 },
 * }
 */
// Now it's obvious, that both reducers get their own
// piece of state to work with

reduceReducers

All reducers share the same state

const addAndMult = reduceReducers(reducerAdd, reducerMult)

const initial = addAndMult(undefined)
/*
 * {
 *   sum: 0,
 *   totalOperations: 0
 * }
 *
 * First, reducerAdd is called, which gives us initial state { sum: 0 }
 * Second, reducerMult is called, which doesn't have payload, so it
 * just returns state unchanged.
 * That's why there isn't any `product` prop.
 */

const next = addAndMult(initial, 4)
/*
 * {
 *   sum: 4,
 *   product: 4,
 *   totalOperations: 2
 * }
 *
 * First, reducerAdd is called, which changes `sum` = 0 + 4 = 4
 * Second, reducerMult is called, which changes `product` = 1 * 4 = 4
 * Both reducers modify `totalOperations`
 */

const final = addAndMult(next, 4)
/*
 * {
 *   sum: 8,
 *   product: 16,
 *   totalOperations: 4
 * }
 */

Use cases

combineReducers - each reducer manage own slice of state (e.g. state.todos and state.logging). This is useful when creating a root reducer.

reduceReducers - each reducer manage the same state. This is useful when chaining several reducers which are supposed to operate over the same state (this might happen for example when combining several reducer created using handleAction from redux-actions)

The difference is obvious from the final state shape.


问:
Dictionary to JSON being serialised twice in swift 3
I'm trying to make a post request with the following dictionary which is converted to JSON

```<code>    let store = [
        "newTask" : [
            "project_name": "iOS",
            "total_time":0,
            "color":"blue"
        ]
    ]
</code>```

I am serialising this using the following code and then making a http-POST request using the following options:

```<code>        let jsonData = try? JSONSerialization.data(withJSONObject: store)

        var request = URLRequest(url: URL(string: "http://localhost:3000/store")!)
        request.httpMethod = "POST"
        request.httpBody = jsonData
</code>```

I am also running a json-server https://github.com/typicode/json-server with the following db.json file

```<code>{
 "store": [
  {
    "id": 0,
    "ios": {
      "project_name": "iOS",
      "total_time": 0,
      "color": "blue"
    }
  },
  {
    "id": 1,
    "elm": {
      "project_name": "elm",
      "total_time": 0,
      "color": "blue"
    }
  }
]
}
</code>```

The problem I am having is that the newly added item in the db looks incorrect with the following format:

```<code>{
  "{\"newTask\":{\"project_name\":\"iOS\",\"total_time\":0,\"color\":\"blue\"}}": "",
  "id": 10
},
</code>```

I am unsure as to why it is serialising the whole dictionary as the key and then an empty string as the value.

Update

Here is the code that posts this to the server:

```<code>let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data, error == nil else {                                                 // check for fundamental networking error
                    print("error=\(error)")
                    return
                }

                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(response)")
                }

                do {
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        print(json)

                    }

                } catch let error {
                    print(error.localizedDescription)
                }

            }
            task.resume()
</code>```

As a side note, I've tried pining this via postman and it all works ok. Attaching a screenshot of it below.

Any help will be appreciated, Thanks!

答:
When you construct your URLRequest would this line fix it for you?

```<code>    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
</code>```

In Postman you are sending it as application/json so I would expect you need to do the same in your swift code.

Body:
I'm trying to make a post request with the following dictionary which is converted to JSON

    let store = [
        "newTask" : [
            "project_name": "iOS",
            "total_time":0,
            "color":"blue"
        ]
    ]

I am serialising this using the following code and then making a http-POST request using the following options:

        let jsonData = try? JSONSerialization.data(withJSONObject: store)

        var request = URLRequest(url: URL(string: "http://localhost:3000/store")!)
        request.httpMethod = "POST"
        request.httpBody = jsonData

I am also running a json-server https://github.com/typicode/json-server with the following db.json file

{
 "store": [
  {
    "id": 0,
    "ios": {
      "project_name": "iOS",
      "total_time": 0,
      "color": "blue"
    }
  },
  {
    "id": 1,
    "elm": {
      "project_name": "elm",
      "total_time": 0,
      "color": "blue"
    }
  }
]
}

The problem I am having is that the newly added item in the db looks incorrect with the following format:

{
  "{\"newTask\":{\"project_name\":\"iOS\",\"total_time\":0,\"color\":\"blue\"}}": "",
  "id": 10
},

I am unsure as to why it is serialising the whole dictionary as the key and then an empty string as the value.

Update

Here is the code that posts this to the server:

let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data, error == nil else {                                                 // check for fundamental networking error
                    print("error=\(error)")
                    return
                }

                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(response)")
                }

                do {
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        print(json)

                    }

                } catch let error {
                    print(error.localizedDescription)
                }

            }
            task.resume()

As a side note, I've tried pining this via postman and it all works ok. Attaching a screenshot of it below.

Any help will be appreciated, Thanks!

Body:
When you construct your URLRequest would this line fix it for you?

    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

In Postman you are sending it as application/json so I would expect you need to do the same in your swift code.


问:
IntelliJ not updating Glassfish Deployment
IntelliJ is acting odd with its redeployment settings.

In the "updating applications" tab it has on the bottom for debugging:

,

I have tried to use all of the update options in order to update my application (update classes, update classes resources, restart), and NONE work to update my server. I have even closed and rebooted IntelliJ and the updates still don't appear.

The update is a simple alert message that is triggered when the index.html is loaded. It works when I load the html manually, but when I run the server, it does not alert, meaning it is still using a previous iteration of my server? This is really frustrating as I can't see any of my changes and don't know how to fix my server.

I am using the latest Glassfish server and latest IntelliJ IDE. It does update my resources EVENTUALLY, but not through some defined pattern as far as I can tell.

答:
Below is the copy of my answer from your other post. I would suggest to close this one and to continue discussion in single thread (if still needed).

The expected sequence is as follows:

make a change to a resource

update the application on the server with the mentioned 'Update <> application' action: 'Update resource' choice should be enough for an exploded application, redeploy/restart may be needed for archive artifact

reload (refresh) the page, that uses the resource in browser

I suspect you're missing the last (3) step. Please note, step (2) only updates the resource on the server, and to see a change in browser (on client) you should reload the corresponding resources from server by refreshing the page manually.

Hope that helps,


问:
Liferay 6.2 ga6 error

BUILD FAILED
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6-\portlets\build.xml:5: The following error occurred while executing this line:
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6\build-common-plugins.xml:5: The following error occurred while executing this line:
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6\build-common.xml:60: The following error occurred while executing this line:
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6\build-common-ivy.xml:130: The following error occurred while executing this line:
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6\build-common-ivy.xml:81: HTTP Authorization failure ```
</div>
</div>
</p>

<p>i am using liferay 6.2 ga6 with plugins sdk of liferay-sdk-ga6 when i am trying to create new portlet for the first time i am facing HTTP Authorization failure . My system is under proxy so in the build-common-ivy.xml file i have added the below line </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><setproxy proxyhost="172.21.2.17" proxyport="80" /></code>```

but i am facing the same issue.

But previously i was using liferay 6.2 ga2 with liferay-sdk-ga2 with same configuration and there everything works perfectly fine.

So i would like to know how this can be fixed and what is difference b/w this two versions and can i use liferay ga2 for by production. and how long support would be provided for ga2. and can i use liferay ga6 with plugins sdk liferay-sdk-ga2??

答:
Your post is short on details. It would be beneficial to have your entire build xml file, a copy paste of your logs, explicit information about your authentication type, and your portal ext properties file. However, off a hunch, I believe this is a known issue with liferay. Go into your build.{USERNAME}.properties file. Add there two lines </p>

```<code>ivy.version = 2.3.0
ivy.jar.url = http://repo1.maven.org/maven2/org/apache/ivy/ivy/${ivy.version}/ivy-${ivy.version}.jar
</code>```

<p>Give it another go with those properties </p>

Title: Liferay 6.2 ga6 error

Body:
BUILD FAILED
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6-\portlets\build.xml:5: The following error occurred while executing this line:
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6\build-common-plugins.xml:5: The following error occurred while executing this line:
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6\build-common.xml:60: The following error occurred while executing this line:
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6\build-common-ivy.xml:130: The following error occurred while executing this line:
E:\Microspace-Utility\liferay GA6\ant-sdk-ga6\build-common-ivy.xml:81: HTTP Authorization failure

i am using liferay 6.2 ga6 with plugins sdk of liferay-sdk-ga6 when i am trying to create new portlet for the first time i am facing HTTP Authorization failure . My system is under proxy so in the build-common-ivy.xml file i have added the below line

<setproxy proxyhost="172.21.2.17" proxyport="80" />

but i am facing the same issue.

But previously i was using liferay 6.2 ga2 with liferay-sdk-ga2 with same configuration and there everything works perfectly fine.

So i would like to know how this can be fixed and what is difference b/w this two versions and can i use liferay ga2 for by production. and how long support would be provided for ga2. and can i use liferay ga6 with plugins sdk liferay-sdk-ga2??

Body:
Your post is short on details. It would be beneficial to have your entire build xml file, a copy paste of your logs, explicit information about your authentication type, and your portal ext properties file. However, off a hunch, I believe this is a known issue with liferay. Go into your build.{USERNAME}.properties file. Add there two lines

ivy.version = 2.3.0
ivy.jar.url = http://repo1.maven.org/maven2/org/apache/ivy/ivy/${ivy.version}/ivy-${ivy.version}.jar

Give it another go with those properties


问:
This Not Working Inside Function
I couldn't find a solution to this, but the second this after mousedown will not work. I've seen different things about binding it but I haven't had any luck. (It works everywhere else in the code).</p>

```<code>$(".rightArrow").click(function () {
    var stop_slide = parseInt($(this).prev().css("marginLeft"));
    scroll_size = $(this).prev().children().size() * 177 * -1;
    if(stop_slide > scroll_size){
        var int00; // declared here to make it visible to clearInterval.
        $(this).mousedown(function(){
            int00 = setInterval(function() {
                $(this).prev().css( { marginLeft : "-=1px" } );
            }, 1);
        }).mouseup(function() {
            clearInterval(int00);
        });

    }

});
</code>```

答:
The this from the setInterval is different than the this from mousedown. Simply use a self variable, this way:

```<code>$(".rightArrow").click(function() {
  var stop_slide = parseInt($(this).prev().css("marginLeft"));
  scroll_size = $(this).prev().children().size() * 177 * -1;
  if (stop_slide > scroll_size) {
    var int00; // declared here to make it visible to clearInterval.
    $(this).mousedown(function() {
      var self = this;
      int00 = setInterval(function() {
        $(self).prev().css({
          marginLeft: "-=1px"
        });
      }, 1);
    }).mouseup(function() {
      clearInterval(int00);
    });
  }
});
</code>```

Each function declared via the function statement has its own context (this), hence, you need to store the previous context into a variable to access it in another function.

Another way is to use bind:

```<code> int00 = setInterval(function () {
    $(this).prev().css(...);
 }.bind(this));
</code>```

This will bind the current context (the current this) to the setInterval callback.

And if you use es2015, you can use arrow functions:

```<code>// the `this` from here
int00 = setInterval(() => {
   // will be the `this` from here
});
</code>```

The arrow functions have no context––they inherit the current context.

Title: This Not Working Inside Function

Body:
I couldn't find a solution to this, but the second this after mousedown will not work. I've seen different things about binding it but I haven't had any luck. (It works everywhere else in the code).

$(".rightArrow").click(function () {
    var stop_slide = parseInt($(this).prev().css("marginLeft"));
    scroll_size = $(this).prev().children().size() * 177 * -1;
    if(stop_slide > scroll_size){
        var int00; // declared here to make it visible to clearInterval.
        $(this).mousedown(function(){
            int00 = setInterval(function() {
                $(this).prev().css( { marginLeft : "-=1px" } );
            }, 1);
        }).mouseup(function() {
            clearInterval(int00);
        });

    }

});

Body:
The this from the setInterval is different than the this from mousedown. Simply use a self variable, this way:

$(".rightArrow").click(function() {
  var stop_slide = parseInt($(this).prev().css("marginLeft"));
  scroll_size = $(this).prev().children().size() * 177 * -1;
  if (stop_slide > scroll_size) {
    var int00; // declared here to make it visible to clearInterval.
    $(this).mousedown(function() {
      var self = this;
      int00 = setInterval(function() {
        $(self).prev().css({
          marginLeft: "-=1px"
        });
      }, 1);
    }).mouseup(function() {
      clearInterval(int00);
    });
  }
});

Each function declared via the function statement has its own context (this), hence, you need to store the previous context into a variable to access it in another function.

Another way is to use bind:

 int00 = setInterval(function () {
    $(this).prev().css(...);
 }.bind(this));

This will bind the current context (the current this) to the setInterval callback.

And if you use es2015, you can use arrow functions:

// the `this` from here
int00 = setInterval(() => {
   // will be the `this` from here
});

The arrow functions have no context––they inherit the current context.


问:
MouseListener doesn't work the first time
I am new to Java and I am creating a simple GUI. I have a label in Java in a JFrame, and when I click it, the program is supposed to show another frame and to hide the current one. I make it print as well to check whether the label (which acts like a button) works. The first time it does not work at all. It works the in the next attempts starting from the second click but it does not hide the current frame.

My code is:

```<code>private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {

    MainFrame mf = new MainFrame();
    jLabel4.addMouseListener(new MouseAdapter (){

        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("It works.");
            mf.setVisible(true);

            NewJFrame2 n2 = new NewJFrame2();
            n2.setVisible(false);

        }
    });
</code>```

Does anyone know how to fix it in order to work from the first click and hide the current frame?

答:
Java Labels are not capable of receiving ActionListener event, you should replace the label with a button. You don't click on labels you click on button, what could work for the label probably would be a property change listeners.

In this answer the Buttons have images, Just remember to create a folder unser src name it res then add the images you the button to display. You can replace the image file names with my file names in

```<code>//new ImageIcon(getClass().getResource("/res/image-file_name"));**

package StackOverflowProblemSets;

import sun.applet.Main;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Created by HACKER on 05/06/2017.
 * https://stackoverflow.com/questions/44370545/mouselistener-doesnt-work-
   the-first-time-and-there-are-other-errors
 */

class MainFrame extends JFrame {

    JButton button2 = new JButton("Go to Frame 2", new
ImageIcon(getClass().getResource("/res/ic_action_maps_blue.png")));

public MainFrame() {
    setSize(500, 500);
    getContentPane().setBackground(Color.RED);
    setLayout(new FlowLayout());

    add(button2);

    button2.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            setVisible(false);
            new Sample2().setVisible(true);
        }
    });}}

public class Sample2 extends JFrame {

JButton button4;

public Sample2() {

    setSize(500, 600);
    setLayout(new FlowLayout());
    getContentPane().setBackground(Color.YELLOW);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    MainFrame mf = new MainFrame();
    button4 = new JButton("Button 4", new
ImageIcon(getClass().getResource("/res/ic_action_alpha_icon_D.png")));
    add(button4);

    button4.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("It works.");
            mf.setVisible(true);
            setVisible(false);
        }
    });
}

public static void main(String[] args) {
    Sample2 sample2 = new Sample2();
    sample2.setVisible(true);
}}
</code>```

Body:
I am new to Java and I am creating a simple GUI. I have a label in Java in a JFrame, and when I click it, the program is supposed to show another frame and to hide the current one. I make it print as well to check whether the label (which acts like a button) works. The first time it does not work at all. It works the in the next attempts starting from the second click but it does not hide the current frame.

My code is:

private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {

    MainFrame mf = new MainFrame();
    jLabel4.addMouseListener(new MouseAdapter (){

        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("It works.");
            mf.setVisible(true);

            NewJFrame2 n2 = new NewJFrame2();
            n2.setVisible(false);

        }
    });

Does anyone know how to fix it in order to work from the first click and hide the current frame?

Body:
Java Labels are not capable of receiving ActionListener event, you should replace the label with a button. You don't click on labels you click on button, what could work for the label probably would be a property change listeners.

In this answer the Buttons have images, Just remember to create a folder unser src name it res then add the images you the button to display. You can replace the image file names with my file names in

//new ImageIcon(getClass().getResource("/res/image-file_name"));**

package StackOverflowProblemSets;

import sun.applet.Main;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Created by HACKER on 05/06/2017.
 * https://stackoverflow.com/questions/44370545/mouselistener-doesnt-work-
   the-first-time-and-there-are-other-errors
 */

class MainFrame extends JFrame {

    JButton button2 = new JButton("Go to Frame 2", new
ImageIcon(getClass().getResource("/res/ic_action_maps_blue.png")));

public MainFrame() {
    setSize(500, 500);
    getContentPane().setBackground(Color.RED);
    setLayout(new FlowLayout());

    add(button2);

    button2.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            setVisible(false);
            new Sample2().setVisible(true);
        }
    });}}

public class Sample2 extends JFrame {

JButton button4;

public Sample2() {

    setSize(500, 600);
    setLayout(new FlowLayout());
    getContentPane().setBackground(Color.YELLOW);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    MainFrame mf = new MainFrame();
    button4 = new JButton("Button 4", new
ImageIcon(getClass().getResource("/res/ic_action_alpha_icon_D.png")));
    add(button4);

    button4.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("It works.");
            mf.setVisible(true);
            setVisible(false);
        }
    });
}

public static void main(String[] args) {
    Sample2 sample2 = new Sample2();
    sample2.setVisible(true);
}}


问:
Send ISOMsg to ISOServer
I have to send ISO8583 messages to an ISOServer using jPOS. I was able to communicate with a QServer from a client-simulator sending messages and getting responses. Now, I have to implement a java project (client) that sends those messages to that same server.

I have a QServer listening on port 10000 and an ISOMsg object in the main class of my project.
How can I send this message to the server (localhost:10000) ?

Thank you in advance.

答:
The best thing you can do is not to use a main class at all, but use the Client Simulator replacing the client simulator deploy descriptor by one that uses a QBean written by you.Chapters 7.4 - 7.6 of the programmers guide. Walk you through the process of creating one, you just need to change the code to get the MUX (you can use the ClientSimulator code as a base to do that) and use it to make a request as the client simulator does.

Here you have an example QBean that sends a request at the start face and prints the response.

```<code>package stack.examples;

import org.jpos.iso.ISOMsg;
import org.jpos.iso.MUX;
import org.jpos.iso.packager.ISO87APackager;
import org.jpos.q2.QBeanSupport;
import org.jpos.q2.iso.QMUX;
public class SendMessageQBean extends  QBeanSupport{

    @Override
    protected void startService() throws Exception {
        super.startService();
        ISOMsg request = new ISOMsg();

        request.setMTI("0200");

        request.set(2, "16");

        request.set(2, "5421287475388412");

        request.set(3, "000000");

        request.set(4, "400.0");

        request.set(7, "0716070815");

        request.set(11, "844515");

        MUX mux = QMUX.getMUX(cfg.get("dest-mux", "clientsimulator-mux"));
        log.info("sending request", request);
        ISOMsg response = mux.request(request, cfg.getInt("timeout", 5000));

        log.info("received response", response);
    }

}
</code>```

Hope this point you in the right direction.

Also if you really want to write a main for understanding the basic concepts here you have a minimalist code (without muxes, logger, etc).

```<code>package stack.examples;

import java.io.IOException;

import org.jpos.iso.ISOChannel;
import org.jpos.iso.ISOException;
import org.jpos.iso.ISOMsg;
import org.jpos.iso.ISOPackager;
import org.jpos.iso.channel.XMLChannel;
import org.jpos.iso.packager.XMLPackager;

public class JposClient {

    public static void main(String[] args) throws ISOException, IOException {
        ISOPackager packager = new XMLPackager();
        ISOChannel channel = new XMLChannel("localhost", 10000,packager);
        channel.connect();
        ISOMsg request = new ISOMsg();

        request.setMTI("0200");

        request.set(2, "16");

        request.set(2, "5421287475388412");

        request.set(3, "000000");

        request.set(4, "400.0");

        request.set(7, "0716070815");

        request.set(11, "844515");

        channel.send(request);

        ISOMsg response = channel.receive();

        response.dump(System.out, "response:");

    }

}
</code>```

Title: Send ISOMsg to ISOServer

Body:
The best thing you can do is not to use a main class at all, but use the Client Simulator replacing the client simulator deploy descriptor by one that uses a QBean written by you.Chapters 7.4 - 7.6 of the programmers guide. Walk you through the process of creating one, you just need to change the code to get the MUX (you can use the ClientSimulator code as a base to do that) and use it to make a request as the client simulator does.

Here you have an example QBean that sends a request at the start face and prints the response.

package stack.examples;

import org.jpos.iso.ISOMsg;
import org.jpos.iso.MUX;
import org.jpos.iso.packager.ISO87APackager;
import org.jpos.q2.QBeanSupport;
import org.jpos.q2.iso.QMUX;
public class SendMessageQBean extends  QBeanSupport{

    @Override
    protected void startService() throws Exception {
        super.startService();
        ISOMsg request = new ISOMsg();

        request.setMTI("0200");

        request.set(2, "16");

        request.set(2, "5421287475388412");

        request.set(3, "000000");

        request.set(4, "400.0");

        request.set(7, "0716070815");

        request.set(11, "844515");

        MUX mux = QMUX.getMUX(cfg.get("dest-mux", "clientsimulator-mux"));
        log.info("sending request", request);
        ISOMsg response = mux.request(request, cfg.getInt("timeout", 5000));

        log.info("received response", response);
    }

}

Hope this point you in the right direction.

Also if you really want to write a main for understanding the basic concepts here you have a minimalist code (without muxes, logger, etc).

package stack.examples;

import java.io.IOException;

import org.jpos.iso.ISOChannel;
import org.jpos.iso.ISOException;
import org.jpos.iso.ISOMsg;
import org.jpos.iso.ISOPackager;
import org.jpos.iso.channel.XMLChannel;
import org.jpos.iso.packager.XMLPackager;

public class JposClient {

    public static void main(String[] args) throws ISOException, IOException {
        ISOPackager packager = new XMLPackager();
        ISOChannel channel = new XMLChannel("localhost", 10000,packager);
        channel.connect();
        ISOMsg request = new ISOMsg();

        request.setMTI("0200");

        request.set(2, "16");

        request.set(2, "5421287475388412");

        request.set(3, "000000");

        request.set(4, "400.0");

        request.set(7, "0716070815");

        request.set(11, "844515");

        channel.send(request);

        ISOMsg response = channel.receive();

        response.dump(System.out, "response:");

    }

}


问:
How to call npm version (to update my own package's version and then commit)
Nothing happens when I run

```<code>npm version minor -m "test"
</code>```

As a note, there is output if I run npm version without any arguments:

```<code>$ npm version
{ 'my-app': '0.7.0',
  npm: '4.2.0',
  ares: '1.10.1-DEV',
  cldr: '30.0.3',
  http_parser: '2.7.0',
  icu: '58.2',
  modules: '51',
  node: '7.10.0',
  openssl: '1.0.2k',
  tz: '2016j',
  unicode: '9.0',
  uv: '1.11.0',
  v8: '5.5.372.43',
  zlib: '1.2.11' }
</code>```

How am I supposed to use npm-version? I expect it to update the version number in package.json, run the 'version' script that I've specified in the package.json scripts list, and then commit. I can use npm run version to execute the 'version' script that I specified, but how do I run npm-version correctly?

答:
If you are on windows a new version of nodejs will do the work. If on Linux ubuntu  a :
Sudo apt-get install npm, will do the work too</p>

Body:
Nothing happens when I run

npm version minor -m "test"

As a note, there is output if I run npm version without any arguments:

$ npm version
{ 'my-app': '0.7.0',
  npm: '4.2.0',
  ares: '1.10.1-DEV',
  cldr: '30.0.3',
  http_parser: '2.7.0',
  icu: '58.2',
  modules: '51',
  node: '7.10.0',
  openssl: '1.0.2k',
  tz: '2016j',
  unicode: '9.0',
  uv: '1.11.0',
  v8: '5.5.372.43',
  zlib: '1.2.11' }

How am I supposed to use npm-version? I expect it to update the version number in package.json, run the 'version' script that I've specified in the package.json scripts list, and then commit. I can use npm run version to execute the 'version' script that I specified, but how do I run npm-version correctly?


问:
Error when opening SQLite Connection on C#?
I'm trying to connect and select data from a SQLite database table but it's showing me this error in con.Open() line:

An unhandled exception of type 'System.AccessViolationException'
  occurred in SQLite.NET.dll

Attempted to read or write protected memory. This is often an
  indication that other memory is corrupt

Here's my code:

```<code>SQLiteConnection con = new SQLiteConnection("Data Source = db.sqlite; Version=3;");
con.Open();

SQLiteCommand command = new SQLiteCommand("Select * from [user] where login=@login and password=@password", con);

command.Parameters.Add("@login", textBox1.Text);
command.Parameters.Add("@password", textBox2.Text);
</code>```

I also added reference to SQLite .dll.

What is the cause of this error?

答: The problem is that you try to embedd your database into your assembly. That is not a good idea since that memory is read only.</p>

Body:
I'm trying to connect and select data from a SQLite database table but it's showing me this error in con.Open() line:

An unhandled exception of type 'System.AccessViolationException'
  occurred in SQLite.NET.dll

Attempted to read or write protected memory. This is often an
  indication that other memory is corrupt

Here's my code:

SQLiteConnection con = new SQLiteConnection("Data Source = db.sqlite; Version=3;");
con.Open();

SQLiteCommand command = new SQLiteCommand("Select * from [user] where login=@login and password=@password", con);

command.Parameters.Add("@login", textBox1.Text);
command.Parameters.Add("@password", textBox2.Text);

I also added reference to SQLite .dll.

What is the cause of this error?


问:
Implict rule cancellation in Makefile
I have come across the following line in U-boot Makefile ( https://github.com/siemens/u-boot/blob/master/Makefile#L128 ) with comment "Cancel implicit rules on top Makefile".
Can you help me to understand the following line, how/what will happen while executing the following line by make utility.</p>

```<code>$(CURDIR)/Makefile Makefile: ;
</code>```

答:
See How Makefiles Are Remade:

If you know that one or more of your makefiles cannot be remade and you want to keep make from performing an implicit rule search on them, perhaps for efficiency reasons, you can use any normal method of preventing implicit rule look-up to do so. For example, you can write an explicit rule with the makefile as the target, and an empty recipe.

And that is exactly what $(CURDIR)/Makefile Makefile: ; rule does - it has an empty recipe.

Title: Implict rule cancellation in Makefile

Body:
I have come across the following line in U-boot Makefile ( https://github.com/siemens/u-boot/blob/master/Makefile#L128 ) with comment "Cancel implicit rules on top Makefile".
Can you help me to understand the following line, how/what will happen while executing the following line by make utility.

$(CURDIR)/Makefile Makefile: ;


问:
How to read NetCDF file and write to CSV using Python
My aim is to access data from a netcdf file and write to a CSV file in the following format.

```<code>Latitude  Longitude Date1  Date2  Date3
100       200       <-- MIN_SFC values -->
</code>```

So far I have accessed the variables, written the header to the file and populated the lat/lons.

How can I access the MIN_SFC values for specified lon,lat coordinates and dates and then write to a CSV file.

I'm a python newbie if there is a better way to go about this please let me know.

NetCDF file info:

```<code>Dimensions:
  time = 7
  latitude = 292
  longitude =341

Variables:
  float MIN_SFC (time=7, latitude = 292, longitude = 341)
</code>```

Here's what I've tried:

 from netCDF4 import Dataset, num2date

 filename = "C:/filename.nc"

 nc = Dataset(filename, 'r', Format='NETCDF4')
 print nc.variables

 print 'Variable List'

 for var in nc.variables:
    print var, var.units, var.shape

 # get coordinates variables
 lats = nc.variables['latitude'][:]
 lons = nc.variables['longitude'][:]

 sfc= nc.variables['Min_SFC'][:]
 times = nc.variables['time'][:]

 # convert date, how to store date only strip away time?
 print "Converting Dates"
 units = nc.variables['time'].units
 dates = num2date (times[:], units=units, calendar='365_day')

 #print [dates.strftime('%Y%m%d%H') for date in dates]

 header = ['Latitude', 'Longitude']

 # append dates to header string

 for d in dates:
    print d
    header.append(d)

 # write to file
 import csv

 with open('Output.csv', 'wb') as csvFile:
    outputwriter = csv.writer(csvFile, delimiter=',')
    outputwriter.writerow(header)
    for lat, lon in zip(lats, lons):
      outputwriter.writerow( [lat, lon] )

 # close the output file
 csvFile.close()

 # close netcdf
 nc.close()```
</div>
</div>
</p>

<p><strong>UPDATE:</strong></p>

<p>I've updated the code that writes the CSV file, there's an attribute error, because the lat/lon are doubles.</p>

<p>AttributeError: 'numpy.float32' object has no attribute 'append'</p>

<p>Any way to cast to a string in python? Do you think it'll work?</p>

<p>I've noticed a number of values returned as "--" when I printed values to the console. I'm wondering if this represents the fillValue or missingValue defined as -32767.0. </p>

<p>I'm also wondering whether the variables of the 3d dataset should be accessed by lats = nc.variables['latitude'][:][:] or lats = nc.variables['latitude'][:][:,:] ?  </p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code># the csv file is closed when you leave the block
with open('output.csv', 'wb') as csvFile:
    outputwriter = csv.writer(csvFile, delimiter=',')
    for time_index, time in enumerate(times): # pull the dates out for the header
         t = num2date(time, units = units, calendar='365_day')
         header.append(t)
    outputwriter.writerow(header)
    for lat_index, lat in enumerate(lats):
        content = lat
        print lat_index
        for lon_index, lon in enumerate(lons):
            content.append(lon)
            print lon_index
            for time_index, time in enumerate(times): # for a date
                # pull out the data
                data = sfc[time_index,lat_index,lon_index]
                content.append(data)
                outputwriter.writerow(content)</code>```

答:
Rich Signell's answer was incredibly helpful! Just as a note, it's important to also import datetime, and when extracting times, it's necessary to use the following code:

```<code>import datetime
import netCDF4
import pandas as pd
import matplotlib.pyplot as plt

...

# 2. Specify the exact time period you want:
start = datetime.datetime(2005,1,1,0,0,0)
stop = datetime.datetime(2010,12,31,0,0,0)
</code>```

I then looped over all the regions that I needed for my dataset.

Body:
My aim is to access data from a netcdf file and write to a CSV file in the following format.

Latitude  Longitude Date1  Date2  Date3
100       200       <-- MIN_SFC values -->

So far I have accessed the variables, written the header to the file and populated the lat/lons.

How can I access the MIN_SFC values for specified lon,lat coordinates and dates and then write to a CSV file.

I'm a python newbie if there is a better way to go about this please let me know.

NetCDF file info:

Dimensions:
  time = 7
  latitude = 292
  longitude =341

Variables:
  float MIN_SFC (time=7, latitude = 292, longitude = 341)

Here's what I've tried:

 from netCDF4 import Dataset, num2date

 filename = "C:/filename.nc"

 nc = Dataset(filename, 'r', Format='NETCDF4')
 print nc.variables

 print 'Variable List'

 for var in nc.variables:
    print var, var.units, var.shape

 # get coordinates variables
 lats = nc.variables['latitude'][:]
 lons = nc.variables['longitude'][:]

 sfc= nc.variables['Min_SFC'][:]
 times = nc.variables['time'][:]

 # convert date, how to store date only strip away time?
 print "Converting Dates"
 units = nc.variables['time'].units
 dates = num2date (times[:], units=units, calendar='365_day')

 #print [dates.strftime('%Y%m%d%H') for date in dates]

 header = ['Latitude', 'Longitude']

 # append dates to header string

 for d in dates:
    print d
    header.append(d)

 # write to file
 import csv

 with open('Output.csv', 'wb') as csvFile:
    outputwriter = csv.writer(csvFile, delimiter=',')
    outputwriter.writerow(header)
    for lat, lon in zip(lats, lons):
      outputwriter.writerow( [lat, lon] )

 # close the output file
 csvFile.close()

 # close netcdf
 nc.close()

UPDATE:

I've updated the code that writes the CSV file, there's an attribute error, because the lat/lon are doubles.

AttributeError: 'numpy.float32' object has no attribute 'append'

Any way to cast to a string in python? Do you think it'll work?

I've noticed a number of values returned as "--" when I printed values to the console. I'm wondering if this represents the fillValue or missingValue defined as -32767.0.

I'm also wondering whether the variables of the 3d dataset should be accessed by lats = nc.variables['latitude'][:][:] or lats = nc.variables['latitude'][:][:,:] ?

# the csv file is closed when you leave the block
with open('output.csv', 'wb') as csvFile:
    outputwriter = csv.writer(csvFile, delimiter=',')
    for time_index, time in enumerate(times): # pull the dates out for the header
         t = num2date(time, units = units, calendar='365_day')
         header.append(t)
    outputwriter.writerow(header)
    for lat_index, lat in enumerate(lats):
        content = lat
        print lat_index
        for lon_index, lon in enumerate(lons):
            content.append(lon)
            print lon_index
            for time_index, time in enumerate(times): # for a date
                # pull out the data
                data = sfc[time_index,lat_index,lon_index]
                content.append(data)
                outputwriter.writerow(content)

Body:
Rich Signell's answer was incredibly helpful! Just as a note, it's important to also import datetime, and when extracting times, it's necessary to use the following code:

import datetime
import netCDF4
import pandas as pd
import matplotlib.pyplot as plt

...

# 2. Specify the exact time period you want:
start = datetime.datetime(2005,1,1,0,0,0)
stop = datetime.datetime(2010,12,31,0,0,0)

I then looped over all the regions that I needed for my dataset.


问:
Turbo Prolog execution order
I'm trying to understand why am I getting the result that I am. Lets say that this is the code and result:

Sorry if this is trivial, but there isn't too many sources online about this... If the output of d(3) makes sense to me, then e(3) doesn't at all.
why does moving the write in cases like this reverse the order?

I'm guessing it has something to do with the recursion, but I'm still clueless at why.

答:
This is because in the first case: You first write and then recursively call d(N1), so for example d(3) will write 3 and then call d(2) etc...

In the second case: You first call e(N1) and then write and this changes the order because for example e(1) will call e(0) which will call e(-1) which will succeed and then e(0) will write 0 then e(1) will write 1 and so on...

Title: Turbo Prolog execution order


问:
Reduce Bootstrap list width
I am creating a list and styling it with Bootstrap. The HTML looks something like this:

```<code><div class="list-group">
    <a href="/link" class="list-group-item list-group-item-success">Name</a>
    <a href="/link" class="list-group-item list-group-item-danger">Name</a>
</div>
</code>```

When this displays, the list elements take up the whole page.

If not for the coloring, this would not be a big deal. How can I make the list elements stretch only as far as the text? Thanks!

答:
try adding style display:inline-block to the .list-group

```<code>.list-group{
      display:inline-block;
 }

<div class="list-group">
    <a href="/link" class="list-group-item list-group-item-success">Name</a>
    <a href="/link" class="list-group-item list-group-item-danger">Name</a>
</div>
</code>```

Title: Reduce Bootstrap list width

Body:
I am creating a list and styling it with Bootstrap. The HTML looks something like this:

    Name
    Name

When this displays, the list elements take up the whole page.

If not for the coloring, this would not be a big deal. How can I make the list elements stretch only as far as the text? Thanks!

Body:
try adding style display:inline-block to the .list-group

.list-group{
      display:inline-block;
 }

<div class="list-group">
    <a href="/link" class="list-group-item list-group-item-success">Name</a>
    <a href="/link" class="list-group-item list-group-item-danger">Name</a>
</div>


问:
Environment variable to use tensorflow without cuDNN doesn't work
I don't want to install cuDNN on a computer for which I haven't sudo privileges. For my TensorFlow model I don't need cuDNN, therefore I use the environment variable TF_USE_CUDNN=0. However, I get:

```<code>ImportError: libcudnn.so.5: cannot open shared object file: No such file or directory
</code>```

How I can use TensorFlow without cuDNN?

答: As far as I can tell from the code that reads the environment variable and its callers, the TF_USE_CUDNN environment variable only disables the use of cuDNN at runtime. Due to the way the standard TensorFlow-on-GPU distribution is linked, it still requires you to install the cuDNN library, because it will be loaded with the rest of the module. The easiest workaround would be to install cuDNN locally in your $HOME/lib directory, and set up LD_LIBRARY_PATH to look for the library there.

Body:
I don't want to install cuDNN on a computer for which I haven't sudo privileges. For my TensorFlow model I don't need cuDNN, therefore I use the environment variable TF_USE_CUDNN=0. However, I get:

ImportError: libcudnn.so.5: cannot open shared object file: No such file or directory

How I can use TensorFlow without cuDNN?


问:
What do DateTime? and using(var x = new y()) mean?
I don't understand what the following lines mean, please explain them to me.

1.

```<code>DateTime? pInsertDate;
</code>```

At this variable declaration, What does ? mean?

2.

```<code>using (TransactionScope scope = new TransactionScope())
</code>```

At this object creation, What does using mean?

答: this is syntax for Nullable Types </p>

Body:
I don't understand what the following lines mean, please explain them to me.

1.

DateTime? pInsertDate;

At this variable declaration, What does ? mean?

2.

using (TransactionScope scope = new TransactionScope())

At this object creation, What does using mean?

Body: this is syntax for Nullable Types


问:
State value `undefined` on state onChange
Writing a component named Member where I'm doing some calculations which I store in this.state before sending it somewhere else, but I got a problem, when firing one of onChange handlers some values of state are undefined , but should be filled some value.

Component Member

```<code>import React from "react";

import {calcSCR, difference, multiply} from "../../utils/Calculations";
import {SCR_COEFF} from "../../constants/calc";

class Member extends React.Component {

    constructor(props){
        super(props);

        this.state = {
            id: "1",
            full_name: 'Mocked member 1',
            role: 'Developer',
            salary: 1650,
            hourly_cost: 19.6, // SCR = (gross * coeff) / 100
            project_data: {
                project_id: '1',
                hourly_rate: 40,
                occupation: 50,
                estimate_hours: 70,
                revenue: 2800,// revenue = estimate_hours * hourly_rate
                cost: 1372,// cost = estimate_hours * hourly_cost
                profit: 1428// profit = revenue - cost
            }
        };

        this.onSalaryChange = this.onSalaryChange.bind(this);
        this.onHourlyCostChange = this.onHourlyCostChange.bind(this);
        this.onHourlyRateChange = this.onHourlyRateChange.bind(this);
        this.onEstimateHoursChange = this.onEstimateHoursChange.bind(this);
        this.onRevenueChange = this.onRevenueChange.bind(this);
        this.onCostChange = this.onCostChange.bind(this);
        this.onNameChange = this.onNameChange.bind(this);
        this.onOccupationChange = this.onOccupationChange.bind(this);

        this.save = this.save.bind(this);

    }

    save(){

    }

    onNameChange(e){
        this.setState({
            full_name: e.target.value
        })
    }

    onSalaryChange(e){
        let salary = e.target.value;

        this.setState({
            salary: salary,
            hourly_cost: calcSCR(salary, SCR_COEFF)
        })
    }

    onHourlyRateChange(e){
        let hourly_rate = e.target.value;
        let estimate_hours = this.state.project_data.estimate_hours;

        this.setState({
            project_data: {
                hourly_rate: hourly_rate,
                revenue: multiply(estimate_hours, hourly_rate)
            }
        })

    }

    onOccupationChange(e){
        this.setState({
            project_data: {
                occupation: e.target.value
            }
        })
    }

    onEstimateHoursChange(e){
        let estimate_hours = e.target.value;

        this.setState({
            project_data: {
                estimate_hours: estimate_hours,
                revenue: multiply(estimate_hours, this.state.project_data.hourly_rate),
                cost: multiply(estimate_hours,this.state.hourly_cost)
            }
        })

    }

    onHourlyCostChange(e){
        let hourly_cost = e.target.value;
        this.setState({
            hourly_cost: hourly_cost,
            project_data: {
                cost: multiply(this.state.project_data.estimate_hours, hourly_cost)
            }
        })
    }

    onRevenueChange(e){

        let revenue = e.target.value;

        this.setState({
            project_data: {
                revenue: revenue,
                profit: difference(revenue,this.state.project_data.cost)
            }
        })
    }

    onCostChange(e){

        let cost = e.target.value;

        this.setState({
            project_data: {
                cost: cost,
                profit: difference(this.state.project_data.revenue,cost)
            }
        })
    }

    render(){

        let {projectName} = this.props;
        let data = this.state;

        return (
            <div className="member">
                <a className="member__short_info" role="button" data-toggle="collapse" href={`#${data.id}`} aria-expanded="false" aria-controls={data.id}>
                    {data.full_name}
                </a>

                <div className="collapse member__member_full_info" id={data.id}>
                    <div className="member__full_info__row">
                        <div className="row">
                            <div className="col-sm-12 col-md-12 com-lg-12 member__full_info__header">
                                {projectName}
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="full_name" className="member__full_info__label">Member full name:</label>
                                <input id="full_name" type="text" name="full_name" value={data.full_name} onChange={this.onNameChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="salary" className="member__full_info__label">Salary:</label>
                                <input id="salary" type="text" name="salary" value={data.salary} onChange={this.onSalaryChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label className="member__full_info__label">Hourly cost: </label>
                                <input id="hourly_cost" type="text" name="hourly_cost" value={data.hourly_cost} onChange={this.onHourlyCostChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="hourly_rate" className="member__full_info__label">Hourly rate</label>
                                <input id="hourly_rate" type="text" name="hourly_rate" value={data.project_data.hourly_rate} onChange={this.onHourlyRateChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="occupation" className="member__full_info__label">Occupation in project (%): </label>
                                <input id="occupation" type="text" name="occupation" value={data.project_data.occupation} onChange={this.onOccupationChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="estimate_hours" className="member__full_info__label">Estimate hours: </label>
                                <input id="estimate_hours" type="text" name="estimate_hours" value={data.project_data.estimate_hours} onChange={this.onEstimateHoursChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-4 member__full_info__column">
                                <label className="member__full_info__label">Revenue: {data.project_data.revenue}</label>
                                {/*<input id="revenue" type="number" name="revenue" value={data.project_data.revenue} onChange={this.onRevenueChange}/>*/}
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-4 member__full_info__column">
                                <label className="member__full_info__label">Cost: {data.project_data.cost}</label>
                                {/*<input id="cost" type="number" name="cost" value={data.project_data.cost} onChange={this.onCostChange}/>*/}
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-4 member__full_info__column">
                                <label className="member__full_info__label">Profit: {data.project_data.profit}</label>
                            </div>

                            <div className="col-sm-12 member__full_info__save">
                                <button className="modal-component positive-btn no-margin" onClick={this.save}>Save</button>

                            </div>

                        </div>
                    </div>
                </div>
            </div>

        );
    }
}

export default Member;
</code>```

For example: inside onHourlyRateChange function estimate_hours becomes undefined after change.

Inside onEstimateHoursChange state variables this.state.project_data.hourly_rate and this.state.project_data.hourly_cost becomes undefined too. I have no Idea why it happens. Maybe you can give me some advices?

答:
Looks like all your nested state is experiencing problems, i.e., nested inside project_data. Component is only updating child elements one time, i.e. on your first key press and for all subsequent key presses, it is not updating anything, instead values goes undefined for nested state items which is very strange. A work around for this can be like you can move all your nested state items as single level state items.
Ex: </p>

```<code>this.state = {
            project_data: { hourly_rate: 40 }
    }
</code>```

<p>instead you can move child item to parent </p>

```<code>this.state = {
            project_data_hourly_rate: 40
    }
</code>```

Body:
Writing a component named Member where I'm doing some calculations which I store in this.state before sending it somewhere else, but I got a problem, when firing one of onChange handlers some values of state are undefined , but should be filled some value.

Component Member

import React from "react";

import {calcSCR, difference, multiply} from "../../utils/Calculations";
import {SCR_COEFF} from "../../constants/calc";

class Member extends React.Component {

    constructor(props){
        super(props);

        this.state = {
            id: "1",
            full_name: 'Mocked member 1',
            role: 'Developer',
            salary: 1650,
            hourly_cost: 19.6, // SCR = (gross * coeff) / 100
            project_data: {
                project_id: '1',
                hourly_rate: 40,
                occupation: 50,
                estimate_hours: 70,
                revenue: 2800,// revenue = estimate_hours * hourly_rate
                cost: 1372,// cost = estimate_hours * hourly_cost
                profit: 1428// profit = revenue - cost
            }
        };

        this.onSalaryChange = this.onSalaryChange.bind(this);
        this.onHourlyCostChange = this.onHourlyCostChange.bind(this);
        this.onHourlyRateChange = this.onHourlyRateChange.bind(this);
        this.onEstimateHoursChange = this.onEstimateHoursChange.bind(this);
        this.onRevenueChange = this.onRevenueChange.bind(this);
        this.onCostChange = this.onCostChange.bind(this);
        this.onNameChange = this.onNameChange.bind(this);
        this.onOccupationChange = this.onOccupationChange.bind(this);

        this.save = this.save.bind(this);

    }

    save(){

    }

    onNameChange(e){
        this.setState({
            full_name: e.target.value
        })
    }

    onSalaryChange(e){
        let salary = e.target.value;

        this.setState({
            salary: salary,
            hourly_cost: calcSCR(salary, SCR_COEFF)
        })
    }

    onHourlyRateChange(e){
        let hourly_rate = e.target.value;
        let estimate_hours = this.state.project_data.estimate_hours;

        this.setState({
            project_data: {
                hourly_rate: hourly_rate,
                revenue: multiply(estimate_hours, hourly_rate)
            }
        })

    }

    onOccupationChange(e){
        this.setState({
            project_data: {
                occupation: e.target.value
            }
        })
    }

    onEstimateHoursChange(e){
        let estimate_hours = e.target.value;

        this.setState({
            project_data: {
                estimate_hours: estimate_hours,
                revenue: multiply(estimate_hours, this.state.project_data.hourly_rate),
                cost: multiply(estimate_hours,this.state.hourly_cost)
            }
        })

    }

    onHourlyCostChange(e){
        let hourly_cost = e.target.value;
        this.setState({
            hourly_cost: hourly_cost,
            project_data: {
                cost: multiply(this.state.project_data.estimate_hours, hourly_cost)
            }
        })
    }

    onRevenueChange(e){

        let revenue = e.target.value;

        this.setState({
            project_data: {
                revenue: revenue,
                profit: difference(revenue,this.state.project_data.cost)
            }
        })
    }

    onCostChange(e){

        let cost = e.target.value;

        this.setState({
            project_data: {
                cost: cost,
                profit: difference(this.state.project_data.revenue,cost)
            }
        })
    }

    render(){

        let {projectName} = this.props;
        let data = this.state;

        return (

                <a className="member__short_info" role="button" data-toggle="collapse" href={`#${data.id}`} aria-expanded="false" aria-controls={data.id}>
                    {data.full_name}

                                {projectName}

                                Member full name:
                                <input id="full_name" type="text" name="full_name" value={data.full_name} onChange={this.onNameChange}/>

                                Salary:
                                <input id="salary" type="text" name="salary" value={data.salary} onChange={this.onSalaryChange}/>

                                Hourly cost:
                                <input id="hourly_cost" type="text" name="hourly_cost" value={data.hourly_cost} onChange={this.onHourlyCostChange}/>

                                Hourly rate
                                <input id="hourly_rate" type="text" name="hourly_rate" value={data.project_data.hourly_rate} onChange={this.onHourlyRateChange}/>

                                Occupation in project (%):
                                <input id="occupation" type="text" name="occupation" value={data.project_data.occupation} onChange={this.onOccupationChange}/>

                                Estimate hours:
                                <input id="estimate_hours" type="text" name="estimate_hours" value={data.project_data.estimate_hours} onChange={this.onEstimateHoursChange}/>

                                Revenue: {data.project_data.revenue}
                                {/*<input id="revenue" type="number" name="revenue" value={data.project_data.revenue} onChange={this.onRevenueChange}/>*/}

                                Cost: {data.project_data.cost}
                                {/*<input id="cost" type="number" name="cost" value={data.project_data.cost} onChange={this.onCostChange}/>*/}

                                Profit: {data.project_data.profit}

                                <button className="modal-component positive-btn no-margin" onClick={this.save}>Save</button>

        );
    }
}

export default Member;

For example: inside onHourlyRateChange function estimate_hours becomes undefined after change.

Inside onEstimateHoursChange state variables this.state.project_data.hourly_rate and this.state.project_data.hourly_cost becomes undefined too. I have no Idea why it happens. Maybe you can give me some advices?

Body:
Looks like all your nested state is experiencing problems, i.e., nested inside project_data. Component is only updating child elements one time, i.e. on your first key press and for all subsequent key presses, it is not updating anything, instead values goes undefined for nested state items which is very strange. A work around for this can be like you can move all your nested state items as single level state items.
Ex:

this.state = {
            project_data: { hourly_rate: 40 }
    }

instead you can move child item to parent

this.state = {
            project_data_hourly_rate: 40
    }


问:
How to export data in QIF format using codeigniter?
How I export my data in qif format. I didn't get any idea, how I Can?
Please help me to find out the way.</p>

答:
try this
//i don't know what is the qif text format, but with this you can write a file

write_file.php

```<code>public function write_qif( $info ){
    $this->load->helper(array('file','download'));
    $_info    = $this->some_model->get_info($info);//return object
    $qif_text = '
                 !Type:'.$_info->type.'//BANK
                 D'.$_info->date1.'//03/03/10
                 T-379.00
                 P'.$_info->city.'//CITY OF
                 ^
                 D'.$_info->date2.'//03/04/10
                 T-20.28
                 P'.$_info->maket_place.'//YOUR LOCAL SUPERMARKET
                 ^
                 D'.$_info->date3.'//03/03/10
                 T-421.35
                 P'.$_info->product.'//...WATER UTILITY
                 ';

    if ( ! write_file('./path/to/file.qif', $_info)){
        echo 'Unable to write the file';
    }
    else{
        $data = file_get_contents(.'/path/to/file.qif');
        $name = 'myqiffile.qif';

        force_download($name, $data);
        echo 'File written!';
    }
}
</code>```

Body:
try this
//i don't know what is the qif text format, but with this you can write a file

write_file.php

public function write_qif( $info ){
    $this->load->helper(array('file','download'));
    $_info    = $this->some_model->get_info($info);//return object
    $qif_text = '
                 !Type:'.$_info->type.'//BANK
                 D'.$_info->date1.'//03/03/10
                 T-379.00
                 P'.$_info->city.'//CITY OF
                 ^
                 D'.$_info->date2.'//03/04/10
                 T-20.28
                 P'.$_info->maket_place.'//YOUR LOCAL SUPERMARKET
                 ^
                 D'.$_info->date3.'//03/03/10
                 T-421.35
                 P'.$_info->product.'//...WATER UTILITY
                 ';

    if ( ! write_file('./path/to/file.qif', $_info)){
        echo 'Unable to write the file';
    }
    else{
        $data = file_get_contents(.'/path/to/file.qif');
        $name = 'myqiffile.qif';

        force_download($name, $data);
        echo 'File written!';
    }
}


问:
How to make a save function in Python
So I made a notepad clone in python but I am stuck.
I want to change the doNothing() Function to be a Save function.
I want the user to be able to name the file he wrote in the program and save it where he wants.</p>

```<code>from tkinter import *

# ********** Functions **********
def doNothing():
print("Ok, i won't!")

# ********** TK Initialization **********
root = Tk()
# ********** Main Menu **********
menu = Menu(root)
root.config(menu=menu)

subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New", command=doNothing)
subMenu.add_command(label="Open...", command=doNothing)
subMenu.add_command(label="Save", command=doNothing)
subMenu.add_command(label="Save As...", command=doNothing)
subMenu.add_separator()
subMenu.add_command(label="Page Setup...", command=doNothing)
subMenu.add_command(label="Print...", command=doNothing)
subMenu.add_separator()
subMenu.add_command(label="Exit", command=root.quit)

editMenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editMenu)
editMenu.add_command(label="Undo", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Cut", command=doNothing)
editMenu.add_command(label="Copy", command=doNothing)
editMenu.add_command(label="Paste", command=doNothing)
editMenu.add_command(label="Delete", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Find...", command=doNothing)
editMenu.add_command(label="Find Next", command=doNothing)
editMenu.add_command(label="Replace...", command=doNothing)
editMenu.add_command(label="Go To...", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Select All", command=doNothing)
editMenu.add_command(label="Time/Date", command=doNothing)

FormatMenu = Menu(menu)
menu.add_cascade(label="Format", menu=FormatMenu)
FormatMenu.add_command(label="Word Wrap", command=doNothing)
FormatMenu.add_command(label="Font...", command=doNothing)

ViewMenu = Menu(menu)
menu.add_cascade(label="View", menu=ViewMenu)
ViewMenu.add_command(label="Status Bar", command=doNothing)

HelpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=HelpMenu)
HelpMenu.add_command(label="View Help", command=doNothing)
HelpMenu.add_separator()
HelpMenu.add_command(label="About Editor", command=doNothing)

AboutMenu = Menu(menu)
menu.add_cascade(label="About", menu=AboutMenu)
AboutMenu.add_command(label="About the Developer", command=doNothing)
AboutMenu.add_separator()
AboutMenu.add_command(label="FK YOALL", command=doNothing)

# ********** Status Bar **********
status = Label(root, text="Preparing to do nothing...", bd=1, relief=SUNKEN,
anchor=W)
status.pack(side=BOTTOM, fill=X)

# ********** Text Area **********
text = Text(root, height=100, width=200)
text.pack()

# ********** Window Properties **********
root.maxsize(width=800, height=680)
root.minsize(width=666, height=666)
root.title('Text Editor')
root.mainloop()
</code>```

答:
There are three steps that you have to implement:

Retrieve the text inside your Text widget. You can do this with the Text.get method.

Prompt the user for a path where the text file is to be saved. You can do this with tkinter function filedialog.asksaveasfilename.

Write a text file with the text from step 1 and the path from step 2. See here for a simple example.

Title: How to make a save function in Python

Body:
So I made a notepad clone in python but I am stuck.
I want to change the doNothing() Function to be a Save function.
I want the user to be able to name the file he wrote in the program and save it where he wants.

from tkinter import *

# ********** Functions **********
def doNothing():
print("Ok, i won't!")

# ********** TK Initialization **********
root = Tk()
# ********** Main Menu **********
menu = Menu(root)
root.config(menu=menu)

subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New", command=doNothing)
subMenu.add_command(label="Open...", command=doNothing)
subMenu.add_command(label="Save", command=doNothing)
subMenu.add_command(label="Save As...", command=doNothing)
subMenu.add_separator()
subMenu.add_command(label="Page Setup...", command=doNothing)
subMenu.add_command(label="Print...", command=doNothing)
subMenu.add_separator()
subMenu.add_command(label="Exit", command=root.quit)

editMenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editMenu)
editMenu.add_command(label="Undo", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Cut", command=doNothing)
editMenu.add_command(label="Copy", command=doNothing)
editMenu.add_command(label="Paste", command=doNothing)
editMenu.add_command(label="Delete", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Find...", command=doNothing)
editMenu.add_command(label="Find Next", command=doNothing)
editMenu.add_command(label="Replace...", command=doNothing)
editMenu.add_command(label="Go To...", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Select All", command=doNothing)
editMenu.add_command(label="Time/Date", command=doNothing)

FormatMenu = Menu(menu)
menu.add_cascade(label="Format", menu=FormatMenu)
FormatMenu.add_command(label="Word Wrap", command=doNothing)
FormatMenu.add_command(label="Font...", command=doNothing)

ViewMenu = Menu(menu)
menu.add_cascade(label="View", menu=ViewMenu)
ViewMenu.add_command(label="Status Bar", command=doNothing)

HelpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=HelpMenu)
HelpMenu.add_command(label="View Help", command=doNothing)
HelpMenu.add_separator()
HelpMenu.add_command(label="About Editor", command=doNothing)

AboutMenu = Menu(menu)
menu.add_cascade(label="About", menu=AboutMenu)
AboutMenu.add_command(label="About the Developer", command=doNothing)
AboutMenu.add_separator()
AboutMenu.add_command(label="FK YOALL", command=doNothing)

# ********** Status Bar **********
status = Label(root, text="Preparing to do nothing...", bd=1, relief=SUNKEN,
anchor=W)
status.pack(side=BOTTOM, fill=X)

# ********** Text Area **********
text = Text(root, height=100, width=200)
text.pack()

# ********** Window Properties **********
root.maxsize(width=800, height=680)
root.minsize(width=666, height=666)
root.title('Text Editor')
root.mainloop()