问:
JavaScript - Convert dates and times (Chart.js and Moment.js)
If you have a better solution (perhaps a D3 solution for this problem): your answer will be appreciated!

I'm new to Chart.js and despite reading the docs of both Chart.js and Moment.js over and over again, I don't seem to possess the skills needed to create the chart I'd like to create.

That said, I have two arrays: one for the y-axis and one for the x-axis.

You can review, edit, fork and all that here on codepen.

It looks like this:

Now this looks fine, but like I said, I don't seem to possess the Moment.js skills to convert those hundreths of a second to a good looking: 2:31.70(mm:ss:SS) or 23.76(ss:SS) or 1:58.43.20(HH:mm:ss:SS).

Next to the time in hundreths being coverted to a normal time, readable for humans. The date is not quite good looking as well. I'd like to be able to convert this date to a local language and custom format. You may paste your codepen link in your answer. Or if you have any other good examples, that's highly appreciated as well!

HTML:

```<code><canvas id="myChart" width="auto" height="100"></canvas>
</code>```

JavaScript:

```<code>var ctx = document.getElementById("myChart").getContext("2d");

var myLineChart = new Chart(ctx, {
    type: "line",
    data: {
        labels: [
            // x-axis array containing dates as String in YYYY-MM-DD format
            // e.g. 2009-04-11 (April 11, 2009)
        ],
        datasets: [
            {
                label: "time",
                backgroundColor: "transparent",
                borderColor: "#0088d4",
                data: [
                    // y-axis array containing times as int in one hundredth of a second
                    // e.g.: 15170 (2 minutes, 31 seconds and 70 hundreth of a second)
                ]
            }
        ]
    },
    options: {
        elements: {
            line: {
                tension: 0
            }
        },
        scales: {
            yAxes: [
                {
                    ticks: {
                        stepSize: 1,
                        callback: function(tickValue, index, ticks) {
                            if (!(index % parseInt(ticks.length / 5))) {
                                return tickValue;
                            }
                        }
                    }
                }
            ]
        }
    }
});
</code>```

答:
You can create a duration and use moment-duration-format plug-in.

Since your input is an amount of seconds you can use moment.duration:

Moment.js also has duration objects. Where a moment is defined as single points in time, durations are defined as a length of time.

You can create a duration for your value using moment.duration(tickValue/100, 'seconds'). Then you can use moment-duration-format to transform 60 seconds to a string like 01:00.00

This is a plugin to the Moment.js JavaScript date library to add comprehensive formatting to Moment Durations.

Using moment-duration-format you can use the format() method for duration object. In your case, you can use 'mm:ss.SS' tokens where mm stands for minutes, ss stands for seconds and SS stands for milliseconds.

Since you want output like 00:23.80 instead of 23.80, yuo can use { trim: false } option.

So to change the displayed values for th y axis, your callback could be like the following:

```<code>callback: function(tickValue, index, ticks) {
  if (!(index % parseInt(ticks.length / 5))) {
    return moment.duration(tickValue/100, 's').format('mm:ss.SS');
  }
}
</code>```

Update after the comment about date: You can convert 2011-04-11 to april 14, 2011 using moment format():

```<code>moment('2011-04-11').format('MMMM DD, YYYY');
</code>```

You simply parse your input using moment(String) (since it matches known ISO 8601 formats) and then use format() using MMMM for month name, DD for day of the month and YYYY for the year.

Here my updated codepen that has the same code of the following snippet:

var ctx = document.getElementById("myChart").getContext("2d");

var myLineChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: [
      moment("2009-04-11").format('MMMM DD, YYYY'),
      moment("2009-05-16").format('MMMM DD, YYYY'),
      moment("2009-10-10").format('MMMM DD, YYYY'),
      moment("2009-11-28").format('MMMM DD, YYYY'),
      moment("2010-02-14").format('MMMM DD, YYYY'),
      moment("2010-03-13").format('MMMM DD, YYYY'),
      moment("2010-04-17").format('MMMM DD, YYYY'),
      moment("2010-12-18").format('MMMM DD, YYYY'),
      moment("2011-01-29").format('MMMM DD, YYYY'),
      moment("2011-03-12").format('MMMM DD, YYYY'),
      moment("2011-03-27").format('MMMM DD, YYYY'),
      moment("2011-05-15").format('MMMM DD, YYYY'),
      moment("2011-10-08").format('MMMM DD, YYYY'),
      moment("2011-11-27").format('MMMM DD, YYYY'),
      moment("2011-12-17").format('MMMM DD, YYYY'),
      moment("2012-03-10").format('MMMM DD, YYYY'),
      moment("2012-05-13").format('MMMM DD, YYYY'),
      moment("2012-10-07").format('MMMM DD, YYYY'),
      moment("2012-11-03").format('MMMM DD, YYYY'),
      moment("2012-11-10").format('MMMM DD, YYYY'),
      moment("2013-05-11").format('MMMM DD, YYYY'),
      moment("2013-10-12").format('MMMM DD, YYYY'),
      moment("2013-11-09").format('MMMM DD, YYYY'),
      moment("2014-01-11").format('MMMM DD, YYYY'),
      moment("2014-11-07").format('MMMM DD, YYYY'),
      moment("2014-11-15").format('MMMM DD, YYYY'),
      moment("2015-03-07").format('MMMM DD, YYYY'),
      moment("2015-04-12").format('MMMM DD, YYYY'),
      moment("2015-11-14").format('MMMM DD, YYYY'),
      moment("2016-11-12").format('MMMM DD, YYYY'),
      moment("2016-12-11").format('MMMM DD, YYYY'),
      moment("2017-01-08").format('MMMM DD, YYYY')
    ],
    datasets: [
      {
        label: "time",
        backgroundColor: "transparent",
        borderColor: "#0088d4",
        data: [
          15170,
          15026,
          15209,
          14335,
          14293,
          14725,
          14560,
          13511,
          13422,
          13230,
          13795,
          12830,
          13126,
          12988,
          12950,
          12750,
          12702,
          12395,
          12534,
          12276,
          12440,
          12462,
          12365,
          12465,
          12021,
          11976,
          12050,
          12016,
          11984,
          11972,
          11717,
          11995
        ]
      }
    ]
  },
  options: {
    elements: {
      line: {
        tension: 0
      }
    },
    scales: {
      yAxes: [
        {
          ticks: {
            stepSize: 1,
            callback: function(tickValue, index, ticks) {
              if (!(index % parseInt(ticks.length / 5))) {
                return moment.duration(tickValue/100, 's').format('mm:ss.SS',{ trim: false });
              }
            }
          }
        }
      ]
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

section {
  padding: 2rem 0;
}

.container {
  position: relative;
  margin: auto;
  width: 100%;
  max-width: 970px;
}</code>```

times chart

    <canvas id="myChart" width="auto" height="100"></canvas>

```

ContentLicense: CC BY-SA 4.0

Body:
If you have a better solution (perhaps a D3 solution for this problem): your answer will be appreciated!

I'm new to Chart.js and despite reading the docs of both Chart.js and Moment.js over and over again, I don't seem to possess the skills needed to create the chart I'd like to create.

That said, I have two arrays: one for the y-axis and one for the x-axis.

You can review, edit, fork and all that here on codepen.

It looks like this:

Now this looks fine, but like I said, I don't seem to possess the Moment.js skills to convert those hundreths of a second to a good looking: 2:31.70(mm:ss:SS) or 23.76(ss:SS) or 1:58.43.20(HH:mm:ss:SS).

Next to the time in hundreths being coverted to a normal time, readable for humans. The date is not quite good looking as well. I'd like to be able to convert this date to a local language and custom format. You may paste your codepen link in your answer. Or if you have any other good examples, that's highly appreciated as well!

HTML:

<canvas id="myChart" width="auto" height="100"></canvas>

JavaScript:

var ctx = document.getElementById("myChart").getContext("2d");

var myLineChart = new Chart(ctx, {
    type: "line",
    data: {
        labels: [
            // x-axis array containing dates as String in YYYY-MM-DD format
            // e.g. 2009-04-11 (April 11, 2009)
        ],
        datasets: [
            {
                label: "time",
                backgroundColor: "transparent",
                borderColor: "#0088d4",
                data: [
                    // y-axis array containing times as int in one hundredth of a second
                    // e.g.: 15170 (2 minutes, 31 seconds and 70 hundreth of a second)
                ]
            }
        ]
    },
    options: {
        elements: {
            line: {
                tension: 0
            }
        },
        scales: {
            yAxes: [
                {
                    ticks: {
                        stepSize: 1,
                        callback: function(tickValue, index, ticks) {
                            if (!(index % parseInt(ticks.length / 5))) {
                                return tickValue;
                            }
                        }
                    }
                }
            ]
        }
    }
});

Body:
You can create a duration and use moment-duration-format plug-in.

Since your input is an amount of seconds you can use moment.duration:

Moment.js also has duration objects. Where a moment is defined as single points in time, durations are defined as a length of time.

You can create a duration for your value using moment.duration(tickValue/100, 'seconds'). Then you can use moment-duration-format to transform 60 seconds to a string like 01:00.00

This is a plugin to the Moment.js JavaScript date library to add comprehensive formatting to Moment Durations.

Using moment-duration-format you can use the format() method for duration object. In your case, you can use 'mm:ss.SS' tokens where mm stands for minutes, ss stands for seconds and SS stands for milliseconds.

Since you want output like 00:23.80 instead of 23.80, yuo can use { trim: false } option.

So to change the displayed values for th y axis, your callback could be like the following:

callback: function(tickValue, index, ticks) {
  if (!(index % parseInt(ticks.length / 5))) {
    return moment.duration(tickValue/100, 's').format('mm:ss.SS');
  }
}

Update after the comment about date: You can convert 2011-04-11 to april 14, 2011 using moment format():

moment('2011-04-11').format('MMMM DD, YYYY');

You simply parse your input using moment(String) (since it matches known ISO 8601 formats) and then use format() using MMMM for month name, DD for day of the month and YYYY for the year.

Here my updated codepen that has the same code of the following snippet:

var ctx = document.getElementById("myChart").getContext("2d");

var myLineChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: [
      moment("2009-04-11").format('MMMM DD, YYYY'),
      moment("2009-05-16").format('MMMM DD, YYYY'),
      moment("2009-10-10").format('MMMM DD, YYYY'),
      moment("2009-11-28").format('MMMM DD, YYYY'),
      moment("2010-02-14").format('MMMM DD, YYYY'),
      moment("2010-03-13").format('MMMM DD, YYYY'),
      moment("2010-04-17").format('MMMM DD, YYYY'),
      moment("2010-12-18").format('MMMM DD, YYYY'),
      moment("2011-01-29").format('MMMM DD, YYYY'),
      moment("2011-03-12").format('MMMM DD, YYYY'),
      moment("2011-03-27").format('MMMM DD, YYYY'),
      moment("2011-05-15").format('MMMM DD, YYYY'),
      moment("2011-10-08").format('MMMM DD, YYYY'),
      moment("2011-11-27").format('MMMM DD, YYYY'),
      moment("2011-12-17").format('MMMM DD, YYYY'),
      moment("2012-03-10").format('MMMM DD, YYYY'),
      moment("2012-05-13").format('MMMM DD, YYYY'),
      moment("2012-10-07").format('MMMM DD, YYYY'),
      moment("2012-11-03").format('MMMM DD, YYYY'),
      moment("2012-11-10").format('MMMM DD, YYYY'),
      moment("2013-05-11").format('MMMM DD, YYYY'),
      moment("2013-10-12").format('MMMM DD, YYYY'),
      moment("2013-11-09").format('MMMM DD, YYYY'),
      moment("2014-01-11").format('MMMM DD, YYYY'),
      moment("2014-11-07").format('MMMM DD, YYYY'),
      moment("2014-11-15").format('MMMM DD, YYYY'),
      moment("2015-03-07").format('MMMM DD, YYYY'),
      moment("2015-04-12").format('MMMM DD, YYYY'),
      moment("2015-11-14").format('MMMM DD, YYYY'),
      moment("2016-11-12").format('MMMM DD, YYYY'),
      moment("2016-12-11").format('MMMM DD, YYYY'),
      moment("2017-01-08").format('MMMM DD, YYYY')
    ],
    datasets: [
      {
        label: "time",
        backgroundColor: "transparent",
        borderColor: "#0088d4",
        data: [
          15170,
          15026,
          15209,
          14335,
          14293,
          14725,
          14560,
          13511,
          13422,
          13230,
          13795,
          12830,
          13126,
          12988,
          12950,
          12750,
          12702,
          12395,
          12534,
          12276,
          12440,
          12462,
          12365,
          12465,
          12021,
          11976,
          12050,
          12016,
          11984,
          11972,
          11717,
          11995
        ]
      }
    ]
  },
  options: {
    elements: {
      line: {
        tension: 0
      }
    },
    scales: {
      yAxes: [
        {
          ticks: {
            stepSize: 1,
            callback: function(tickValue, index, ticks) {
              if (!(index % parseInt(ticks.length / 5))) {
                return moment.duration(tickValue/100, 's').format('mm:ss.SS',{ trim: false });
              }
            }
          }
        }
      ]
    }
  }
});

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

section {
  padding: 2rem 0;
}

.container {
  position: relative;
  margin: auto;
  width: 100%;
  max-width: 970px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

<section>
  <div class="container">
    <h2>times chart</h2>
  </div>
  <div class="container">
    <canvas id="myChart" width="auto" height="100"></canvas>
  </div>
</section>


来源: stackexchange

问:
Laravel , how to select data if relationship condition is true
i have this query

```<code>$organisationUserNotifications = OrganisationUserNotification::
            whereHas('user',function($user){
                $user->where('status',STATUS_ACTIVE);
            })
            ->orWhere('new_comment',ORGANISATION_NOTIFICATION_ACTIVE)
            ->orWhere('new_review',ORGANISATION_NOTIFICATION_ACTIVE)
            ->orWhere('new_salary',ORGANISATION_NOTIFICATION_ACTIVE)
            ->get();
</code>```

this query get result for all users who have new_comment->1 or new_review->1 or new_salary->1

i have user table

id name status

   1| us_1| 0

   2| us_2| 1

   3| us_3| 1

and notification table

id new_comment new_review new_salary

   1| 0| 1 | 1

   2| 1| 0 | 1

   3| 1| 0 | 1

this query get all rows because user 1 have status 0 or new_review 1
please any idea
how to verify other where if user is active , without leftjoin

答:
ok , i found the solution if anyone needs it</p>

```<code>$organisationUserNotifications = OrganisationUserNotification::
        whereHas('user',function($user){
            $user->where('status',STATUS_ACTIVE);
        })
        ->where(function($query){
           $query->orWhere('new_comment',ORGANISATION_NOTIFICATION_ACTIVE);
           $query->orWhere('new_review',ORGANISATION_NOTIFICATION_ACTIVE);
           $query->orWhere('new_salary',ORGANISATION_NOTIFICATION_ACTIVE);
        })
        ->get();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have this query

$organisationUserNotifications = OrganisationUserNotification::
            whereHas('user',function($user){
                $user->where('status',STATUS_ACTIVE);
            })
            ->orWhere('new_comment',ORGANISATION_NOTIFICATION_ACTIVE)
            ->orWhere('new_review',ORGANISATION_NOTIFICATION_ACTIVE)
            ->orWhere('new_salary',ORGANISATION_NOTIFICATION_ACTIVE)
            ->get();

this query get result for all users who have new_comment->1 or new_review->1 or new_salary->1

i have user table

id name status

   1| us_1| 0

   2| us_2| 1

   3| us_3| 1

and notification table

id new_comment new_review new_salary

   1| 0| 1 | 1

   2| 1| 0 | 1

   3| 1| 0 | 1

this query get all rows because user 1 have status 0 or new_review 1
please any idea
how to verify other where if user is active , without leftjoin

Body:
ok , i found the solution if anyone needs it

$organisationUserNotifications = OrganisationUserNotification::
        whereHas('user',function($user){
            $user->where('status',STATUS_ACTIVE);
        })
        ->where(function($query){
           $query->orWhere('new_comment',ORGANISATION_NOTIFICATION_ACTIVE);
           $query->orWhere('new_review',ORGANISATION_NOTIFICATION_ACTIVE);
           $query->orWhere('new_salary',ORGANISATION_NOTIFICATION_ACTIVE);
        })
        ->get();


问:
Looking for non-destructive counterpart of `splice ARRAY,OFFSET,LENGTH,LIST`
splice is "destructive"; i.e. it modifies its first argument "in place".

For example:

```<code>  DB<63> @a = (0, 1, 2, 3, 4, 5)

  DB<64> @b = (20, 30, 40)

  DB<65> splice( @a, 2, 3, @b )

  DB<66> x \@a
0  ARRAY(0x1daf6e0)
   0  0
   1  1
   2  20
   3  30
   4  40
   5  5
</code>```

(The splice expression above returns the elements spliced out, but in this question I'm interested only in slice's side effects.)

Q: Is there a "non-destructive" counterpart function of splice?

E.g. if @a and @b are as originally defined above, then the desired non_destructive_splice function would be such that after

```<code>@new_a = non_destructive_splice( @a, 2, 3, @b );
</code>```

...the variable @new_a would hold (0, 1, 20, 30, 40, 5), and @a would be left unchanged.

Body:
splice is "destructive"; i.e. it modifies its first argument "in place".

For example:

  DB<63> @a = (0, 1, 2, 3, 4, 5)

  DB<64> @b = (20, 30, 40)

  DB<65> splice( @a, 2, 3, @b )

  DB<66> x \@a
0  ARRAY(0x1daf6e0)
   0  0
   1  1
   2  20
   3  30
   4  40
   5  5

(The splice expression above returns the elements spliced out, but in this question I'm interested only in slice's side effects.)

Q: Is there a "non-destructive" counterpart function of splice?

E.g. if @a and @b are as originally defined above, then the desired non_destructive_splice function would be such that after

@new_a = non_destructive_splice( @a, 2, 3, @b );

...the variable @new_a would hold (0, 1, 20, 30, 40, 5), and @a would be left unchanged.

Body:
@new_a = @a;
splice @new_a, 2, 3, @b;


问:
How to copy projects in Android Studio?
I tried copying my Android Studio project but every time I do that it gives me errors. I read other questions and answers on this topics but none of this helped me.

When I copy a project and try to run it on the emulator it gives the following error:

"Installation failed with message Invalid File:
  C:...\app\build\intermediates\split-apk\debug\slices\slice_9.apk. It
  is possible that this issue is resolved by uninstalling an existing
  version of the apk if it is present, and then re-installing."

According to answers on similar questions, it should help to perform a 'clean project'. When I do this, the emulator starts but stops starting the app with a runtime error:

"java.lang.RuntimeException: Unable to instantiate activity
  ComponentInfo{nl.assortimens.hardlooptrainingapp/nl.assortimens.hardlooptrainingapp.MainMenuActivity}:
  java.lang.ClassNotFoundException: Didn't find class
  "nl.assortimens.hardlooptrainingapp.MainMenuActivity" on path:
  DexPathList[[zip file
  "/data/app/nl.assortimens.hardlooptrainingapp-1/base.apk"],nativeLibraryDirectories=[/data/app/nl.assortimens.hardlooptrainingapp-1/lib/x86,
  /vendor/lib, /system/lib]]"

How can I copy projects without errors or what should I do to fix those errors?

答: try to delete the intermediates folder and rebuild the project, if not delete the build folder and rebuild again

Title: How to copy projects in Android Studio?


问:
Adding const to function template pointer argument
Consider:

```<code>template<typename X>
inline typename std::enable_if< std::is_pointer<X>::value, void>::type
replyOk(X pointer)
{
    *pointer = *pointer; //for sake of example
}
</code>```

Is it possible to add constness to the pointed data so that *pointer = *pointer creates a compiler error.

For example I can do

```<code>...
replyOk(X const pointer)
...
</code>```

But this adds constness to the variable pointer not what it points to. I'm not sure that even makes sense...

答:
I don't see the point of the enable_if.

```<code>template<typename X>
inline void replyOk(const X* pointer) {
  //...
}
</code>```

Body:
Consider:

template<typename X>
inline typename std::enable_if< std::is_pointer<X>::value, void>::type
replyOk(X pointer)
{
    *pointer = *pointer; //for sake of example
}

Is it possible to add constness to the pointed data so that *pointer = *pointer creates a compiler error.

For example I can do

...
replyOk(X const pointer)
...

But this adds constness to the variable pointer not what it points to. I'm not sure that even makes sense...

Body:
I don't see the point of the enable_if.

template<typename X>
inline void replyOk(const X* pointer) {
  //...
}


问:
volttron.platform.web INFO: Web server not started
When I try to run volttron through Eclipse it gives me this message at the end:

```<code>volttron.platform.web INFO: Web server not started
</code>```

In the run configurations, the arguments I gave at first was -vv --developer-mode. It didn't recognize it, neither did it recognise -vv -developer-mode. The message was:

```<code>usage: main.py [OPTION]...
main.py: error: unrecognized arguments: --developer-mode
</code>```

When I remover developer-mode it gives me the first message.
I am using Ubuntu, Luna eclipse.

答:
Developer mode has been removed and is no longer needed.

To achieve the equivalent of the old developer mode do this:

```<code>volttron-ctl auth add
</code>```

Leave ever answer blank except for this:

```<code>credentials []: /.*/
</code>```

This will setup the platform to allow agents to connect without proper credentials which is needed for running an agent in a debugger.

You can find out more here: http://volttron.readthedocs.io/en/develop/devguides/agent_development/index.html

The web server message is just informing you that the VOLTTRON platform web server is not setup to start. This is not an error condition.

Th web server is used for platform discovery, the common agent restful API, and a few other features, none of which required for normal operation.

Body:
When I try to run volttron through Eclipse it gives me this message at the end:

volttron.platform.web INFO: Web server not started

In the run configurations, the arguments I gave at first was -vv --developer-mode. It didn't recognize it, neither did it recognise -vv -developer-mode. The message was:

usage: main.py [OPTION]...
main.py: error: unrecognized arguments: --developer-mode

When I remover developer-mode it gives me the first message.
I am using Ubuntu, Luna eclipse.

Body:
Developer mode has been removed and is no longer needed.

To achieve the equivalent of the old developer mode do this:

volttron-ctl auth add

Leave ever answer blank except for this:

credentials []: /.*/

This will setup the platform to allow agents to connect without proper credentials which is needed for running an agent in a debugger.

You can find out more here: http://volttron.readthedocs.io/en/develop/devguides/agent_development/index.html

The web server message is just informing you that the VOLTTRON platform web server is not setup to start. This is not an error condition.

Th web server is used for platform discovery, the common agent restful API, and a few other features, none of which required for normal operation.


问:
How to simulate android back button in react-native test
In componentDidMount I'm adding a listener to handle Android back navigation and would like to add tests around it's behaviour. How do I firstly test something in componentDidMount and secondly how would I simulate clicking the back button.

```<code>class Component extends React.Component {
  componentDidMount () {
    BackHandler.addEventListener('hardwareBackPress', () => {...})
  }
}
</code>```

答:
There are a couple ways you can approach this:

First, you could just assume that componentDidMount and BackHandler.addEventListener are going to work.  That would leave you just testing your function.  If you go that route, you'd probably want to register a named function, rather than an arrow function, in addEventListener so that you can target it in your test.

If for some reason, you want to test the full lifecycle, then Facebook actually has a mocked out BackHandler that lets you simulate a back press:

https://github.com/facebook/react-native/blob/master/Libraries/Utilities/mocks/BackHandler.js

You'd just need to import that mock into your test, mount the component in a test renderer and then trigger mockBackPress and watch to see if your function is called.

Body:
In componentDidMount I'm adding a listener to handle Android back navigation and would like to add tests around it's behaviour. How do I firstly test something in componentDidMount and secondly how would I simulate clicking the back button.

class Component extends React.Component {
  componentDidMount () {
    BackHandler.addEventListener('hardwareBackPress', () => {...})
  }
}


问:
How do I import an object into its own manager?
I realize that my logic is flawed and its causing a circular import.

Here's what I am trying to accomplish:

managers.py (kept separate from models.py)

```<code>class TicketManager(models.Manager):
    def create_in_atom(self, ticket):
        if type(ticket) is not Ticket:
            raise Exception('Not a Ticket object.')
</code>```

This produces this error:

NameError: global name 'Ticket' is not defined

And so then I tried to import it:

```<code>from models import Ticket
</code>```

Which produces:

ImportError: cannot import name Ticket

How do I check to see if an argument passed to a function of the TicketManager is of the type "Ticket", which the TickerManager falls under?

答:
Instead of import, you can dynamically get the model: </p>

```<code>from django.apps import AppConfig

class TicketManager(models.Manager):
    def create_in_atom(self, ticket):
        if type(ticket) is not AppConfig.get_model('Ticket'):
            raise Exception('Not a Ticket object.')
</code>```

Body:
I realize that my logic is flawed and its causing a circular import.

Here's what I am trying to accomplish:

managers.py (kept separate from models.py)

class TicketManager(models.Manager):
    def create_in_atom(self, ticket):
        if type(ticket) is not Ticket:
            raise Exception('Not a Ticket object.')

This produces this error:

NameError: global name 'Ticket' is not defined

And so then I tried to import it:

from models import Ticket

Which produces:

ImportError: cannot import name Ticket

How do I check to see if an argument passed to a function of the TicketManager is of the type "Ticket", which the TickerManager falls under?

Body:
Instead of import, you can dynamically get the model:

from django.apps import AppConfig

class TicketManager(models.Manager):
    def create_in_atom(self, ticket):
        if type(ticket) is not AppConfig.get_model('Ticket'):
            raise Exception('Not a Ticket object.')


问:
Why do I need two return values within a function?
This question is very basic and very simple but I need to understand it.

I have this function in React:

```<code>renderPosts() {
  return _.map(this.props.posts, post => {
    return (
      <li className="list-group-item" key={post.id}>
        { post.title }
      </li>
    );
  });
}
</code>```

Why do I need the first return?

Basically, the second return will return me the li's. Why do I need to return (first return) them again? I need someone to help me explain this part. I am just confused.

答:
The first return is going to return the result of _.map(), which returns individual posts.  The end result would be an array of posts as
 elements.

Body:
This question is very basic and very simple but I need to understand it.

I have this function in React:

renderPosts() {
  return _.map(this.props.posts, post => {
    return (

        { post.title }

    );
  });
}

Why do I need the first return?

Basically, the second return will return me the li's. Why do I need to return (first return) them again? I need someone to help me explain this part. I am just confused.

Body: The first return is going to return the result of _.map(), which returns individual posts.  The end result would be an array of posts as <li/> elements.


问:
Problems with Selecting a Gallery Image in OnActivityResult method
I got 2 problems in OnActivityResult method while trying to upload image accoding to this. How can I solve them?
The full code of the class is:

```<code>public class AddNewTourActivity : Activity
    {
        GettingCountry gettingCountry = new GettingCountry();
        private static int idOfChosenCountry, IdOfChosenCategory;
        private static string status, promptMessage;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.AddNewTour);

            //clearing lists
            GettingCountry.listOfCountriesRoot.Clear();
            GettingCountry.countriesList.Clear();

            GettingCategories gc = new GettingCategories();
            //Getting list of countries
            gettingCountry.Fetch();

            //clearing listCategoriesRoot
            GettingCategories.categoriesList.Clear();
            //getting categories method
            gc.GetCategories();
            Spinner categories_spinner = FindViewById<Spinner>(Resource.Id.categories_spinner);
            Spinner countries = FindViewById<Spinner>(Resource.Id.countries);
            //adapter
            ArrayAdapter adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, GettingCategories.categoriesList);
            ArrayAdapter adapterCountries = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, GettingCountry.countriesList);
            categories_spinner.Adapter = adapter;
            countries.Adapter = adapterCountries;
            countries.ItemSelected += Countries_ItemSelected;
            categories_spinner.ItemSelected += Categories_spinner_ItemSelected;
            //FindViewById<EditText>(Resource.Id.owner_id).Text = Login.user_id.ToString();

            var title = FindViewById<EditText>(Resource.Id.title);
            var image = FindViewById<ImageView>(Resource.Id.myImageView);
            var location = FindViewById<EditText>(Resource.Id.location);
            var description = FindViewById<EditText>(Resource.Id.description);
            var price = FindViewById<EditText>(Resource.Id.price);
            var min_capacity = FindViewById<EditText>(Resource.Id.min_capacity);
            var max_capacity = FindViewById<EditText>(Resource.Id.max_capacity);
            var duration = FindViewById<EditText>(Resource.Id.duration);
            var meet_place_address = FindViewById<EditText>(Resource.Id.meet_place_address);
            var meet_place_city = FindViewById<EditText>(Resource.Id.meet_place_city);
            var lat = FindViewById<EditText>(Resource.Id.lat);
            var lng = FindViewById<EditText>(Resource.Id.lng);

            //uploading image
            image.Click += Image_Click;
            //uploading image ENDED

            FindViewById<Button>(Resource.Id.add_tour_button).Click += delegate
            {
                //setting prompt message empty
                promptMessage = "";
                var client = new RestClient("http://api.locopal.com");
                var request = new RestRequest("/experience", Method.POST);

                //CHECKING THE CORRECTNESS OF THE USER'S INTRODUCTION TO ALL FIELDS
                if (title.Text.Length < 3)
                {
                    promptMessage += " Title must have at least 3 symbols.\n";
                }
                if (location.Text.Length < 3)
                {
                    promptMessage += " Location must have at least 3 symbols.\n";
                }
                if (description.Text.Length < 30)
                {
                    promptMessage += " Description length must be at least 30 symbols.\n";
                }

                //checking if price, capacity, etc... are integer values
                int res;
                bool priceIsInt = false;
                priceIsInt = Int32.TryParse(price.Text, out res);

                if (priceIsInt == false)
                {
                    promptMessage += " Price must be an integer value.\n";
                }

                bool minCapacityIsInt = false;
                minCapacityIsInt = Int32.TryParse(min_capacity.Text, out res);
                if (minCapacityIsInt == false)
                {
                    promptMessage += " Minimum capacity must be an integer value.\n";
                }

                bool maxCapacityIsInt = false;
                maxCapacityIsInt = Int32.TryParse(max_capacity.Text, out res);
                if (maxCapacityIsInt == false)
                {
                    promptMessage += " Maximum capacity must be an integer value.\n";
                }

                bool durationIsInt = false;
                durationIsInt = Int32.TryParse(duration.Text, out res);
                if (durationIsInt == false)
                {
                    promptMessage += " Duration must be an integer value.\n";
                }
                //checking if price, capacity, etc... are integer values ENDED

                if (meet_place_address.Text.Length < 3)
                {
                    promptMessage += " Address of meeting place must have at least 3 symbols.\n";
                }

                if (meet_place_city.Text.Length < 3)
                {
                    promptMessage += " City of meeting place must have at least 3 symbols.\n";
                }

                //checking if lat and lng are doubles
                double resDouble;

                bool latIsDouble = false;
                latIsDouble = Double.TryParse(lat.Text, out resDouble);
                if (latIsDouble == false)
                {
                    promptMessage += " Latitude must be a fractional value.\n";
                }

                bool lngIsDouble = false;
                lngIsDouble = Double.TryParse(lng.Text, out resDouble);
                if (lngIsDouble == false)
                {
                    promptMessage += " Longitude must be a fractional value.";
                }
                //checking if lat and lng are doubles ENDED

                //CHECKING THE CORRECTNESS OF THE USER'S INTRODUCTION TO ALL FIELDS ENDED

                request.AddParameter("api_token", Login.token);
                request.AddParameter("title", title.Text);
                request.AddParameter("location", location.Text);
                request.AddParameter("description", description.Text);
                request.AddParameter("price", price.Text);
                request.AddParameter("owner_id", Login.user_id);
                request.AddParameter("min_capacity", min_capacity.Text);
                request.AddParameter("max_capacity", max_capacity.Text);
                request.AddParameter("duration", duration.Text);
                request.AddParameter("duration_type", 1);
                request.AddParameter("meet_place_address", meet_place_address.Text);
                request.AddParameter("meet_place_city", meet_place_city.Text);
                request.AddParameter("meet_place_country", idOfChosenCountry);
                request.AddParameter("category_list[0]", IdOfChosenCategory);
                request.AddParameter("lat", lat.Text);
                request.AddParameter("lng", lng.Text);

                try
                {
                    IRestResponse response = client.Execute(request);
                    var content = response.Content;
                    var myContent = JObject.Parse(content);
                    status = myContent["status"].ToString();
                }
                catch { }

                if (status == "success")
                {
                    Toast.MakeText(this, "Tour added successfully", ToastLength.Short).Show();
                    //setting status variable to null to prevent issues with adding new places in future
                    status = null;
                    StartActivity(typeof(MainActivity));
                }
                else
                {
                    Toast.MakeText(this, promptMessage, ToastLength.Long).Show();
                }
            };
        }

        private void Image_Click(object sender, EventArgs e)
        {
            var imageIntent = new Intent();
            imageIntent.SetType("image/*");
            imageIntent.SetAction(Intent.ActionGetContent);
            StartActivityForResult(
                Intent.CreateChooser(imageIntent, "Select photo"), 0);
        }

        private void Categories_spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            IdOfChosenCategory = e.Position;
        }

        private void Countries_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            idOfChosenCountry = gettingCountry.retrievingChoosenCountryId(GettingCountry.countriesList[e.Position].ToString());
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)
            {

                var imageView = FindViewById<ImageView>(Resource.Id.myImageView);
                imageView.SetImageURI(data.Data);
            }
        }
    }
</code>```

答:
I changed the namespace from RecyclerViewSample to RecyclerViewSampl. I deleted only one letter. Then I added full path RecyclerViewSample.Resource.Id.min_capacity as an example to all elements of previous namespace.
For example:
SetContentView(RecyclerViewSample.Resource.Layout.AddNewTour);
In another classes I did analogical references to this new namespace.
Such as:
StartActivity(new Intent(this, typeof(RecyclerViewSampl.AddNewTourActivity)));

Body:
I got 2 problems in OnActivityResult method while trying to upload image accoding to this. How can I solve them?
The full code of the class is:

public class AddNewTourActivity : Activity
    {
        GettingCountry gettingCountry = new GettingCountry();
        private static int idOfChosenCountry, IdOfChosenCategory;
        private static string status, promptMessage;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.AddNewTour);

            //clearing lists
            GettingCountry.listOfCountriesRoot.Clear();
            GettingCountry.countriesList.Clear();

            GettingCategories gc = new GettingCategories();
            //Getting list of countries
            gettingCountry.Fetch();

            //clearing listCategoriesRoot
            GettingCategories.categoriesList.Clear();
            //getting categories method
            gc.GetCategories();
            Spinner categories_spinner = FindViewById<Spinner>(Resource.Id.categories_spinner);
            Spinner countries = FindViewById<Spinner>(Resource.Id.countries);
            //adapter
            ArrayAdapter adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, GettingCategories.categoriesList);
            ArrayAdapter adapterCountries = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, GettingCountry.countriesList);
            categories_spinner.Adapter = adapter;
            countries.Adapter = adapterCountries;
            countries.ItemSelected += Countries_ItemSelected;
            categories_spinner.ItemSelected += Categories_spinner_ItemSelected;
            //FindViewById<EditText>(Resource.Id.owner_id).Text = Login.user_id.ToString();

            var title = FindViewById<EditText>(Resource.Id.title);
            var image = FindViewById<ImageView>(Resource.Id.myImageView);
            var location = FindViewById<EditText>(Resource.Id.location);
            var description = FindViewById<EditText>(Resource.Id.description);
            var price = FindViewById<EditText>(Resource.Id.price);
            var min_capacity = FindViewById<EditText>(Resource.Id.min_capacity);
            var max_capacity = FindViewById<EditText>(Resource.Id.max_capacity);
            var duration = FindViewById<EditText>(Resource.Id.duration);
            var meet_place_address = FindViewById<EditText>(Resource.Id.meet_place_address);
            var meet_place_city = FindViewById<EditText>(Resource.Id.meet_place_city);
            var lat = FindViewById<EditText>(Resource.Id.lat);
            var lng = FindViewById<EditText>(Resource.Id.lng);

            //uploading image
            image.Click += Image_Click;
            //uploading image ENDED

            FindViewById<Button>(Resource.Id.add_tour_button).Click += delegate
            {
                //setting prompt message empty
                promptMessage = "";
                var client = new RestClient("http://api.locopal.com");
                var request = new RestRequest("/experience", Method.POST);

                //CHECKING THE CORRECTNESS OF THE USER'S INTRODUCTION TO ALL FIELDS
                if (title.Text.Length < 3)
                {
                    promptMessage += " Title must have at least 3 symbols.\n";
                }
                if (location.Text.Length < 3)
                {
                    promptMessage += " Location must have at least 3 symbols.\n";
                }
                if (description.Text.Length < 30)
                {
                    promptMessage += " Description length must be at least 30 symbols.\n";
                }

                //checking if price, capacity, etc... are integer values
                int res;
                bool priceIsInt = false;
                priceIsInt = Int32.TryParse(price.Text, out res);

                if (priceIsInt == false)
                {
                    promptMessage += " Price must be an integer value.\n";
                }

                bool minCapacityIsInt = false;
                minCapacityIsInt = Int32.TryParse(min_capacity.Text, out res);
                if (minCapacityIsInt == false)
                {
                    promptMessage += " Minimum capacity must be an integer value.\n";
                }

                bool maxCapacityIsInt = false;
                maxCapacityIsInt = Int32.TryParse(max_capacity.Text, out res);
                if (maxCapacityIsInt == false)
                {
                    promptMessage += " Maximum capacity must be an integer value.\n";
                }

                bool durationIsInt = false;
                durationIsInt = Int32.TryParse(duration.Text, out res);
                if (durationIsInt == false)
                {
                    promptMessage += " Duration must be an integer value.\n";
                }
                //checking if price, capacity, etc... are integer values ENDED

                if (meet_place_address.Text.Length < 3)
                {
                    promptMessage += " Address of meeting place must have at least 3 symbols.\n";
                }

                if (meet_place_city.Text.Length < 3)
                {
                    promptMessage += " City of meeting place must have at least 3 symbols.\n";
                }

                //checking if lat and lng are doubles
                double resDouble;

                bool latIsDouble = false;
                latIsDouble = Double.TryParse(lat.Text, out resDouble);
                if (latIsDouble == false)
                {
                    promptMessage += " Latitude must be a fractional value.\n";
                }

                bool lngIsDouble = false;
                lngIsDouble = Double.TryParse(lng.Text, out resDouble);
                if (lngIsDouble == false)
                {
                    promptMessage += " Longitude must be a fractional value.";
                }
                //checking if lat and lng are doubles ENDED

                //CHECKING THE CORRECTNESS OF THE USER'S INTRODUCTION TO ALL FIELDS ENDED

                request.AddParameter("api_token", Login.token);
                request.AddParameter("title", title.Text);
                request.AddParameter("location", location.Text);
                request.AddParameter("description", description.Text);
                request.AddParameter("price", price.Text);
                request.AddParameter("owner_id", Login.user_id);
                request.AddParameter("min_capacity", min_capacity.Text);
                request.AddParameter("max_capacity", max_capacity.Text);
                request.AddParameter("duration", duration.Text);
                request.AddParameter("duration_type", 1);
                request.AddParameter("meet_place_address", meet_place_address.Text);
                request.AddParameter("meet_place_city", meet_place_city.Text);
                request.AddParameter("meet_place_country", idOfChosenCountry);
                request.AddParameter("category_list[0]", IdOfChosenCategory);
                request.AddParameter("lat", lat.Text);
                request.AddParameter("lng", lng.Text);

                try
                {
                    IRestResponse response = client.Execute(request);
                    var content = response.Content;
                    var myContent = JObject.Parse(content);
                    status = myContent["status"].ToString();
                }
                catch { }

                if (status == "success")
                {
                    Toast.MakeText(this, "Tour added successfully", ToastLength.Short).Show();
                    //setting status variable to null to prevent issues with adding new places in future
                    status = null;
                    StartActivity(typeof(MainActivity));
                }
                else
                {
                    Toast.MakeText(this, promptMessage, ToastLength.Long).Show();
                }
            };
        }

        private void Image_Click(object sender, EventArgs e)
        {
            var imageIntent = new Intent();
            imageIntent.SetType("image/*");
            imageIntent.SetAction(Intent.ActionGetContent);
            StartActivityForResult(
                Intent.CreateChooser(imageIntent, "Select photo"), 0);
        }

        private void Categories_spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            IdOfChosenCategory = e.Position;
        }

        private void Countries_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            idOfChosenCountry = gettingCountry.retrievingChoosenCountryId(GettingCountry.countriesList[e.Position].ToString());
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)
            {

                var imageView = FindViewById<ImageView>(Resource.Id.myImageView);
                imageView.SetImageURI(data.Data);
            }
        }
    }


问:
Angular: Revert object back to original if update fails
I have a client object that gets updated through an inline form and if my service cannot successfully update the client, I want it to revert to what it was before the before the client side changes took place.  Here's what I have so far:

```<code>  updateForm() {
    let client_id = this.client.id
    let curr_client = this.client
    console.log("updating", curr_client)

    this.clientService.update(this.client, "client", this.token).subscribe(
      data => {
        // sets this client to new client returned from service
        this.client = data
        this.clientService.handleResponse("Successfully updated the client!")
        this.clientService.setClient(this.client)
      },
      err => {
        console.log(curr_client)
        this.clientService.handleResponse("Ut oh.. couldn't update the client!")
        // attempt at reverting back but curr_client changes with this.client
        this.client = curr_client
      },
      () => this.editMode = false
    )
  }
</code>```

What can I change in the failure block to revert the client?

答:
This is what I did:

```<code>private currentProduct: IProduct;
private originalProduct: IProduct;

get product(): IProduct {
    return this.currentProduct;
}
set product(value: IProduct) {
    this.currentProduct = value;
    // Clone the object to retain a copy
    this.originalProduct = Object.assign({}, value);
}
</code>```

I clone the object to make a copy as soon as the product is set from the Http call. Then I can use the original if I need to revert back.

Body:
I have a client object that gets updated through an inline form and if my service cannot successfully update the client, I want it to revert to what it was before the before the client side changes took place.  Here's what I have so far:

  updateForm() {
    let client_id = this.client.id
    let curr_client = this.client
    console.log("updating", curr_client)

    this.clientService.update(this.client, "client", this.token).subscribe(
      data => {
        // sets this client to new client returned from service
        this.client = data
        this.clientService.handleResponse("Successfully updated the client!")
        this.clientService.setClient(this.client)
      },
      err => {
        console.log(curr_client)
        this.clientService.handleResponse("Ut oh.. couldn't update the client!")
        // attempt at reverting back but curr_client changes with this.client
        this.client = curr_client
      },
      () => this.editMode = false
    )
  }

What can I change in the failure block to revert the client?

Body:
This is what I did:

private currentProduct: IProduct;
private originalProduct: IProduct;

get product(): IProduct {
    return this.currentProduct;
}
set product(value: IProduct) {
    this.currentProduct = value;
    // Clone the object to retain a copy
    this.originalProduct = Object.assign({}, value);
}

I clone the object to make a copy as soon as the product is set from the Http call. Then I can use the original if I need to revert back.


问:
Use sed/awk to remove the last portion of a delimited-text column
I have a file with rows of values. The first column, a PacBio read ID, is a forward-slash-delimited value. I would like to modify the column by removing the final slash and values beyond it. Ideally the result would be stream-able (sed/awk, etc.) and would not rely on the number of forward slashes (i.e. the solution should work whether there is a single forward slash, or three, as below.) </p>

```<code># example row
m54151_170617_100137/4194626/10117_11723/0_1606 1257    1606

# desired row
m54151_170617_100137/4194626/10117_11723    1257    1606
</code>```

答:
If you potentially have spaces in your fields, use the / to split.

With awk you can split on /, rejoin the fields with / then print the last field:

```<code>$ awk -F'/' '{s=""
             for (i=1;i<NF;i++)
                s=s ? s FS $i : $i
              print s $NF}' file
</code>```

The same is a bit easier in Ruby:

```<code>$ ruby -F'/' -lane 'puts $F[0...-1].join("/")<<$F[-1]' file
</code>```

Body:
I have a file with rows of values. The first column, a PacBio read ID, is a forward-slash-delimited value. I would like to modify the column by removing the final slash and values beyond it. Ideally the result would be stream-able (sed/awk, etc.) and would not rely on the number of forward slashes (i.e. the solution should work whether there is a single forward slash, or three, as below.)

# example row
m54151_170617_100137/4194626/10117_11723/0_1606 1257    1606

# desired row
m54151_170617_100137/4194626/10117_11723    1257    1606

Body:
If you potentially have spaces in your fields, use the / to split.

With awk you can split on /, rejoin the fields with / then print the last field:

$ awk -F'/' '{s=""
             for (i=1;i<NF;i++)
                s=s ? s FS $i : $i
              print s $NF}' file

The same is a bit easier in Ruby:

$ ruby -F'/' -lane 'puts $F[0...-1].join("/")<<$F[-1]' file


问:
How to write http url based web service in netbeans?
How can I write a web service where I can query in the URL with some parameters and display the result in the JSON format.

For example, There is a table AppInfo in my database which has two columns named AppID and Status

Now, what I want is to write a web service like that

```<code>http://10.11.201.84?q=Select+*+from+AppInfo+where+AppID='21212'&format=json
</code>```

So, from a user, I will take the application id and get the status using this web service. I might have to use get method for using the HTTP URL request.

Which web service I have to use in this case and how?

答:
I implemented the necessary http url based web service by this, I have used restful web service implementation

1) Create a Java Web Project and create a servlet

2) Connect with my Oracle database (using ojdbc 6.0)

3) Taking the query as a parameter in the url (as requirement) and then process the query (I used preparedStatement)

4) Getting the result of the query and Save it to json

5) Display the successive Json data in the browser and then parse the data json data to send back the response to user.

Thanks to all who guided me !!

Body:
How can I write a web service where I can query in the URL with some parameters and display the result in the JSON format.

For example, There is a table AppInfo in my database which has two columns named AppID and Status

Now, what I want is to write a web service like that

http://10.11.201.84?q=Select+*+from+AppInfo+where+AppID='21212'&format=json

So, from a user, I will take the application id and get the status using this web service. I might have to use get method for using the HTTP URL request.

Which web service I have to use in this case and how?


问:
python load OpenDap to NetcdfFile
I am opening netcdf data from an opendap server (a subset of the data) using an URL. When I open it the data is (as far as I can see) not actually loaded until the variable is requested. I would like to save the data to a file on disk, how would I do this?

I currently have:

```<code>import numpy as np
import netCDF4 as NC

url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
set = NC.Dataset(url) # I think data is not yet loaded here, only the "layout"
varData = set.variables['varname'][:,:] # I think data is loaded here

# now i want to save this data to a file (for example test.nc), set.close() obviously wont work
</code>```

Hope someone can help, thanks!

答:
If you can use xarray, this should work as:

```<code>import xarray as xr

url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
ds = xr.open_dataset(url, engine='netcdf4')  # or engine='pydap'
ds.to_netcdf('test.nc')
</code>```

The xarray documentation has another example of how you could do this.

Title: python load OpenDap to NetcdfFile

Body:
I am opening netcdf data from an opendap server (a subset of the data) using an URL. When I open it the data is (as far as I can see) not actually loaded until the variable is requested. I would like to save the data to a file on disk, how would I do this?

I currently have:

import numpy as np
import netCDF4 as NC

url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
set = NC.Dataset(url) # I think data is not yet loaded here, only the "layout"
varData = set.variables['varname'][:,:] # I think data is loaded here

# now i want to save this data to a file (for example test.nc), set.close() obviously wont work

Hope someone can help, thanks!

Body:
If you can use xarray, this should work as:

import xarray as xr

url = u'http://etc/etc/hourly?varname[0:1:10][0:1:30]'
ds = xr.open_dataset(url, engine='netcdf4')  # or engine='pydap'
ds.to_netcdf('test.nc')

The xarray documentation has another example of how you could do this.


问:
getJson() inside another function returns "undefined"
I'm handling with a "Switch" diferent actions. In this case Im trying to add to the variable "data" just one product into a Json object. The function giveMeProd.. should return the value.

```<code>case "pvc":
        if (option == 1) { //1 means I want a single prod.
            data = giveMeTheProductPlease(sessionStorage.baseId);
            console.log("result: " + data); ...
</code>```

The giveMeTheProduct function:

```<code>    function giveMeTheProductPlease(id) {
    var aux = null;
    $.getJSON("./data/results.json", function (data) {

        var l = Object.keys(data).length;
        for (var i = 0; i < l; i++) {
            if (data[i].id == id) {
                console.log(data[i]);
                aux = data[i];

            }
        }
    })
    return aux;
}
</code>```

I have been reading about the matter, it seems Im trying to run a asyncronous function and return it into an syncronous function. It could be solved with a "callback", but I need to recieve the "id" parameter and I dont know how to do it.

Any idea?

答:
Your function giveMeTheProductPlease() is dealing with asynchronous code. It actually returns null before the request made with $.getJSON has a chance to finish.

Here what you could do:

```<code> var findProduct = function(id, data) {
     var aux = null;
     for (var i = 0; i < data.length; i++) {
         if (data[i].id === id) {
             aux = data[i];
        }
    }

     return aux;
 }

 $.getJSON("./data/results.json", function (result) {
     switch(val) {
     case "pvc":
         if (option == 1) { //1 means I want a single prod.
             data = findProduct(sessionStorage.baseId, result);
         }
 })
</code>```

Body:
I'm handling with a "Switch" diferent actions. In this case Im trying to add to the variable "data" just one product into a Json object. The function giveMeProd.. should return the value.

case "pvc":
        if (option == 1) { //1 means I want a single prod.
            data = giveMeTheProductPlease(sessionStorage.baseId);
            console.log("result: " + data); ...

The giveMeTheProduct function:

    function giveMeTheProductPlease(id) {
    var aux = null;
    $.getJSON("./data/results.json", function (data) {

        var l = Object.keys(data).length;
        for (var i = 0; i < l; i++) {
            if (data[i].id == id) {
                console.log(data[i]);
                aux = data[i];

            }
        }
    })
    return aux;
}

I have been reading about the matter, it seems Im trying to run a asyncronous function and return it into an syncronous function. It could be solved with a "callback", but I need to recieve the "id" parameter and I dont know how to do it.

Any idea?

Body:
Your function giveMeTheProductPlease() is dealing with asynchronous code. It actually returns null before the request made with $.getJSON has a chance to finish.

Here what you could do:

 var findProduct = function(id, data) {
     var aux = null;
     for (var i = 0; i < data.length; i++) {
         if (data[i].id === id) {
             aux = data[i];
        }
    }

     return aux;
 }

 $.getJSON("./data/results.json", function (result) {
     switch(val) {
     case "pvc":
         if (option == 1) { //1 means I want a single prod.
             data = findProduct(sessionStorage.baseId, result);
         }
 })


问:
Funneling Proxy Server through AWS Workspaces
I use RETSConnector to diagnose RETS server feeds.  Some are IP restricted.  I am trying to access these feeds through an AWS Windows 7 Workspace.  You can connect with a proxy server, but it doesn't seem to affect the IP the space is reporting.  So my question is, is there anyway I can get AWS Workspace/Windows 7 to reports the proxy server IP internally, thus allowing me to utilize the IP that is already stored in various vendor accounts.</p>

答: This is really a networking issue, you would need to setup a VPN in one of the whitelisted networks.</p>


问:
How do I get the X window class given a window ID with rust-xcb?
I'm trying to use rust-xcb to get a window's class given a window ID.

fn get_class(conn: &xcb::Connection, id: &i32) {
    let window: xcb::xproto::Window = *id as u32;
    let class_prop: xcb::xproto::Atom = 67; // XCB_ATOM_WM_CLASS from xproto.h
    let cookie = xcb::xproto::get_property(&conn, false, window, class_prop, 0, 0, 2);
    match cookie.get_reply() {
        Ok(reply) => {
            let x: &[std::os::raw::c_void] = reply.value();
            println!("reply is {:?}", x[0]);
        }
        Err(err) => println!("err {:?}", err),
    }
}
```

<p>The documentation is kind of sparse and hasn't been incredibly helpful, though I did find this bit about the <code>GetPropertyReply</code> and of the <code>xcb_get_property_reply_t</code> it wraps.</p>

<p>I looked at this answer in JavaScript but I don't know what the <code>ctypes</code> equivalent in Rust is. I tried just casting the <code>&[c_void]</code> as a <code>&str</code> or <code>String</code>:</p>

<pre class="lang-rs prettyprint-override"><code> ...
 Ok(reply) => {
     let len = reply.value_len() as usize;
     let buf = reply.value() as &str;
     println!("{}", buf.slice_unchecked(0, len)); // this seems redundant
 }
 ...
</code>```

but it returns

error: non-scalar cast: `&[_]` as `&str`
```

<p>I tried casting the <code>&[c_void]</code> as a <code>&[u8]</code> and then collecting the <code>Vec</code> into a <code>String</code>, which sort of works:</p>

<pre class="lang-rs prettyprint-override"><code>  ...
  Ok(reply) => {
      let value : &[u8] = reply.value();
      let buf : String = value.into_iter().map(|i| *i as char).collect();
      println!("\t{:?}", buf);
  }
  ...
</code>```

but I'm now getting weird results. for example , when I use xprop on Chrome I see "google-chrome" but for me it is only showing "google-c", and "roxterm" is showing up as "roxterm\u{0}". I'm guessing "\u{0}" is something Unicode related but I'm not sure, and I don't know why stuff is being concatenated either. Maybe I have to check the reply again?

答:
Here's my updated function:

```<code>fn get_class(conn: &Connection, id: &i32) -> String {
    let window: xproto::Window = *id as u32;
    let long_length: u32 = 8;
    let mut long_offset: u32 = 0;
    let mut buf = Vec::new();
    loop {
        let cookie = xproto::get_property(
            &conn,
            false,
            window,
            xproto::ATOM_WM_CLASS,
            xproto::ATOM_STRING,
            long_offset,
            long_length,
        );
        match cookie.get_reply() {
            Ok(reply) => {
                let value: &[u8] = reply.value();
                buf.extend_from_slice(value);
                match reply.bytes_after() {
                    0 => break,
                    _ => {
                        let len = reply.value_len();
                        long_offset += len / 4;
                    }
                }
            }
            Err(err) => {
                println!("{:?}", err);
                break;
            }
        }
    }
    let result = String::from_utf8(buf).unwrap();
    let results: Vec<&str> = result.split('\0').collect();
    results[0].to_string()
}
</code>```

There were three main parts to this question:

I put xproto::get_property() in a loop so I could check reply.bytes_after() and accordingly adjust long_offset. I think with an appropriate long_length there will usually only be one read, but just being safe.

As @peter-hall said, converting &[u8] -> String should be done using String::from_utf8, which needs a Vec; so I let mut buf = Vec::new() and buf.extend_from_slice over the loop before creating the result string with String::from_utf8(buf).unwrap()

According to this random page WM_CLASS is actually two consecutive null-terminated strings, so I split the result by \0 and grab the first value.

I might've just been looking in the wrong place, but xcb has absolutely terrible documentation..

Body:
I'm trying to use rust-xcb to get a window's class given a window ID.

fn get_class(conn: &xcb::Connection, id: &i32) {
    let window: xcb::xproto::Window = *id as u32;
    let class_prop: xcb::xproto::Atom = 67; // XCB_ATOM_WM_CLASS from xproto.h
    let cookie = xcb::xproto::get_property(&conn, false, window, class_prop, 0, 0, 2);
    match cookie.get_reply() {
        Ok(reply) => {
            let x: &[std::os::raw::c_void] = reply.value();
            println!("reply is {:?}", x[0]);
        }
        Err(err) => println!("err {:?}", err),
    }
}

The documentation is kind of sparse and hasn't been incredibly helpful, though I did find this bit about the GetPropertyReply and of the xcb_get_property_reply_t it wraps.

I looked at this answer in JavaScript but I don't know what the ctypes equivalent in Rust is. I tried just casting the &[c_void] as a &str or String:

 ...
 Ok(reply) => {
     let len = reply.value_len() as usize;
     let buf = reply.value() as &str;
     println!("{}", buf.slice_unchecked(0, len)); // this seems redundant
 }
 ...

but it returns

error: non-scalar cast: `&[_]` as `&str`

I tried casting the &[c_void] as a &[u8] and then collecting the Vec into a String, which sort of works:

  ...
  Ok(reply) => {
      let value : &[u8] = reply.value();
      let buf : String = value.into_iter().map(|i| *i as char).collect();
      println!("\t{:?}", buf);
  }
  ...

but I'm now getting weird results. for example , when I use xprop on Chrome I see "google-chrome" but for me it is only showing "google-c", and "roxterm" is showing up as "roxterm\u{0}". I'm guessing "\u{0}" is something Unicode related but I'm not sure, and I don't know why stuff is being concatenated either. Maybe I have to check the reply again?

Body:
Here's my updated function:

fn get_class(conn: &Connection, id: &i32) -> String {
    let window: xproto::Window = *id as u32;
    let long_length: u32 = 8;
    let mut long_offset: u32 = 0;
    let mut buf = Vec::new();
    loop {
        let cookie = xproto::get_property(
            &conn,
            false,
            window,
            xproto::ATOM_WM_CLASS,
            xproto::ATOM_STRING,
            long_offset,
            long_length,
        );
        match cookie.get_reply() {
            Ok(reply) => {
                let value: &[u8] = reply.value();
                buf.extend_from_slice(value);
                match reply.bytes_after() {
                    0 => break,
                    _ => {
                        let len = reply.value_len();
                        long_offset += len / 4;
                    }
                }
            }
            Err(err) => {
                println!("{:?}", err);
                break;
            }
        }
    }
    let result = String::from_utf8(buf).unwrap();
    let results: Vec<&str> = result.split('\0').collect();
    results[0].to_string()
}

There were three main parts to this question:

I put xproto::get_property() in a loop so I could check reply.bytes_after() and accordingly adjust long_offset. I think with an appropriate long_length there will usually only be one read, but just being safe.

As @peter-hall said, converting &[u8] -> String should be done using String::from_utf8, which needs a Vec; so I let mut buf = Vec::new() and buf.extend_from_slice over the loop before creating the result string with String::from_utf8(buf).unwrap()

According to this random page WM_CLASS is actually two consecutive null-terminated strings, so I split the result by \0 and grab the first value.

I might've just been looking in the wrong place, but xcb has absolutely terrible documentation..


问:
Odoo - Update record when click on button in email template
I am using Odoo 10-e. I create a simple email template which i am sending on a particular event from my class. What i want to know that is this possible in Odoo to create a email template and put button into it. When user click on that button my particular class field will be updated.</p>

答:
You could write a http controller which will update a database record. Just let the "email button" call a specific url.

But keep in mind that giving non odoo users (and that's what you're doing here) such access rights could end in a security disaster.


问:
Launching Cuda Call from struct
Given a simple struct to wrap the cuda code one can write something like

```<code>func<float> s;
s.val = 3.f;
start_correct<<<1, 2>>>(s);
</code>```

However, I would like to put the block, grid, shared memory computation into the struct and call the kernel like

```<code>func<float> s;
s.val = 3.f;
s.launch();
</code>```

While the first is working, the second gives me an illegal memory access error.

A minimal example to reproduce my problem is

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

template<typename T>
struct func;

template<typename T>
__global__ void start(const func<T>& s){
  printf("host access val %f \n",s.val);
  s();
}

template<typename T>
struct func
{
  T val;

  __device__ void operator()() const{
    printf("device access val %f [%d]\n",val,threadIdx.x);
  }

  enum{ C_N = 2 };

  void launch()
  {
    start<<<1, C_N>>>(*this);
  }

};

template<typename T>
__global__ void start_correct(const func<T> s){
  printf("host access val %f \n", s.val);
  s();
}

int main(int argc, char const *argv[])
{
  cudaError_t err;

  func<float> s;
  s.val = 3.f;

  // launch cuda kernel <-- WORKS
  start_correct<<<1, 2>>>(s);
  cudaDeviceSynchronize();
  if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));

  // launch cuda kernel <-- DOES NOT WORK
  s.launch();
  cudaDeviceSynchronize();
  err = cudaGetLastError();
  if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));

  return 0;
}
</code>```

The output is

```<code>host access val 3.000000
host access val 3.000000
device access val 3.000000 [0]
device access val 3.000000 [1]
host access val 0.000000
host access val 0.000000
device access val 0.000000 [0]
device access val 0.000000 [1]
Error: an illegal memory access was encountered
</code>```

Shouldn't both ways be equivalent? Are there any alternatives, which also do the shm, grid calculations inside the struct?

答:
Unless you are using managed memory (which you aren't), it is not legal to pass kernel parameters by reference:

```<code>__global__ void start(const func<T>& s){
                                   ^
</code>```

When I remove that ampersand, your code runs without any runtime error for me, and gives sensible output:

```<code>$ cuda-memcheck ./t355
========= CUDA-MEMCHECK
host access val 3.000000
host access val 3.000000
device access val 3.000000 [0]
device access val 3.000000 [1]
host access val 3.000000
host access val 3.000000
device access val 3.000000 [0]
device access val 3.000000 [1]
========= ERROR SUMMARY: 0 errors
$
</code>```

Note that this doesn't really make sense:

```<code>  cudaDeviceSynchronize();
  if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));
</code>```

and throws a compiler warning for me.

Perhaps you meant:

```<code>  err = cudaDeviceSynchronize();
  if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));
</code>```

Title: Launching Cuda Call from struct

Body:
Given a simple struct to wrap the cuda code one can write something like

func<float> s;
s.val = 3.f;
start_correct<<<1, 2>>>(s);

However, I would like to put the block, grid, shared memory computation into the struct and call the kernel like

func<float> s;
s.val = 3.f;
s.launch();

While the first is working, the second gives me an illegal memory access error.

A minimal example to reproduce my problem is

#include <stdio.h>

template<typename T>
struct func;

template<typename T>
__global__ void start(const func<T>& s){
  printf("host access val %f \n",s.val);
  s();
}

template<typename T>
struct func
{
  T val;

  __device__ void operator()() const{
    printf("device access val %f [%d]\n",val,threadIdx.x);
  }

  enum{ C_N = 2 };

  void launch()
  {
    start<<<1, C_N>>>(*this);
  }

};

template<typename T>
__global__ void start_correct(const func<T> s){
  printf("host access val %f \n", s.val);
  s();
}

int main(int argc, char const *argv[])
{
  cudaError_t err;

  func<float> s;
  s.val = 3.f;

  // launch cuda kernel <-- WORKS
  start_correct<<<1, 2>>>(s);
  cudaDeviceSynchronize();
  if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));

  // launch cuda kernel <-- DOES NOT WORK
  s.launch();
  cudaDeviceSynchronize();
  err = cudaGetLastError();
  if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));

  return 0;
}

The output is

host access val 3.000000
host access val 3.000000
device access val 3.000000 [0]
device access val 3.000000 [1]
host access val 0.000000
host access val 0.000000
device access val 0.000000 [0]
device access val 0.000000 [1]
Error: an illegal memory access was encountered

Shouldn't both ways be equivalent? Are there any alternatives, which also do the shm, grid calculations inside the struct?

Body:
Unless you are using managed memory (which you aren't), it is not legal to pass kernel parameters by reference:

__global__ void start(const func<T>& s){
                                   ^

When I remove that ampersand, your code runs without any runtime error for me, and gives sensible output:

$ cuda-memcheck ./t355
========= CUDA-MEMCHECK
host access val 3.000000
host access val 3.000000
device access val 3.000000 [0]
device access val 3.000000 [1]
host access val 3.000000
host access val 3.000000
device access val 3.000000 [0]
device access val 3.000000 [1]
========= ERROR SUMMARY: 0 errors
$

Note that this doesn't really make sense:

  cudaDeviceSynchronize();
  if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));

and throws a compiler warning for me.

Perhaps you meant:

  err = cudaDeviceSynchronize();
  if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err));


问:
Insert with on duplicate key update ignores index
So I've got a table product_supplier that I need to add data to from import_tbl. Product_supplier has three columns product_id, supplier_id and price. Import_tbl has the same columns plus some extra. What's most important and what I can't get working is that when a specific combination of product_id and supplier_id exists, only the price should be updated. If that combination does not exist a new row needs to be added. I tried this query

```<code>INSERT INTO product_supplier (product_id, supplier_id, price)
SELECT i.product_id, i.supplier_id, i.price
FROM import_tbl i
ON DUPLICATE KEY UPDATE
    price = i.price
</code>```

This one works if I add a row with a new product_id, but it totally ignores the supplier_id. So it won't add new rows if I a row uses the same product_id but a different supplier_id.

I think this has something to do with indexes, and I tried unique indexes for both product_id, and supplier_id and a multiple-column index of both product_id and supplier_id. But when I put EXPLAIN in front of the query it never recognises any indexes. Please some help, thanks!

Table structure of product_supplier

```<code>+---------------------+---------+------+-----+---------+----------------+
|        Field        |  Type   | Null | Key | Default |     Extra      |
+---------------------+---------+------+-----+---------+----------------+
| product_supplier_id | int(11) | NO   | PRI | NULL    | auto_increment |
| product_id          | int(11) | NO   | UNI | 0       |                |
| supplier_id         | int(11) | NO   | MUL | 0       |                |
| price               | int(11) | NO   |     | 0       |                |
+---------------------+---------+------+-----+---------+----------------+
</code>```

答:
It looks like you have a key problem.

The "ON DUPLICATE KEY UPDATE" pays attention to the table's primary key only, in this case a combo primary of product_supplier_id plus product_id. The  product_supplier_id field isn't being included in your INSERT, and is then being auto-generated.

If you really want to make this commit as a single action (instead of check for existing then choose to either insert or update) then you'll need to move the primary key to be based on a combo of product_id and supplier_id and drop the auto-increment field.

If you need to be able to have more than one price per product/supplier then you can't use ON DUPLICATE KEY UPDATE and will need to run multiple queries.

Body:
So I've got a table product_supplier that I need to add data to from import_tbl. Product_supplier has three columns product_id, supplier_id and price. Import_tbl has the same columns plus some extra. What's most important and what I can't get working is that when a specific combination of product_id and supplier_id exists, only the price should be updated. If that combination does not exist a new row needs to be added. I tried this query

INSERT INTO product_supplier (product_id, supplier_id, price)
SELECT i.product_id, i.supplier_id, i.price
FROM import_tbl i
ON DUPLICATE KEY UPDATE
    price = i.price

This one works if I add a row with a new product_id, but it totally ignores the supplier_id. So it won't add new rows if I a row uses the same product_id but a different supplier_id.

I think this has something to do with indexes, and I tried unique indexes for both product_id, and supplier_id and a multiple-column index of both product_id and supplier_id. But when I put EXPLAIN in front of the query it never recognises any indexes. Please some help, thanks!

Table structure of product_supplier

+---------------------+---------+------+-----+---------+----------------+
|        Field        |  Type   | Null | Key | Default |     Extra      |
+---------------------+---------+------+-----+---------+----------------+
| product_supplier_id | int(11) | NO   | PRI | NULL    | auto_increment |
| product_id          | int(11) | NO   | UNI | 0       |                |
| supplier_id         | int(11) | NO   | MUL | 0       |                |
| price               | int(11) | NO   |     | 0       |                |
+---------------------+---------+------+-----+---------+----------------+


问:
Escape special characters # & ' " in a string in Coldfusion
Following thie topic AngularJS - Special Characters in JSON and Coldfusion Request I have concluded that the problem didn't come from ANGULARJS or my JSON syntax. It's certainly a problem with Coldfusion.

For reminder, I'm trying to use a JSON string for doing an INSERT in a database with ColdFusion. I'm using a function defined in a component for doing that.

My function has the string as argument.

Here an example of the string used:

```<code>jsStruct={"LASTNAME":"Nämé","FIRSTN%a£öME":"TestFirstName","PHONENUMBER":48484488,"EMAIL":"tes.test@test.test","COMPANY":"Test & Comp"}
</code>```

My string is correct and the structure of the JSON is ok.

In my Coldfusion component "component.cfc":

```<code>    <cffunction name="myfunction" access="remote" returnformat="JSON" output="no">
        <cfargument name="jsStruct" type="string" required="true">
        <cfset var cfStruct=DeserializeJSON(jsStruct)>

        ..................

    </cffunction>
</code>```

I obtain this error on the server when I use the string because in my string there is special characters. For instance "COMPANY":"Test & Comp":

```<code>JSON parsing failure: Unexpected end of JSON string

The error occurred in ../contacts.cfc: line 267

265 :       <cfargument name="jsStruct" type="string" required="true">
266 :
267 :       <cfset var cfStruct=DeserializeJSON(jsStruct)>
</code>```

Could you please help me to solve this problem and prevent (escape) special characters used by ColdFusion and Oracle as &, #, ', " and others?

答:
You say, in error,

My function has the string as argument.
Here an example of the string used:

```<code>*jsStruct={"LASTNAME":"Nämé","FIRSTN%a£öME":"TestFirstName","PHONENUMBER":48484488,"EMAIL":"tes.test@test.test","COMPANY":"Test & Comp"}*
</code>```

You yourself call that a struct, which is correct. It is not a string.

Use something like:

```<code>jsonString='{"LASTNAME":"Nämé","FIRSTN%a£öME":"TestFirstName","PHONENUMBER":48484488,"EMAIL":"tes.test@test.test","COMPANY":"Test & Comp"}';
</code>```

Body:
Following thie topic AngularJS - Special Characters in JSON and Coldfusion Request I have concluded that the problem didn't come from ANGULARJS or my JSON syntax. It's certainly a problem with Coldfusion.

For reminder, I'm trying to use a JSON string for doing an INSERT in a database with ColdFusion. I'm using a function defined in a component for doing that.

My function has the string as argument.

Here an example of the string used:

jsStruct={"LASTNAME":"Nämé","FIRSTN%a£öME":"TestFirstName","PHONENUMBER":48484488,"EMAIL":"tes.test@test.test","COMPANY":"Test & Comp"}

My string is correct and the structure of the JSON is ok.

In my Coldfusion component "component.cfc":

    <cffunction name="myfunction" access="remote" returnformat="JSON" output="no">
        <cfargument name="jsStruct" type="string" required="true">
        <cfset var cfStruct=DeserializeJSON(jsStruct)>

        ..................

    </cffunction>

I obtain this error on the server when I use the string because in my string there is special characters. For instance "COMPANY":"Test & Comp":

JSON parsing failure: Unexpected end of JSON string

The error occurred in ../contacts.cfc: line 267

265 :       <cfargument name="jsStruct" type="string" required="true">
266 :
267 :       <cfset var cfStruct=DeserializeJSON(jsStruct)>

Could you please help me to solve this problem and prevent (escape) special characters used by ColdFusion and Oracle as &, #, ', " and others?

Body:
You say, in error,

My function has the string as argument.
Here an example of the string used:

*jsStruct={"LASTNAME":"Nämé","FIRSTN%a£öME":"TestFirstName","PHONENUMBER":48484488,"EMAIL":"tes.test@test.test","COMPANY":"Test & Comp"}*

You yourself call that a struct, which is correct. It is not a string.

Use something like:

jsonString='{"LASTNAME":"Nämé","FIRSTN%a£öME":"TestFirstName","PHONENUMBER":48484488,"EMAIL":"tes.test@test.test","COMPANY":"Test & Comp"}';


问:
How to centralize and resize digits using opencv?
I want to OCR some scanned forms (filled by hand). It is the first time I do something serious using computer vision. So far I'm able to locate the squares containing digits for a date field:

Looking at the example handwritten digit dataset that comes with OpenCV, I see digits are centralized and resized to (20, 20):

Since this may be a fairly common problem, I'm wondering if the algorithm is already implemented in OpenCV (or numpy, scipy, etc) so I don't have to reinvent the wheel.

The question is: is there a built-in pipeline in Python in order to normalize the samples?

答:
I ended up using this function:

```<code>def norm_digit(im):
    h, w = im.shape
    if h > w:
        top, left = round(h * 0.1), round((1.2 * h - w) / 2)
    else:
        top, left = round(w * 0.1), round((1.2 * w - h) / 2)

    return cv2.resize(
        cv2.copyMakeBorder(im, top, top, left, left, cv2.BORDER_CONSTANT),
        (20, 20)
    )
</code>```

Input is a image already cropped to the bounding box of the digit contour. There are some corner cases it doesn't cover but looks like this may be good enough.

Body:
I ended up using this function:

def norm_digit(im):
    h, w = im.shape
    if h > w:
        top, left = round(h * 0.1), round((1.2 * h - w) / 2)
    else:
        top, left = round(w * 0.1), round((1.2 * w - h) / 2)

    return cv2.resize(
        cv2.copyMakeBorder(im, top, top, left, left, cv2.BORDER_CONSTANT),
        (20, 20)
    )

Input is a image already cropped to the bounding box of the digit contour. There are some corner cases it doesn't cover but looks like this may be good enough.


问:
Segmentation fault with dynamically allocated arrays as members of structure in c++?
I am writing a program using an array of structures to store a name, id number, and an array of test scores for a certain amount of students. Both the array of structures and the array of test scores member need to be dynamically allocated. I've gotten down to the function that allows the user to input test scores for each student, however I am having problems with the cin in the last function (getScores function). When using Linux I get a segmentation fault, so I'm assuming it has something to do with the dynamically allocated tests array that is a member of the structure, I just can't see it. I'm wondering how I can go about debugging it and an explanation of why this is actually occurring so I can avoid it in the future. </p>

```<code>//Preprocessor Directives
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

//Structure declaration
struct Students
{
    string name; //Student name
    int idNum; //Student ID number
    double *tests; //Pointer to an array of test scores
};

//Function prototypes
Students *getStudents(int &);
double *getTests(int &);
void getInfo(string &, int &, int);
void getScores(double &, string, int);

//Main program section
int main ()
{
    int numStudents = 0;
    int numTests = 0;
    Students *studentFiles = NULL;

    //Call the getStudents function
    studentFiles = getStudents(numStudents);

    //Call the getTests function
    studentFiles->tests = getTests(numTests);

    for(int i = 0; i < numStudents; i++)
    {
        //Call the getInfo function
        getInfo(studentFiles[i].name, studentFiles[i].idNum, i+1);
    }

    for(int i = 0; i < numStudents; i++)
    {
        for(int j = 0; j < numTests; j++)
        {
            getScores(studentFiles[i].tests[j], studentFiles[i].name, j);
        }
    }
    delete [] studentFiles;
    delete [] studentFiels->tests;
    return 0;
}

Students *getStudents(int &numStudents)
{
    Students *studentFiles = NULL;

    //Prompt the user for the number of students
    cout<<"Enter the number of students: ";
    cin>>numStudents;
    //Dynamically allocate an array of structs, one for each student
    studentFiles = new Students[numStudents];

    return studentFiles;
}

double *getTests(int &numTests)
{
    double *tests = NULL;

    //Prompt the user for the number of tests
    cout<<"Enter the number of tests: ";
    cin>>numTests;
    cin.ignore();
    //Dynamicall allocate an array of integers, one for each test
    tests = new double[numTests];

    return tests;
}

void getInfo(string &name, int &idNum, int index)
{
    //Prompt for each student's name and id number
    cout<<"Enter the name of student #"<<index<<": ";
    getline(cin, name);
    cout<<"Enter the id number of student #"<<index<<": ";
    cin>>idNum;
    cin.ignore();
}

void getScores(double &test, string name, int numTest)
{
    cout<<name<<endl;
    cout<<numTest<<endl;
    //Prompt for each test score for each student
    cout<<"Enter "<<name<<"'s score for test #"<<numTest+1<<": ";
    cin>>test;
}
</code>```

答:
One error is that you access a member of deleted object studentFiles. Reverse the lines to fix that:

```<code>delete [] studentFiles->tests;
delete [] studentFiles;
</code>```

Ideally, use std::vector<> instead of dynamically allocating and releasing memory manually.

Also note, that the code only initializes Student::tests of the first member of the array, the rest of Student objects have this member uninitialized. The result of expression studentFiles[i].tests[j] is undefined and is likely to cause a crash.

You need to initialize Student::tests member of each Student. And when done, deallocate Student::tests of each Student.

Body:
I am writing a program using an array of structures to store a name, id number, and an array of test scores for a certain amount of students. Both the array of structures and the array of test scores member need to be dynamically allocated. I've gotten down to the function that allows the user to input test scores for each student, however I am having problems with the cin in the last function (getScores function). When using Linux I get a segmentation fault, so I'm assuming it has something to do with the dynamically allocated tests array that is a member of the structure, I just can't see it. I'm wondering how I can go about debugging it and an explanation of why this is actually occurring so I can avoid it in the future.

//Preprocessor Directives
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

//Structure declaration
struct Students
{
    string name; //Student name
    int idNum; //Student ID number
    double *tests; //Pointer to an array of test scores
};

//Function prototypes
Students *getStudents(int &);
double *getTests(int &);
void getInfo(string &, int &, int);
void getScores(double &, string, int);

//Main program section
int main ()
{
    int numStudents = 0;
    int numTests = 0;
    Students *studentFiles = NULL;

    //Call the getStudents function
    studentFiles = getStudents(numStudents);

    //Call the getTests function
    studentFiles->tests = getTests(numTests);

    for(int i = 0; i < numStudents; i++)
    {
        //Call the getInfo function
        getInfo(studentFiles[i].name, studentFiles[i].idNum, i+1);
    }

    for(int i = 0; i < numStudents; i++)
    {
        for(int j = 0; j < numTests; j++)
        {
            getScores(studentFiles[i].tests[j], studentFiles[i].name, j);
        }
    }
    delete [] studentFiles;
    delete [] studentFiels->tests;
    return 0;
}

Students *getStudents(int &numStudents)
{
    Students *studentFiles = NULL;

    //Prompt the user for the number of students
    cout<<"Enter the number of students: ";
    cin>>numStudents;
    //Dynamically allocate an array of structs, one for each student
    studentFiles = new Students[numStudents];

    return studentFiles;
}

double *getTests(int &numTests)
{
    double *tests = NULL;

    //Prompt the user for the number of tests
    cout<<"Enter the number of tests: ";
    cin>>numTests;
    cin.ignore();
    //Dynamicall allocate an array of integers, one for each test
    tests = new double[numTests];

    return tests;
}

void getInfo(string &name, int &idNum, int index)
{
    //Prompt for each student's name and id number
    cout<<"Enter the name of student #"<<index<<": ";
    getline(cin, name);
    cout<<"Enter the id number of student #"<<index<<": ";
    cin>>idNum;
    cin.ignore();
}

void getScores(double &test, string name, int numTest)
{
    cout<<name<<endl;
    cout<<numTest<<endl;
    //Prompt for each test score for each student
    cout<<"Enter "<<name<<"'s score for test #"<<numTest+1<<": ";
    cin>>test;
}

Body:
One error is that you access a member of deleted object studentFiles. Reverse the lines to fix that:

delete [] studentFiles->tests;
delete [] studentFiles;

Ideally, use std::vector<> instead of dynamically allocating and releasing memory manually.

Also note, that the code only initializes Student::tests of the first member of the array, the rest of Student objects have this member uninitialized. The result of expression studentFiles[i].tests[j] is undefined and is likely to cause a crash.

You need to initialize Student::tests member of each Student. And when done, deallocate Student::tests of each Student.


问:
Java reflection - classloader detecting moved class in old and new package
I have been messing around with the class loader and other reflection methods, and it seems I have run into a weird bug.   I used to have a file, lets say "ClassA.java" in one package, lets say "com.a".  However, I had to the need to move it to package "com.b".

Now when I use this code to grab all classes in both packages,

```<code>ClassLoader[] classLoaders = new ClassLoader[] { ClasspathHelper.contextClassLoader(), ClasspathHelper.staticClassLoader() };

    String[] packagePrefixes = {"com.a", "com.b"};
    FilterBuilder filterBuilder = new FilterBuilder();
    for (String packagePrefix : packagePrefixes)
        filterBuilder.includePackage(packagePrefix);

    ConfigurationBuilder configurationBuiler = new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false), new ResourcesScanner())
            .setUrls(ClasspathHelper.forClassLoader(classLoaders))
            .filterInputsBy(filterBuilder);

    Set<Class<?>> allClasses = new Reflections(configurationBuiler).getSubTypesOf(Object.class);
</code>```

The "ClassA.java" class appears twice in the allClasses set (Because the classes are ultimately different due to their different packages)

I tried cleaning and deleting/remaking the packages and files, but it seems to believe the file exists in both packages.

When I dragged the file into "com.b", eclipse gave me the normal pop-up and I did not check the "update fully qualified names in non-Java files".

I have a maven project. Any Ideas?  Thanks!

答:
If this is a webapp, delete the server and recreate it. In my case, it was a webapp deployed from within Eclipse into a tomcat server. Nothing worked until I deleted the server and recreated it, then readded the webapp and started the server again. BOOM. Problem solved.

Some cache somewhere was not getting cleared. Clearing tomcat's the working directory was not enough.

Hope this helps someone out there.

Body:
I have been messing around with the class loader and other reflection methods, and it seems I have run into a weird bug.   I used to have a file, lets say "ClassA.java" in one package, lets say "com.a".  However, I had to the need to move it to package "com.b".

Now when I use this code to grab all classes in both packages,

ClassLoader[] classLoaders = new ClassLoader[] { ClasspathHelper.contextClassLoader(), ClasspathHelper.staticClassLoader() };

    String[] packagePrefixes = {"com.a", "com.b"};
    FilterBuilder filterBuilder = new FilterBuilder();
    for (String packagePrefix : packagePrefixes)
        filterBuilder.includePackage(packagePrefix);

    ConfigurationBuilder configurationBuiler = new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false), new ResourcesScanner())
            .setUrls(ClasspathHelper.forClassLoader(classLoaders))
            .filterInputsBy(filterBuilder);

    Set<Class<?>> allClasses = new Reflections(configurationBuiler).getSubTypesOf(Object.class);

The "ClassA.java" class appears twice in the allClasses set (Because the classes are ultimately different due to their different packages)

I tried cleaning and deleting/remaking the packages and files, but it seems to believe the file exists in both packages.

When I dragged the file into "com.b", eclipse gave me the normal pop-up and I did not check the "update fully qualified names in non-Java files".

I have a maven project. Any Ideas?  Thanks!


问:
When `HttpGet` handling `Create` action method just returns `View()`, why doesn't the javascript validation get triggered on the browser?
When HttpGet handling Create action method just returns View(), it causes all form fields to be uninitialized.

Why javascript validation does not get triggered when users views the blank form?

答: In Rails the answer is because validations are only called on save. I imagine the answer is the same or similar here.</p>

ContentLicense: CC BY-SA 2.5