问:
multinom: how to get the number of observations
I am using multinom from nnet to create a logistic model from a massive clinical database. The syntax I'm using is:

```<code>library(nnet)
fit=multinom(group ~ sex + age + var3 + var4,
            data=d, na.action = na.omit)
</code>```

Now, each row (a patient) has a different number of NAs, as not all clinical data were recorded for all patients, and it is not clear to me if the model only uses those rows for which all of the variables do not contain any NAs.
More in general, it would be useful to obtain the Ns of observations that the model is based on, which I suspect is smaller that the number of rows of my dataframe (N of patients).
I have looked everywhere but I don't seem to be able to find how to do this.

答:
I believe nrow(residuals(fit)) should work (pointed out in comments that residuals() returns a matrix).

If you want to explore the data set that was used to fit the model, you can do:

```<code>mf <- model.frame(group ~ sex + age + var3 + var4, data=d,
                  na.action=na.omit)
</code>```

(this is how multinom processes your data) and then count the number of rows, tabulate the number of observations in different categories for different variables (e.g. table(mf$var3)), etc.. lapply(mf,table) should tabulate the number of observations by category for every variable.

You might find the describe function from the Hmisc package useful:

```<code>Hmisc::describe(group ~ sex + age + var3 + var4, data=d)
</code>```

Body:
I am using multinom from nnet to create a logistic model from a massive clinical database. The syntax I'm using is:

library(nnet)
fit=multinom(group ~ sex + age + var3 + var4,
            data=d, na.action = na.omit)

Now, each row (a patient) has a different number of NAs, as not all clinical data were recorded for all patients, and it is not clear to me if the model only uses those rows for which all of the variables do not contain any NAs.
More in general, it would be useful to obtain the Ns of observations that the model is based on, which I suspect is smaller that the number of rows of my dataframe (N of patients).
I have looked everywhere but I don't seem to be able to find how to do this.

Body:
I believe nrow(residuals(fit)) should work (pointed out in comments that residuals() returns a matrix).

If you want to explore the data set that was used to fit the model, you can do:

mf <- model.frame(group ~ sex + age + var3 + var4, data=d,
                  na.action=na.omit)

(this is how multinom processes your data) and then count the number of rows, tabulate the number of observations in different categories for different variables (e.g. table(mf$var3)), etc.. lapply(mf,table) should tabulate the number of observations by category for every variable.

You might find the describe function from the Hmisc package useful:

Hmisc::describe(group ~ sex + age + var3 + var4, data=d)

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
if else condition of css in jQuery not working
I wrote below code to get my output.

```<code>$(document).ready(function(){
  if ($('.figure').css("left","702px")) {
    $('.level1').css("display", "inline-block");
  } else {
    $('.level1').css("display", "none");
  }
});
</code>```

What I want when my .figure is reach to left 702px. I want to show level1 icon. But now display none is not applying before 702px. That is level1 icon showing before reaching to 702px. Anything wrong ? please help. Even i want to add more conditions that is after some for example left 1500px of .figure then show level2 icon. Thanks.

答:
Here you go with an example solution

$('button').click(function(){
  $('div').css('left', '100px');

  if($('div').css('left') == '100px'){
    $('span').css('display', 'block');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  display: none;
}

div {
  width: 50px;
  height: 50px;
  border: 1px solid #000;
  position: relative;
}</code>```

<button>Click ME!!!</button>

Clicked ME!!!```

Hope this will help you.

ContentLicense: CC BY-SA 3.0

Body:
I wrote below code to get my output.

$(document).ready(function(){
  if ($('.figure').css("left","702px")) {
    $('.level1').css("display", "inline-block");
  } else {
    $('.level1').css("display", "none");
  }
});

What I want when my .figure is reach to left 702px. I want to show level1 icon. But now display none is not applying before 702px. That is level1 icon showing before reaching to 702px. Anything wrong ? please help. Even i want to add more conditions that is after some for example left 1500px of .figure then show level2 icon. Thanks.

Body:
Here you go with an example solution

$('button').click(function(){
  $('div').css('left', '100px');

  if($('div').css('left') == '100px'){
    $('span').css('display', 'block');
  }
});

span {
  display: none;
}

div {
  width: 50px;
  height: 50px;
  border: 1px solid #000;
  position: relative;
}

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

<button>Click ME!!!</button>

<span>Clicked ME!!!</span>

Hope this will help you.


问:
How to change label value to be like password field value?
i'm having password like value to be set into label to be shown as ***(as per characters).

```<code><label>password</label>
</code>```

Output of this shown like below,because label value whatever it is.

```<code>password
</code>```

Expected result:

********

In my case its should be converted like ******** (as per no of characters).

Am newbie to js. Any one suggest me key points to do this.

How to convert this to be number of * values as per characters?

答:
Here is another simple solution :</p>

```<code><html>
<body>

<label id="passw">password</label>

<script>
var pass= document.getElementById("passw").innerHTML;
var char = pass.length;
var password ="";
for (i=0;i<char;i++)
{
password += "*";
}
document.getElementById("passw").innerHTML = password;
</script>

</body>
</html>
</code>```

Body:
i'm having password like value to be set into label to be shown as ***(as per characters).

password

Output of this shown like below,because label value whatever it is.

password

Expected result:

********

In my case its should be converted like ******** (as per no of characters).

Am newbie to js. Any one suggest me key points to do this.

How to convert this to be number of * values as per characters?

Body:
Here is another simple solution :

<html>
<body>

<label id="passw">password</label>

<script>
var pass= document.getElementById("passw").innerHTML;
var char = pass.length;
var password ="";
for (i=0;i<char;i++)
{
password += "*";
}
document.getElementById("passw").innerHTML = password;
</script>

</body>
</html>


问:
Dynamically change the template depend on screen orientation ionic v1
I am working on ionic 1 project. I want to change the template according to screen orientation like:

```<code> if(portrait)
  // template 1
else
 // template 2
</code>```

I tried below code:

```<code>//detect orientation here
function weAreOnPortrait() {
    return true
};
$stateProvider.state({
  templateUrl: function () {
    if (weAreOnPortrait()) {return 'tmpl/feature/_portrait.html'}
    else {return 'tmpl/feature/_landscape.html'}
  },
  controller: 'CommonControllerForBothCases'
});
</code>```

But this is running only once. I want to run every time the orientation changes.

How can I manage this?

I am able to get the orientation using https://github.com/apache/cordova-plugin-screen-orientation plugin.

答:
You have to rewrite your route-definition a little bit, use an IIFE to execute your desired template-url for templateUrl depending on your screen-orientation:

```<code>function weAreOnPortrait() {
    return screen.orientation.type && screen.orientation.type.indexOf('portrait') !== -1
}

$stateProvider.state({
  templateUrl: (function () {
    if (weAreOnPortrait()) {return 'tmpl/feature/_portrait.html'}
    else {return 'tmpl/feature/_landscape.html'}
  })(),
  controller: 'CommonControllerForBothCases'
});
</code>```

And you need a listener to screen-orientation changes to reload the page if a change has been detected:

```<code>window.addEventListener("orientationchange", function(){

    // if a change was detected reload page again by using transitionTo
    $state.transitionTo($state.current, {
            reload: true
    });

    // or by using go
    $state.go($state.current, {}, {reload: true});

    // or by using location
    location.reload(true)

});
</code>```

Although I could not test it, this should work.

Hope it helps.

Body:
I am working on ionic 1 project. I want to change the template according to screen orientation like:

 if(portrait)
  // template 1
else
 // template 2

I tried below code:

//detect orientation here
function weAreOnPortrait() {
    return true
};
$stateProvider.state({
  templateUrl: function () {
    if (weAreOnPortrait()) {return 'tmpl/feature/_portrait.html'}
    else {return 'tmpl/feature/_landscape.html'}
  },
  controller: 'CommonControllerForBothCases'
});

But this is running only once. I want to run every time the orientation changes.

How can I manage this?

I am able to get the orientation using https://github.com/apache/cordova-plugin-screen-orientation plugin.

Body:
You have to rewrite your route-definition a little bit, use an IIFE to execute your desired template-url for templateUrl depending on your screen-orientation:

function weAreOnPortrait() {
    return screen.orientation.type && screen.orientation.type.indexOf('portrait') !== -1
}

$stateProvider.state({
  templateUrl: (function () {
    if (weAreOnPortrait()) {return 'tmpl/feature/_portrait.html'}
    else {return 'tmpl/feature/_landscape.html'}
  })(),
  controller: 'CommonControllerForBothCases'
});

And you need a listener to screen-orientation changes to reload the page if a change has been detected:

window.addEventListener("orientationchange", function(){

    // if a change was detected reload page again by using transitionTo
    $state.transitionTo($state.current, {
            reload: true
    });

    // or by using go
    $state.go($state.current, {}, {reload: true});

    // or by using location
    location.reload(true)

});

Although I could not test it, this should work.

Hope it helps.


问:
Python, Stop a Thread
I'm trying to create a class that pings an ip address and keeps a record for connected/ not connected times.

Since this class is a part of a GUI, I wish to stop this thread when asked by user.

Found some Q&As regrading this issue, but neither one actually causes thread to stop.

I'm trying to make a method, a part of this class that will stop self.run()

Here's my Pinger class:

```<code>class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4

    def run(self):
            self.start_ping()

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while True:
            ping_result = os.system('ping %s -n 1 >Null' % self.address)
            self.ping_vector.append(ping_result)

            if self.last_ping != ping_result:
                text = ['Reachable', 'Lost']
                print(str(self.timestamp)[:-4], self.address, text[ping_result])

            round_time_qouta = datetime.datetime.now() - self.timestamp
            self.timestamp = datetime.datetime.now()
            self.update_time_counter(ping_result, round_time_qouta)

            self.last_ping = ping_result
            time.sleep(self.ping_rate)

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]
</code>```

答:
use _Thread_stop():

MyPinger._Thread__stop()

Title: Python, Stop a Thread

Body:
I'm trying to create a class that pings an ip address and keeps a record for connected/ not connected times.

Since this class is a part of a GUI, I wish to stop this thread when asked by user.

Found some Q&As regrading this issue, but neither one actually causes thread to stop.

I'm trying to make a method, a part of this class that will stop self.run()

Here's my Pinger class:

class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4

    def run(self):
            self.start_ping()

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while True:
            ping_result = os.system('ping %s -n 1 >Null' % self.address)
            self.ping_vector.append(ping_result)

            if self.last_ping != ping_result:
                text = ['Reachable', 'Lost']
                print(str(self.timestamp)[:-4], self.address, text[ping_result])

            round_time_qouta = datetime.datetime.now() - self.timestamp
            self.timestamp = datetime.datetime.now()
            self.update_time_counter(ping_result, round_time_qouta)

            self.last_ping = ping_result
            time.sleep(self.ping_rate)

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]


问:
Integrated Onlyoffice Documentserver in Owncloud Documents are not syncable anylonger
I integrated Onlyoffice Documentserver into my Owncloud Instance.
Now I cannot sync my files from Owncloud, because they are hidden and renamed for onlyoffice usage. Now I see files named .Table.xlsx~34324fs
something like that.

Also the directory structure is not mirrored to the webspace directory as usual....

Is Documentserver storing all the files and directory now?

Is there a opportunity to sync the files from owncloud as usual?

答: i found a solution simply sync over davs protocol working like a charme...</p>


问:
Select an input after its inserted using `Ember.run`
Updated — The problem with my solution below was with if statement around Ember.run. Removing it solved the problem, but my approach was also incorrect. Instead of scheduling the focus for after rendering, I should make a custom component as acorncom suggested.

Original Question:

I'm building a list of text inputs based on an array on my model. On newline I'd like to insert a new text field and then select it. I'm trying to do this with Ember.run.scheduleOnce, but the function I provide is never called.

I've reopened the textfield to expose a data-index attribute binding, and in my template am rendering:

```<code>{{#each model.entries as |entry index|}}
  {{input value=entry.text class='field--entry' data-index=index insert-newline=(action 'insertEntry' index)}}
{{/each}}
</code>```

In my controller:

```<code>actions: {
  insertEntry(index){
    // This works fine and a new textfield is added.
    this.get('model.entries').addObject({text: 'Example'});

    if (index){
      Ember.run.scheduleOnce('afterRender', this, function(){
        // This doesn't seem to work at all.
        console.log("This is never logged");
        $(".field--entry[data-index='" + index + 1 + "']").focus();
      });
    }
  }
}
</code>```

答:
I don't think you need to manually manipulate the focus:
This Ember can set the autofocus attritbute on render.
"(eq index 0)" sets it to true on the first element only</p>

```<code>{{#each model.entries as |entry index|}}
  {{input value=entry.text autofocus=(eq index 0)}}
{{/each}}
</code>```

Body:
Updated — The problem with my solution below was with if statement around Ember.run. Removing it solved the problem, but my approach was also incorrect. Instead of scheduling the focus for after rendering, I should make a custom component as acorncom suggested.

Original Question:

I'm building a list of text inputs based on an array on my model. On newline I'd like to insert a new text field and then select it. I'm trying to do this with Ember.run.scheduleOnce, but the function I provide is never called.

I've reopened the textfield to expose a data-index attribute binding, and in my template am rendering:

{{#each model.entries as |entry index|}}
  {{input value=entry.text class='field--entry' data-index=index insert-newline=(action 'insertEntry' index)}}
{{/each}}

In my controller:

actions: {
  insertEntry(index){
    // This works fine and a new textfield is added.
    this.get('model.entries').addObject({text: 'Example'});

    if (index){
      Ember.run.scheduleOnce('afterRender', this, function(){
        // This doesn't seem to work at all.
        console.log("This is never logged");
        $(".field--entry[data-index='" + index + 1 + "']").focus();
      });
    }
  }
}

Body:
I don't think you need to manually manipulate the focus:
This Ember can set the autofocus attritbute on render.
"(eq index 0)" sets it to true on the first element only

{{#each model.entries as |entry index|}}
  {{input value=entry.text autofocus=(eq index 0)}}
{{/each}}


问:
Getting null_pointer_exception when accessing _aggs elements in Scripted Metric Aggregation

I have an index of stock ticks for every second that look like the following and I am trying to aggregate them together into larger ticks of 5 minutes. Aggregating the high and low is easy using min/max. However the open and close are harder. I am trying to use the Scripted Metric Aggregation but I am getting a null pointer exception that I can't explain.

```<code>{ "time": "2017-12-06 12:02:00", "high": 10, "low": 1, "open": 1, "close": 5}
</code>```

My query looks like the following, although I've removed a lot from combine_script and reduce_script just so it is easy to read.

```<code>{
    "size": 0,
    "aggs": {
        "ticks": {
            "date_histogram": {
                "field":"time",
                "interval":"5m"
            },
            "aggs": {
                "open": {
                    "scripted_metric": {
                        "init_script": "params._agg.opens = []",
                        "map_script": "params._agg.opens.add(['time': doc.time.value.getMillis(),'open':doc.open.value])",
                        "combine_script": "return params._agg.opens[0]",
                        "reduce_script":  "return params._aggs[0]"
                    }
                }
            }
        }
    }
}
</code>```

If I run the query you can see it outputs a Map (with the keys time and open) for the "open" value as you'd expect.

```<code>{
  "aggregations": {
    "ticks": {
      "buckets": [
        {
          "key_as_string": "2017-12-06 14:20",
          "key": 1512570000000,
          "doc_count": 6,
          "volume": {
            "value": 84.09597664
          },
          "high": {
            "value": 12886
          },
          "low": {
            "value": 12874.99
          },
          "open": {
            "value": {
              "time": 1512570420000,
              "open": 12874.99
            }
          }
        }
      ]
    }
  }
}
</code>```

But if I try and access any properties of the map (as a simple example just returning params._aggs[0]['open']) I get a null pointer exception. I've tried accessing it with params._aggs[0].open and even setting it to a map and then accessing that map Map myMap = params._aggs[0]; return myMap['open']; but I get the same error.

```<code>{
  "error": {
    "root_cause": [],
    "type": "search_phase_execution_exception",
    "reason": "",
    "phase": "fetch",
    "grouped": true,
    "failed_shards": [],
    "caused_by": {
      "type": "script_exception",
      "reason": "runtime error",
      "script_stack": [
        "return params._aggs[0]['open']",
        "                   ^---- HERE"
      ],
      "script": "return params._aggs[0]['open']",
      "lang": "painless",
      "caused_by": {
        "type": "null_pointer_exception",
        "reason": null
      }
    }
  },
  "status": 503
}
</code>```

This is a problem because I need to do some additional stuff in reduce_script but can't seem to access any properties of the maps in _aggs without getting an NPE.

答:
I was able to solve the problem by using the ?. operator. I am guessing because I had some null fields, it was blowing up by trying to access properties on null. So by just adding that, I get what I expect. So it is just the simple matter of params._aggs[0] ?. open

```<code>{
    "size": 0,
    "aggs": {
        "ticks": {
            "date_histogram": {
                "field":"time",
                "interval":"5m"
            },
            "aggs": {
                "open": {
                    "scripted_metric": {
                        "init_script": "params._agg.opens= []",
                        "map_script": "params._agg.opens.add(['time': doc.time.value.getMillis(),'open':doc.open.value])",
                        "combine_script": "return params._agg.opens[0]",
                        "reduce_script":  "return params._aggs[0]?.open"
                    }
                }
            }
        }
    }
}
</code>```

```<code>{
  "aggregations": {
    "ticks": {
      "buckets": [
        {
          "key_as_string": "2017-12-07 12:20",
          "key": 1512649200000,
          "doc_count": 2,
          "open": {
            "value": 13
          }
        }
      ]
    }
  }
}
</code>```

Body:
I have an index of stock ticks for every second that look like the following and I am trying to aggregate them together into larger ticks of 5 minutes. Aggregating the high and low is easy using min/max. However the open and close are harder. I am trying to use the Scripted Metric Aggregation but I am getting a null pointer exception that I can't explain.

{ "time": "2017-12-06 12:02:00", "high": 10, "low": 1, "open": 1, "close": 5}

My query looks like the following, although I've removed a lot from combine_script and reduce_script just so it is easy to read.

{
    "size": 0,
    "aggs": {
        "ticks": {
            "date_histogram": {
                "field":"time",
                "interval":"5m"
            },
            "aggs": {
                "open": {
                    "scripted_metric": {
                        "init_script": "params._agg.opens = []",
                        "map_script": "params._agg.opens.add(['time': doc.time.value.getMillis(),'open':doc.open.value])",
                        "combine_script": "return params._agg.opens[0]",
                        "reduce_script":  "return params._aggs[0]"
                    }
                }
            }
        }
    }
}

If I run the query you can see it outputs a Map (with the keys time and open) for the "open" value as you'd expect.

{
  "aggregations": {
    "ticks": {
      "buckets": [
        {
          "key_as_string": "2017-12-06 14:20",
          "key": 1512570000000,
          "doc_count": 6,
          "volume": {
            "value": 84.09597664
          },
          "high": {
            "value": 12886
          },
          "low": {
            "value": 12874.99
          },
          "open": {
            "value": {
              "time": 1512570420000,
              "open": 12874.99
            }
          }
        }
      ]
    }
  }
}

But if I try and access any properties of the map (as a simple example just returning params._aggs[0]['open']) I get a null pointer exception. I've tried accessing it with params._aggs[0].open and even setting it to a map and then accessing that map Map myMap = params._aggs[0]; return myMap['open']; but I get the same error.

{
  "error": {
    "root_cause": [],
    "type": "search_phase_execution_exception",
    "reason": "",
    "phase": "fetch",
    "grouped": true,
    "failed_shards": [],
    "caused_by": {
      "type": "script_exception",
      "reason": "runtime error",
      "script_stack": [
        "return params._aggs[0]['open']",
        "                   ^---- HERE"
      ],
      "script": "return params._aggs[0]['open']",
      "lang": "painless",
      "caused_by": {
        "type": "null_pointer_exception",
        "reason": null
      }
    }
  },
  "status": 503
}

This is a problem because I need to do some additional stuff in reduce_script but can't seem to access any properties of the maps in _aggs without getting an NPE.

Body:
I was able to solve the problem by using the ?. operator. I am guessing because I had some null fields, it was blowing up by trying to access properties on null. So by just adding that, I get what I expect. So it is just the simple matter of params._aggs[0] ?. open

{
    "size": 0,
    "aggs": {
        "ticks": {
            "date_histogram": {
                "field":"time",
                "interval":"5m"
            },
            "aggs": {
                "open": {
                    "scripted_metric": {
                        "init_script": "params._agg.opens= []",
                        "map_script": "params._agg.opens.add(['time': doc.time.value.getMillis(),'open':doc.open.value])",
                        "combine_script": "return params._agg.opens[0]",
                        "reduce_script":  "return params._aggs[0]?.open"
                    }
                }
            }
        }
    }
}

{
  "aggregations": {
    "ticks": {
      "buckets": [
        {
          "key_as_string": "2017-12-07 12:20",
          "key": 1512649200000,
          "doc_count": 2,
          "open": {
            "value": 13
          }
        }
      ]
    }
  }
}


问:
How to make a type with date field deserializable from json
I need to define data type that would have date field and deserialize it from json. Here's my attempt.

```<code>data Some = Some { date :: Data.Time.Calendar.Day } deriving (Show, Generic)

instance FromJSON Day where
     parseJSON (Object x) = parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
</code>```

Here's errors.

```<code>• Couldn't match type ‘m0 t0’ with ‘Day’
  Expected type: aeson-1.2.3.0:Data.Aeson.Types.Internal.Parser Day
    Actual type: aeson-1.2.3.0:Data.Aeson.Types.Internal.Parser
                   (m0 t0)
• In the expression:
    parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
  In an equation for ‘parseJSON’:
      parseJSON (Object x)
        = parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
  In the instance declaration for ‘FromJSON Day’
</code>```

I find it very strange that I can't find any data type with exposed constructor for creating Date objects. And I can't find the function that would parse Date from String

答:
parseTimeM has type (Monad m, ParseTime t) => ... -> m t, which if you specialize it at Day, is ... -> m Day, so you need to chain monadic actions (with m ~ Parser) or unwrap m somehow (e.g., m ~ Maybe).

```<code>(x .: pack "date") >>= parseTimeM True defaultTimeLocale "%F"
</code>```

Also, Day already has an instance, that parses the YYYY-MM-DD format.

Body:
I need to define data type that would have date field and deserialize it from json. Here's my attempt.

data Some = Some { date :: Data.Time.Calendar.Day } deriving (Show, Generic)

instance FromJSON Day where
     parseJSON (Object x) = parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")

Here's errors.

• Couldn't match type ‘m0 t0’ with ‘Day’
  Expected type: aeson-1.2.3.0:Data.Aeson.Types.Internal.Parser Day
    Actual type: aeson-1.2.3.0:Data.Aeson.Types.Internal.Parser
                   (m0 t0)
• In the expression:
    parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
  In an equation for ‘parseJSON’:
      parseJSON (Object x)
        = parseTimeM True defaultTimeLocale "%F" <$> x .: (pack "date")
  In the instance declaration for ‘FromJSON Day’

I find it very strange that I can't find any data type with exposed constructor for creating Date objects. And I can't find the function that would parse Date from String

Body:
parseTimeM has type (Monad m, ParseTime t) => ... -> m t, which if you specialize it at Day, is ... -> m Day, so you need to chain monadic actions (with m ~ Parser) or unwrap m somehow (e.g., m ~ Maybe).

(x .: pack "date") >>= parseTimeM True defaultTimeLocale "%F"

Also, Day already has an instance, that parses the YYYY-MM-DD format.


问:
Should an SP or IdP prefer Redirect or POST when both are available?
For AuthnRequest, Response, and LogoutRequest, if Redirect and POST are supported (per metadata), should one be preferred over another?</p>

答:
Most commonly, Requests can be either, but Responses are POST. This is driven by security and size of the Assertion.

Security: if using redirect, the Response is part of the URL. As such, it can be captured in various logs, as noted in the security considerations of the spec, specifically Section 3.4.5.2 lines 670-1 of saml-bindings.

Size: some enterprises send a large number of attributes, including big sets of groups. I've even seen avatars sent in assertions. This can make the size of the response very large, and in some cases, can overwhelm the browser's allowed URL size.

If neither of these are of concern, then either can be used.


问:
How do I organize my code when developing forms to meet the following requirements?
I'm simply trying to figure out the correct way to lay out the architecture for my forms to meet the following requirements:

The form must have server side validation.

If a user is filling out a form on domain.com/register and the form doesn't pass server side validation, they should be brought back to domain.com/register with the errors displaying.

(continued from point #2) If the user is brought back to domain.com/register to fix validation errors, the data they have already entered in to the inputs should automatically display.

If a user clicks back or forward on the form page the browser should not throw the "Confirm Form Resubmission" warning.

I'm a bit confused on where the form submit should be posting to.  Should the form on domain.com/register post to a different page that simply handles the validation? If so, how do I pass the validation errors and inputed data back to domain.com/register?

Or, should the form be posting to itself? If so, how do I prevent the browser from throwing the "Confirm Form Resubmission" warning when clicking the back or forward button?

答:
A logical way of approaching this (that attempts to keep all related items as localised as possible), would be to use a single page that has a "mode" switch statement near the top with an "update" case in it that contains your validation code.

Within the form, you'd simply post to the same page that you're on, but you'd add a hidden field in the form called "mode" with a value of "update". As such when the form is submitted execution will flow into the "update" case of your switch statement and you can carry out the required validation.

If the validation succeeds, you'd usually kick forward to another page (via the use of header('Location: ...'); followed by exit();) and if validation fails, execution will simply continue down the page at which point you should output the errors that occurred during the validation.

ContentLicense: CC BY-SA 2.5


问:
how do you generate random numbers from a bimodal Gaussian Probability Density Function in MATLAB?
How do you generate numbers from a bimodal Gaussian PDF in MATLAB?

For a unimodal symmetric Gaussian PDF it is really easy:

```<code>x=randn(1000,1);
</code>```

But now I want to draw 1000 numbers from a Gaussian PDF that has two peaks (or two means).  How do I do this?

答:
You can generate the bimodal Normal (Gaussian) distribution by combining two Normal distributions with different mean and standard deviation (as explained in this comment).

In MATLAB you can do this in several ways:

First, we need to specify the mean (mu) and standard deviation (sigma) that characterize our Normal distributions, usually noted as N(mu, sigma).

Normal distribution a: N(-1, 0.5)

```<code>mu_a = -1;      % Mean (a).
sigma_a = 0.5;  % Standard deviation (a).
</code>```

Normal distribution b: N(2, 1)

```<code>mu_b = 2;       % Mean (b).
sigma_b = 1;    % Standard deviation (b).
</code>```

Finally, let's define the size of our random vectors:

```<code>sz = [1e4, 1];  % Size vector.
</code>```

Now let's generate the bimodal random values by concatenating two vectors of Normally distributed random numbers:

OPTION 1: using randn

```<code>x_1 = [sigma_a*randn(sz) + mu_a, sigma_b*randn(sz) + mu_b];
</code>```

OPTION 2: using normrnd

```<code>x_2 = [normrnd(mu_a, sigma_a, sz), normrnd(mu_b, sigma_b, sz)];
</code>```

OPTION 3: using random

```<code>x_3 = [random('Normal', mu_a, sigma_a, sz), random('Normal', mu_b, sigma_b, sz)];
</code>```

Let's visualize the results:

```<code>subplot(1, 3, 1); histogram(x_1);
subplot(1, 3, 2); histogram(x_2);
subplot(1, 3, 3); histogram(x_3);
</code>```

Body:
How do you generate numbers from a bimodal Gaussian PDF in MATLAB?

For a unimodal symmetric Gaussian PDF it is really easy:

x=randn(1000,1);

But now I want to draw 1000 numbers from a Gaussian PDF that has two peaks (or two means).  How do I do this?

Body:
You can generate the bimodal Normal (Gaussian) distribution by combining two Normal distributions with different mean and standard deviation (as explained in this comment).

In MATLAB you can do this in several ways:

First, we need to specify the mean (mu) and standard deviation (sigma) that characterize our Normal distributions, usually noted as N(mu, sigma).

Normal distribution a: N(-1, 0.5)

mu_a = -1;      % Mean (a).
sigma_a = 0.5;  % Standard deviation (a).

Normal distribution b: N(2, 1)

mu_b = 2;       % Mean (b).
sigma_b = 1;    % Standard deviation (b).

Finally, let's define the size of our random vectors:

sz = [1e4, 1];  % Size vector.

Now let's generate the bimodal random values by concatenating two vectors of Normally distributed random numbers:

OPTION 1: using randn

x_1 = [sigma_a*randn(sz) + mu_a, sigma_b*randn(sz) + mu_b];

OPTION 2: using normrnd

x_2 = [normrnd(mu_a, sigma_a, sz), normrnd(mu_b, sigma_b, sz)];

OPTION 3: using random

x_3 = [random('Normal', mu_a, sigma_a, sz), random('Normal', mu_b, sigma_b, sz)];

Let's visualize the results:

subplot(1, 3, 1); histogram(x_1);
subplot(1, 3, 2); histogram(x_2);
subplot(1, 3, 3); histogram(x_3);


问:
Exception not being caught by its catch block, then the method throws an exception of another kind
I'm experiencing some strange behavior but maybe I just don't completely understand how exception-handling works. I have the following piece of code:

```<code>public String encrypt(String msg, SecretKeySpec key) throws RuntimeException {

    try {

        System.out.println("1");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        System.out.println("2");

        ...

    } catch (InvalidKeyException e) {
        System.out.println("3");
        throw new RuntimeException("invalid key");
    }

}
</code>```

Upon invoking, the method throws a RuntimeException and the console output is: 1

(The cipher object is an attribute of the class the method is part of and was successfully created using Cipher.getInstance("AES", "BC"). Here is the documentation of the init method where the program fails.)

答:
The symptoms tell us that init is throwing a RuntimeException. Since that isn't an InvalidKeyException, your catch handler doesn't catch it.

Remember that although init is only documented to throw InvalidKeyException, it can also throw any RuntimeException it likes. RuntimeException doesn't have to be declared (or caught); it's an unchecked exception, that's its purpose.

Although you don't have to catch them, you can catch them if you want. Normally that's not good practice (it's normally a RuntimeException for a good reason), but in limited cases catching it can be appropriate.

Body:
I'm experiencing some strange behavior but maybe I just don't completely understand how exception-handling works. I have the following piece of code:

public String encrypt(String msg, SecretKeySpec key) throws RuntimeException {

    try {

        System.out.println("1");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        System.out.println("2");

        ...

    } catch (InvalidKeyException e) {
        System.out.println("3");
        throw new RuntimeException("invalid key");
    }

}

Upon invoking, the method throws a RuntimeException and the console output is: 1

(The cipher object is an attribute of the class the method is part of and was successfully created using Cipher.getInstance("AES", "BC"). Here is the documentation of the init method where the program fails.)


问:
ZF2 multi-select form preselect values ManyToMany
I can't get to preselect values in a multiselect form element representing a many to many relation.

In my model $admin I have the proper data : an ArrayCollection containing the correct CampsTypes but in the form I can't get the multiselect to preselect the proper options.

Admins model

```<code>/**
 * @var ArrayCollection CampsTypes $campstypes
 *
 * @ORM\ManyToMany(targetEntity="CampsTypes", inversedBy="admins", cascade={"persist"})
 * @ORM\JoinTable(name="campstypes_admins",
 *      joinColumns={@ORM\JoinColumn(name="admins_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="campstypes_id", referencedColumnName="id")}
 *      )
 */
private $campstypes;
</code>```

CampsType model

```<code>/**
 * @var ArrayCollection Admins $admins
 *
 * @ORM\ManyToMany(targetEntity="Admins", mappedBy="campstypes", cascade={"persist"})
 */
private $admins;
</code>```

Then I define my form select element as follow

```<code>        [
            'type' => 'DoctrineModule\Form\Element\ObjectSelect',
            'name' => 'campTypes',
            'required' => false,
            'options' => [
                'object_manager' => $this->getServiceLocator()->get(EntityManager::class),
                'target_class'   => CampsTypes::class,
                'property'       => 'title',
                'label'          => 'Type de camps autorisés',
                'instructions'   => 'Ne rien sélectionner si edition d\'un super admin',

            ],
            'attributes' => [
                'class'    => '',
                'multiple' => 'multiple',
            ]
        ],
</code>```

And finally here is my action to receive the form

```<code>protected function saveAdmin(Admins &$admin, &$form, &$msg)
{
    $em = $this->getEntityManager();
    /** @var CampTypesService $serviceCampTypes */
    $serviceCampTypes = $this->getServiceLocator()->get(CampTypesService::class);

    $form->bind($admin);

    if ($this->getRequest()->isPost()) {
        $data = $this->getRequest()->getPost();
        if (empty($data['password'])) {
            $form->remove('password');
        }
        $form->setData($data);
        if ($form->isValid()) {
            if (isset($data['campTypes'])) {
                $ids = $form->get('campTypes')->getValue();
                $campsTypes = new ArrayCollection($serviceCampTypes->getCampTypesByIds(array_values($ids)));
                foreach ($campsTypes as &$campsType) {
                    /** @var CampsTypes $campsType*/
                    $campsType->addAdmin($admin);
                }
                $admin->setCampTypes($campsTypes);
            }
            $em->persist($admin);
            $em->flush();
            $msg = 'Sauvegarde des données effectuée';
            return;
        }
    }

    return;
}
</code>```

I'm getting out of solution to try.

Any idea what I am doing wrong ?

答:
Have you read this ? I have the feeling you're looking for the ObjectMultiCheckbox instead of the ObjectSelect Form Element.

Examples from my own code

Usage for a single select (use case: set/change a default currency for some other entity)

```<code>$this->add([
    'type' => ObjectSelect::class,
    'required' => true,
    'name' => 'defaultCurrency',
    'options' => [
        'object_manager' => $this->getEntityManager(),
        'target_class'   => Currency::class,
        'property'       => 'id',
// Use these commented lines if you wish to use a Repository function ('name' => 'repositoryFunctionName')
//        'is_method'      => true,
//        'find_method'    => [
//            'name' => 'getEnabledCurrencies',
//        ],
        'display_empty_item' => true,
        'empty_item_label'   => '---',
        'label' => _('Default currency'),
        'label_attributes' => [
            'class' => '',
            'title' => _('Default currency'),
        ],
        'label_generator' => function ($targetEntity) {
            /** @var Currency $targetEntity */
            return $targetEntity->getName(); // Generates option text based on name property of Entity (Currency in this case)
        },
    ],
]);
</code>```

Usage for multiple select (Use case: add/remove (multiple) roles to/from user)

```<code>$this->add([
    'name' => 'roles',
    'required' => false,
    'type' => ObjectMultiCheckbox::class,
    'options' => [
        'object_manager' => $this->getEntityManager(),
        'target_class'   => Role::class,
        'property'       => 'id',
        'display_empty_item' => true,
        'empty_item_label'   => '---',
        'label' => _('Roles'),
        'label_generator' => function ($targetEntity) {
            /** @var Role $targetEntity */
            return $targetEntity->getName();
        },
    ],
]);
</code>```

As a side note: you should really use factories more. I see you using the ServiceLocator throughout your class code, you can avoid that by injecting your needs via a Factory.

If you need more information, I suggest you have a look at a bunch of my past questions as well. I had quite a few, starting out similar to what you're looking for. Managed to figure quite a few of them out on my own and have tried to describe the solutions in depth.

Body:
I can't get to preselect values in a multiselect form element representing a many to many relation.

In my model $admin I have the proper data : an ArrayCollection containing the correct CampsTypes but in the form I can't get the multiselect to preselect the proper options.

Admins model

/**
 * @var ArrayCollection CampsTypes $campstypes
 *
 * @ORM\ManyToMany(targetEntity="CampsTypes", inversedBy="admins", cascade={"persist"})
 * @ORM\JoinTable(name="campstypes_admins",
 *      joinColumns={@ORM\JoinColumn(name="admins_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="campstypes_id", referencedColumnName="id")}
 *      )
 */
private $campstypes;

CampsType model

/**
 * @var ArrayCollection Admins $admins
 *
 * @ORM\ManyToMany(targetEntity="Admins", mappedBy="campstypes", cascade={"persist"})
 */
private $admins;

Then I define my form select element as follow

        [
            'type' => 'DoctrineModule\Form\Element\ObjectSelect',
            'name' => 'campTypes',
            'required' => false,
            'options' => [
                'object_manager' => $this->getServiceLocator()->get(EntityManager::class),
                'target_class'   => CampsTypes::class,
                'property'       => 'title',
                'label'          => 'Type de camps autorisés',
                'instructions'   => 'Ne rien sélectionner si edition d\'un super admin',

            ],
            'attributes' => [
                'class'    => '',
                'multiple' => 'multiple',
            ]
        ],

And finally here is my action to receive the form

protected function saveAdmin(Admins &$admin, &$form, &$msg)
{
    $em = $this->getEntityManager();
    /** @var CampTypesService $serviceCampTypes */
    $serviceCampTypes = $this->getServiceLocator()->get(CampTypesService::class);

    $form->bind($admin);

    if ($this->getRequest()->isPost()) {
        $data = $this->getRequest()->getPost();
        if (empty($data['password'])) {
            $form->remove('password');
        }
        $form->setData($data);
        if ($form->isValid()) {
            if (isset($data['campTypes'])) {
                $ids = $form->get('campTypes')->getValue();
                $campsTypes = new ArrayCollection($serviceCampTypes->getCampTypesByIds(array_values($ids)));
                foreach ($campsTypes as &$campsType) {
                    /** @var CampsTypes $campsType*/
                    $campsType->addAdmin($admin);
                }
                $admin->setCampTypes($campsTypes);
            }
            $em->persist($admin);
            $em->flush();
            $msg = 'Sauvegarde des données effectuée';
            return;
        }
    }

    return;
}

I'm getting out of solution to try.

Any idea what I am doing wrong ?

Body:
Have you read this ? I have the feeling you're looking for the ObjectMultiCheckbox instead of the ObjectSelect Form Element.

Examples from my own code

Usage for a single select (use case: set/change a default currency for some other entity)

$this->add([
    'type' => ObjectSelect::class,
    'required' => true,
    'name' => 'defaultCurrency',
    'options' => [
        'object_manager' => $this->getEntityManager(),
        'target_class'   => Currency::class,
        'property'       => 'id',
// Use these commented lines if you wish to use a Repository function ('name' => 'repositoryFunctionName')
//        'is_method'      => true,
//        'find_method'    => [
//            'name' => 'getEnabledCurrencies',
//        ],
        'display_empty_item' => true,
        'empty_item_label'   => '---',
        'label' => _('Default currency'),
        'label_attributes' => [
            'class' => '',
            'title' => _('Default currency'),
        ],
        'label_generator' => function ($targetEntity) {
            /** @var Currency $targetEntity */
            return $targetEntity->getName(); // Generates option text based on name property of Entity (Currency in this case)
        },
    ],
]);

Usage for multiple select (Use case: add/remove (multiple) roles to/from user)

$this->add([
    'name' => 'roles',
    'required' => false,
    'type' => ObjectMultiCheckbox::class,
    'options' => [
        'object_manager' => $this->getEntityManager(),
        'target_class'   => Role::class,
        'property'       => 'id',
        'display_empty_item' => true,
        'empty_item_label'   => '---',
        'label' => _('Roles'),
        'label_generator' => function ($targetEntity) {
            /** @var Role $targetEntity */
            return $targetEntity->getName();
        },
    ],
]);

As a side note: you should really use factories more. I see you using the ServiceLocator throughout your class code, you can avoid that by injecting your needs via a Factory.

If you need more information, I suggest you have a look at a bunch of my past questions as well. I had quite a few, starting out similar to what you're looking for. Managed to figure quite a few of them out on my own and have tried to describe the solutions in depth.


问:
HTML5 input type=date: Can I open/close the date picker with JavaScript?
I am trying to customise the HTML5 input type="date" element. I want to add a separate button clicking which will toggle visibility of the date picker dropdown. I couldn't find any info on this. Any help greatly appreciated!

答:
Here is Solution I made using CSS.

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

.exmp-wrp {
    margin-top: 100px;
    position: relative;
    width: 200px;
}

.btn-wrp {
    border: 1px solid #dadada;
    display: inline-block;
    width: 100%;
    position: relative;
    z-index: 10;
}

.btn-clck {
    border: none;
    background: transparent;
    width: 100%;
    padding: 10px;
}

.btn-clck::-webkit-calendar-picker-indicator {
    right: -10px;
    position: absolute;
    width: 78px;
    height: 40px;
    color: rgba(204, 204, 204, 0);
    opacity: 0
}

.btn-clck::-webkit-inner-spin-button {
    -webkit-appearance: none;
}
.btn-clck::-webkit-clear-button {
    margin-right:75px;
 }
.btn {
    height: 100%;
    background: #fda200;
    border: none;
    color: #fff;
    padding: 13px;
    position: absolute;
    right: 0;
    top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="exmp-wrp">
  <div class="btn-wrp">
    <input type="date" class="btn-clck"/>
  </div>
  <button class="btn">Click me</button>
</div></code>```

Body:
Here is Solution I made using CSS.

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

.exmp-wrp {
    margin-top: 100px;
    position: relative;
    width: 200px;
}

.btn-wrp {
    border: 1px solid #dadada;
    display: inline-block;
    width: 100%;
    position: relative;
    z-index: 10;
}

.btn-clck {
    border: none;
    background: transparent;
    width: 100%;
    padding: 10px;
}

.btn-clck::-webkit-calendar-picker-indicator {
    right: -10px;
    position: absolute;
    width: 78px;
    height: 40px;
    color: rgba(204, 204, 204, 0);
    opacity: 0
}

.btn-clck::-webkit-inner-spin-button {
    -webkit-appearance: none;
}
.btn-clck::-webkit-clear-button {
    margin-right:75px;
 }
.btn {
    height: 100%;
    background: #fda200;
    border: none;
    color: #fff;
    padding: 13px;
    position: absolute;
    right: 0;
    top: 0;
}

<div class="exmp-wrp">
  <div class="btn-wrp">
    <input type="date" class="btn-clck"/>
  </div>
  <button class="btn">Click me</button>
</div>


问:
XML Restrict based on another element value
Basically I have my XML version 1.0 and I have a complex element with following example:

```<code><tile>
  <position>5</position>
  <type>floor</type>
  <towerPlacement>true</towerPlacement>
</tile>
</code>```

I have defined following in my XML Schema:

```<code><xs:element name="type">
   <xs:simpleType>
   <xs:restriction base="xs:string">
   <xs:enumeration value="road"/>
   <xs:enumeration value="floor"/>
   <xs:enumeration value="startPos"/>
   <xs:enumeration value="endPos"/>
   </xs:restriction>
   </xs:simpleType>
</xs:element>
</code>```

Is there a way to make my towerPlacement true only if type = floor?

```<code><xs:element type="xs:boolean" name="towerPlacement" minOccurs="0" maxOccurs="1" />
</code>```

答:
XSD 1.0

Your constraint cannot be expressed in XSD 1.0.

XSD 1.1

Your constraint can be expressed in XSD 1.1 using an assertion to state that towerPlacement must only be true if type = 'floor':

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
           vc:minVersion="1.1">
  <xs:element name="tile">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="position" type="xs:integer"/>
        <xs:element name="type">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:enumeration value="road"/>
              <xs:enumeration value="floor"/>
              <xs:enumeration value="startPos"/>
              <xs:enumeration value="endPos"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
        <xs:element name="towerPlacement" type="xs:string"/>
      </xs:sequence>
      <xs:assert test="(type='floor' and towerPlacement='true')
                       or towerPlacement!='true'"/>
    </xs:complexType>
  </xs:element>
</xs:schema>
</code>```

Body:
Basically I have my XML version 1.0 and I have a complex element with following example:

<tile>
  <position>5</position>
  <type>floor</type>
  <towerPlacement>true</towerPlacement>
</tile>

I have defined following in my XML Schema:

<xs:element name="type">
   <xs:simpleType>
   <xs:restriction base="xs:string">
   <xs:enumeration value="road"/>
   <xs:enumeration value="floor"/>
   <xs:enumeration value="startPos"/>
   <xs:enumeration value="endPos"/>
   </xs:restriction>
   </xs:simpleType>
</xs:element>

Is there a way to make my towerPlacement true only if type = floor?

<xs:element type="xs:boolean" name="towerPlacement" minOccurs="0" maxOccurs="1" />

Body:
XSD 1.0

Your constraint cannot be expressed in XSD 1.0.

XSD 1.1

Your constraint can be expressed in XSD 1.1 using an assertion to state that towerPlacement must only be true if type = 'floor':

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
           vc:minVersion="1.1">
  <xs:element name="tile">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="position" type="xs:integer"/>
        <xs:element name="type">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:enumeration value="road"/>
              <xs:enumeration value="floor"/>
              <xs:enumeration value="startPos"/>
              <xs:enumeration value="endPos"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
        <xs:element name="towerPlacement" type="xs:string"/>
      </xs:sequence>
      <xs:assert test="(type='floor' and towerPlacement='true')
                       or towerPlacement!='true'"/>
    </xs:complexType>
  </xs:element>
</xs:schema>


问:
How to store image captured using camera.takePicture(null,null,mPicture) so that it can be displayed it in next activity?
I am making a custom camera application in android. I capture the image using

camera.takePicture(null,null,mPicture)" and "Camera.PictureCallBack()

I want to store the image taken from the camera so that I can display it in the next activity. How can it be done?

```<code>    Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);

            fos.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
        }
    }
};

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
            + "IMG_" + timeStamp + ".jpg");

    return mediaFile;
}
</code>```

答: You can use CameraView to implement the custom camera in very simple way which gives you the functionalities to capture image and video. You can see the DEMO where it the CameraActivity tooks the picture and PicturePreviewActivity and VideoPreviewActivity are use to preview the picture and video taken in CameraActivity.</p>

Body:
I am making a custom camera application in android. I capture the image using

camera.takePicture(null,null,mPicture)" and "Camera.PictureCallBack()

I want to store the image taken from the camera so that I can display it in the next activity. How can it be done?

    Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);

            fos.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
        }
    }
};

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
            + "IMG_" + timeStamp + ".jpg");

    return mediaFile;
}


问:
Dynamic queries with knex-postgis
I am building a simple API that also deal with geometries (store into postGIS).
I am using knex-postgis to access the ST_ spatial functions in postGIS with knex.

I have used this example to insert a point and it work when its hard coded.
But my lack of experience is leave me hanging, how can I make the query dynamic? I want to create a form with input for x and y value and send it to the ST_geomFromText function to save it to the geom type in the db.
Is this when  you would use parameters? Could someone point me in the right direction?

```<code>// insert a point
const sql1 = db.insert({
  id: 1,
  geom: st.geomFromText('Point(0 0)', 4326)
}).into('points').toString();
console.log(sql1);
// insert into "points" ("geom", "id") values
(ST_geomFromText('Point(0 0)'), '1')
</code>```

So far I have tried

```<code>router.post('/', (req, res, next) => {
  queries.create(req.body).then(poi => {
    res.json(poi[0]);
  });
});
</code>```

Insert query

```<code>  create(poi) {
    const sql = db.insert(poi).returning('*').into('poi');
    return sql;
  },
</code>```

In Postman I am sending this in its body

```<code>{
    "place": "test",
    "comments": "new",
    "numbers": 6,
    "geom": "st.geomFromText('Point(-71.064544 44.28787)', 4326)"
}
</code>```

But get an error "Unhandled rejection error: parse error - invalid geometry"
The hard coded object looks the same and is work fine.

I have a feeling that I am using the st.geomFromText wrong, but i dont I am not sure?

This is what i get if i console.log returned query

```<code>insert into "poi" ("comments", "geom", "numbers", "place") values ('new', 'st.geomFromText(''Point(-71.064544 44.28787)'', 4326)', 6, 'test')
</code>```

(see how it does not change st.geom.. to st_geom..? Also the quotation marks around the ST function and the Point object is not right)

This  string work when I run it in pgAdmin

```<code>insert into "poi" ("comments", "geom", "numbers", "place") values ('new', st_GeomFromText('Point(-71.064544 44.28787)', 4326), 6, 'test')
</code>```

EDIT:
I console.log the hardcoded version too. It does no appear to add the extra '' on the geometry value

```<code>insert into "poi" ("geom") values (ST_geomFromText('Point(-71.064544 44.28787)', 4326))
</code>```

Any advice?

答:
You pass coordinates from postman as string value in JSON object

```<code>"geom": "st.geomFromText('Point(-71.064544 44.28787)', 4326)"
</code>```

And expect your code to transform it into a function call

```<code>st.geomFromText('Point(-71.064544 44.28787)', 4326)
</code>```

What knex does in this case. It takes your string and convert it as it is string field (here you get a single quote ' replacement with double '' for Postgres to escape it).

What you can do. Pass your geometry to your API like this

```<code>"geom": "Point(-71.064544 44.28787)"
</code>```

And in your route handler

```<code>create(poi) {
  const sql = db.insert({
    place: poi.place,
    comments: poi.comments,
    numbers: poi.numbers,
    geom: st.geomFromText(poi.geom, 4326)
  }).returning('*').into('poi');
  return sql;
},
</code>```

Title: Dynamic queries with knex-postgis

Body:
I am building a simple API that also deal with geometries (store into postGIS).
I am using knex-postgis to access the ST_ spatial functions in postGIS with knex.

I have used this example to insert a point and it work when its hard coded.
But my lack of experience is leave me hanging, how can I make the query dynamic? I want to create a form with input for x and y value and send it to the ST_geomFromText function to save it to the geom type in the db.
Is this when  you would use parameters? Could someone point me in the right direction?

// insert a point
const sql1 = db.insert({
  id: 1,
  geom: st.geomFromText('Point(0 0)', 4326)
}).into('points').toString();
console.log(sql1);
// insert into "points" ("geom", "id") values
(ST_geomFromText('Point(0 0)'), '1')

So far I have tried

router.post('/', (req, res, next) => {
  queries.create(req.body).then(poi => {
    res.json(poi[0]);
  });
});

Insert query

  create(poi) {
    const sql = db.insert(poi).returning('*').into('poi');
    return sql;
  },

In Postman I am sending this in its body

{
    "place": "test",
    "comments": "new",
    "numbers": 6,
    "geom": "st.geomFromText('Point(-71.064544 44.28787)', 4326)"
}

But get an error "Unhandled rejection error: parse error - invalid geometry"
The hard coded object looks the same and is work fine.

I have a feeling that I am using the st.geomFromText wrong, but i dont I am not sure?

This is what i get if i console.log returned query

insert into "poi" ("comments", "geom", "numbers", "place") values ('new', 'st.geomFromText(''Point(-71.064544 44.28787)'', 4326)', 6, 'test')

(see how it does not change st.geom.. to st_geom..? Also the quotation marks around the ST function and the Point object is not right)

This  string work when I run it in pgAdmin

insert into "poi" ("comments", "geom", "numbers", "place") values ('new', st_GeomFromText('Point(-71.064544 44.28787)', 4326), 6, 'test')

EDIT:
I console.log the hardcoded version too. It does no appear to add the extra '' on the geometry value

insert into "poi" ("geom") values (ST_geomFromText('Point(-71.064544 44.28787)', 4326))

Any advice?

Body:
You pass coordinates from postman as string value in JSON object

"geom": "st.geomFromText('Point(-71.064544 44.28787)', 4326)"

And expect your code to transform it into a function call

st.geomFromText('Point(-71.064544 44.28787)', 4326)

What knex does in this case. It takes your string and convert it as it is string field (here you get a single quote ' replacement with double '' for Postgres to escape it).

What you can do. Pass your geometry to your API like this

"geom": "Point(-71.064544 44.28787)"

And in your route handler

create(poi) {
  const sql = db.insert({
    place: poi.place,
    comments: poi.comments,
    numbers: poi.numbers,
    geom: st.geomFromText(poi.geom, 4326)
  }).returning('*').into('poi');
  return sql;
},


问:
Ensure that a consumer group's offset is behind another group's
I have two services, A and B, processing stuff from a Kafka topic. However, B must not process stuff from the topic before A is done doing so. Is there any way to ensure that B's poll() will only return records that have been committed by A?

答:
Check out the details of doing transactions in Kafka >=0.11 : https://www.confluent.io/blog/transactions-apache-kafka/

But depending on what you're actually building, maybe having A produce back to another topic for B to consume (as @Abhimanyu suggests) may be the right option here.


问:
Gave up waiting for service error: during pax exam integration tests in opendaylight
I'm developing an app on Opendaylight using the startup archetype. I'm using the Carbon version and after running mvn install, I get this error during the pax exam integration tests:

org.ops4j.pax.swissbox.tracker.ServiceLookupException: gave up waiting for service org.opendaylight.controller.sal.binding.api.BindingAwareBroker

Can anyone help me with this error please?

答: That message just means that the MD SAL data store is not up and running. You need to look into the Karaf logs from the IT to understand why that is so - look around in the *Test-output.txt, *Test.txt and *Test.xml files in target/surefire-reports/ of your failing integration test artifact.


问:
Declaration or Definition in C
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

```<code>int i;
</code>```

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

```<code>                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.
</code>```

答:
Assuming it's at file scope it's a 'tentative definition'. From 6.9.2/2 "External object definitions":

A declaration of an identifier for an object that has file scope without an initializer, and
  without a storage-class specifier or with the storage-class specifier static, constitutes a
  tentative definition. If a translation unit contains one or more tentative definitions for an
  identifier, and the translation unit contains no external definition for that identifier, then
  the behavior is exactly as if the translation unit contains a file scope declaration of that
  identifier, with the composite type as of the end of the translation unit, with an initializer
  equal to 0.

This means that it would be valid to also have the following in the translation unit:

```<code>int i = 42;
</code>```

since that declaration has an explicit initializer, it's the definition of the variable i.

As far as if the declaration is in a block scope, the standard says the following (6.2.2/2 "Linkages of identifiers"):

Each declaration of an identifier with
  no linkage denotes a unique entity.

...

(paragraph 6)  The following
  identifiers have no linkage: ... a
  block scope identifier for an object
  declared without the storage-class
  specifier extern.

So in block scope, the declaration would be a definition as well.

Title: Declaration or Definition in C

Body:
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

int i;

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.

Body:
Assuming it's at file scope it's a 'tentative definition'. From 6.9.2/2 "External object definitions":

A declaration of an identifier for an object that has file scope without an initializer, and
  without a storage-class specifier or with the storage-class specifier static, constitutes a
  tentative definition. If a translation unit contains one or more tentative definitions for an
  identifier, and the translation unit contains no external definition for that identifier, then
  the behavior is exactly as if the translation unit contains a file scope declaration of that
  identifier, with the composite type as of the end of the translation unit, with an initializer
  equal to 0.

This means that it would be valid to also have the following in the translation unit:

int i = 42;

since that declaration has an explicit initializer, it's the definition of the variable i.

As far as if the declaration is in a block scope, the standard says the following (6.2.2/2 "Linkages of identifiers"):

Each declaration of an identifier with
  no linkage denotes a unique entity.

...

(paragraph 6)  The following
  identifiers have no linkage: ... a
  block scope identifier for an object
  declared without the storage-class
  specifier extern.

So in block scope, the declaration would be a definition as well.


问:
TensorFlow Object Detection API: evaluation mAP behaves weirdly?
I am training an object detector for my own data using Tensorflow Object Detection API. I am following the (great) tutorial by Dat Tran https://towardsdatascience.com/how-to-train-your-own-object-detector-with-tensorflows-object-detector-api-bec72ecfe1d9. I am using the provided ssd_mobilenet_v1_coco-model pre-trained model checkpoint as the starting point for the training. I have only one object class.

I exported the trained model, ran it on the evaluation data and looked at the resulted bounding boxes. The trained model worked nicely; I would say that if there was 20 objects, typically there were 13 objects with spot on predicted bounding boxes ("true positives");  7 where the objects were not detected ("false negatives"); 2 cases where problems occur were two or more objects are close to each other: the bounding boxes get drawn between the objects in some of these cases ("false positives"<-of course, calling these "false positives" etc. is inaccurate, but this is just for me to understand the concept of precision here). There are almost no other "false positives". This seems much better result than what I was hoping to get, and while this kind of visual inspection does not give the actual mAP (which is calculated based on overlap of the predicted and tagged bounding boxes?), I would roughly estimate the mAP as something like 13/(13+2) >80%.

However, when I run the evaluation (eval.py) (on two different evaluation sets), I get the following mAP graph (0.7 smoothed):
mAP during training

This would indicate a huge variation in mAP, and level of about 0.3 at the end of the training, which is way worse than what I would assume based on how well the boundary boxes are drawn when I use the exported output_inference_graph.pb on the evaluation set.

Here is the total loss graph for the training:
total loss during training

My training data consist of 200 images with about 20 labeled objects each (I labeled them using the labelImg app); the images are extracted from a video and the objects are small and kind of blurry. The original image size is 1200x900, so I reduced it to 600x450 for the training data. Evaluation data (which I used both as the evaluation data set for eval.pyand to visually check what the predictions look like) is similar, consists of 50 images with 20 object each, but is still in the original size (the training data is extracted from the first 30 min of the video and evaluation data from the last 30 min).

Question 1: Why is the mAP so low in evaluation when the model appears to work so well? Is it normal for the mAP graph fluctuate so much? I did not touch the default values for how many images the tensorboard uses to draw the graph (I read this question: Tensorflow object detection api validation data size and have some vague idea that there is some default value that can be changed?)

Question 2: Can this be related to different size of the training data and the evaluation data (1200x700 vs 600x450)? If so, should I resize the evaluation data, too? (I did not want to do this as my application uses the original image  size, and I want to evaluate how well the model does on that data).

Question 3: Is it a problem to form the training and evaluation data from images where there are multiple tagged objects per image (i.e. surely the evaluation routine compares all the predicted bounding boxes in one image to all the tagged bounding boxes in one image, and not all the predicted boxes in one image to one tagged box which would preduce many "false false positives"?)

(Question 4: it seems to me the model training could have been stopped after around 10000 timesteps were the mAP kind of leveled out, is it now overtrained? it's kind of hard to tell when it fluctuates so much.)

I am a newbie with object detection so I very much appreciate any insight anyone can offer! :)

答:
Question 1: This is the tough one... First, I think you don't understand correctly what mAP is, since your rough calculation is false. Here is, briefly, how it is computed:

For each class of object, using the overlap between the real objects and the detected ones, the detections are tagged as "True positive" or "False positive"; all the real objects with no "True positive" associated to them are labelled "False Negative".

Then, iterate through all your detections (on all images of the dataset) in decreasing order of confidence. Compute the accuracy (TP/(TP+FP)) and recall (TP/(TP+FN)), only counting the detections that you've already seen ( with confidence bigger than the current one) for TP and FP. This gives you a point (acc, recc), that you can put on a precision-recall graph.

Once you've added all possible points to your graph, you compute the area under the curve: this is the Average Precision for this category

if you have multiple categories, the mAP is the standard mean of all APs.

Applying that to your case: in the best case your true positive are the detections with the best confidence. In that case your acc/rec curve will look like a rectangle: you'd have 100% accuracy up to (13/20) recall, and then points with 13/20 recall and <100% accuracy; this gives you mAP=AP(category 1)=13/20=0.65. And this is the best case, you can expect less in practice due to false positives which higher confidence.

Other reasons why yours could be lower:

maybe among the bounding boxes that appear to be good, some are still rejected in the calculations because the overlap between the detection and the real object is not quite big enough. The criterion is that Intersection over Union (IoU) of the two bounding boxes (real one and detection) should be over 0.5. While it seems like a gentle threshold, it's not really; you should probably try and write a script to display the detected bounding boxes with a different color depending on whether they're accepted or not (if not, you'll get both a FP and a FN).

maybe you're only visualizing the first 10 images of the evaluation. If so, change that, for 2 reasons: 1. maybe you're just very lucky on these images, and they're not representative of what follows, just by luck. 2. Actually, more than luck, if these images are the first from the evaluation set, they come right after the end of the training set in your video, so they are probably quite similar to some images in the training set, so they are easier to predict, so they're not representative of your evaluation set.

Question 2: if you have not changed that part in the config file mobilenet_v1_coco-model, all your images (both for training and testing) are rescaled to 300x300 pixels at the start of the network, so your preprocessings don't matter.

Question 3: no it's not a problem at all, all these algorithms were designed to detect multiple objects in images.

Question 4: Given the fluctuations, I'd actually keep training it until you can see improvement or clear overtraining. 10k steps is actually quite small, maybe it's enough because your task is relatively easy, maybe it's not enough and you need to wait ten times that to have significant improvement...


问:
Using endorsements in Hyperledger Fabric to design a process
I would really like to understand how endorsments work in Hyperledger Fabric in order to help me in designing a solution to a problem.

let's assume I am an endorser and a transaction proposal has just arrived. I would randomly select a participant within my organization, use its identity to perform the validations, checking for replay attacks etc then sign an endorsement with that participant's private key. Assuming I used an admin's credentials, the admin(person) may not be aware that I used its identities to validate and endorse a transaction proposal. Is this example correct?

Initial discussions here makes me feel like the more I look into it, the more confused I become. Could anyone help?

答:
Just to start with, the endorser is the peer that capable to handle incoming invocation, maintain and run the chaincode. The flow works as following, support you have a client (C) and the endorsing peer (P), which runs a chaincode (CC).

Client forms transaction proposal request which includes parameters for chaincode invocation.

In order to get an endorsement for this proposal he sends it the endorsing peer.

Endorsing peer opens a transaction proposal and forwards requests to the required chaincode along the way it passes all parameters.

Chaincode get invoked which produces a RWset (set of keys and values read of changed during the invocation)

Peer collects RWset and forms proposal response and signs it

Client gets the proposal response, signs it as well and send it to the ordering service

Ordering service collects proposal responses and cuts the block which got distributed to the peers in the network.

Upon arrival peers opens a block and validates all transactions, one of the validation is to check whenever transaction conforms the endorsement policy, where basically it checks whenever transaction has enough signatures which satisfies the policy.

Back to your question, please note that at each step everyone uses its own key and certificate to sign, no one randomly selects participants to use they identities for signatures or whatever else.

PS. Note that process above a bit simplified and lack a lot of technical details.

PPS. There is a new course on Coursera which covers pretty well many technical aspects of Hyperledger Fabric architecture and the interaction between different components, I would urge you to consider taking this course.


问:
Call subclass constructor from parent in Java
so I'm learning about java inheritance and I just ran into a situation I don't know how to solve.

What I'm trying to do is to call a subclass constructor from the superclass. I don't know if this makes any sense, but I'll try to explain myself with an example.

```<code>public class Phone {
    private String brand;
    private int weight;

    public Phone(String brand, int weight) {
        this.brand = brand;
        this.weight = weight;
    }

    public Phone(String brand, int weight, String tech) {
        // Here it is where I'm stuck
        // Call SmartPhone constructor with all the parameters
    }
}
</code>```

```<code>public class SmartPhone extends Phone {
    private String tech;

    public SmartPhone(String Brand, int weight, String tech) {
        super(brand, weight);
        this.tech = tech;
    }
}
</code>```

Why would I want to do that?

I would like to be able to not have to deal with SmartPhone in the main.

I'd like to be able to do:

```<code>Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance
</code>```

答: You could use a private constructor, and instantiate a SmartPhone() object from within the Phone() constructor with three parameters.

Body:
so I'm learning about java inheritance and I just ran into a situation I don't know how to solve.

What I'm trying to do is to call a subclass constructor from the superclass. I don't know if this makes any sense, but I'll try to explain myself with an example.

public class Phone {
    private String brand;
    private int weight;

    public Phone(String brand, int weight) {
        this.brand = brand;
        this.weight = weight;
    }

    public Phone(String brand, int weight, String tech) {
        // Here it is where I'm stuck
        // Call SmartPhone constructor with all the parameters
    }
}

public class SmartPhone extends Phone {
    private String tech;

    public SmartPhone(String Brand, int weight, String tech) {
        super(brand, weight);
        this.tech = tech;
    }
}

Why would I want to do that?

I would like to be able to not have to deal with SmartPhone in the main.

I'd like to be able to do:

Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance


问:
How to Auto Submit form using PHP
I am currently developing a website where I am facing the following problem:

I tried passing the User id and password to the login page and auto submit the page using a script, which will take the user to the next page. This is just to bypass the login page in my site. This works perfectly fine.

When the "No script" add on is enabled on a Mozilla Firefox browser, the script to auto submit the form is not working. As a result, the login page is getting displayed to the user with the filled in user id and password.

Also, sometimes the user is able to see the login page on the front end when we auto submit the login page.

Are there any possible ways to overcome these two issues?

答:
Redirecting the user's browser as you are doing now is really only possible client side with Javascript, which is always able to be blocked. You could store the user_id and password in a session variable and access that data on your login page which handle's the actual authentication. Doing it that way would eliminate the need for auto submitting forms.

But if you really want to use form posting you can emulate a form post with PHP using cURL, but this is a little more complicated.

cURL on php.net

Sending post form data with PHP and cURL

On my site, if the user is not logged in I run a "tryCookieAuthentication" method on every page load which checks to see if the "remember me" cookie is set. If it's set and everything seems legitimate, I go ahead and authenticate the user and log him in. This way the user doesn't even have to touch the login page. I don't know if this is what you're trying to do, but it might give you an idea.

Title: How to Auto Submit form using PHP


问:
Batch: Read out number, iterate and write back
I want a text file with just a number that is getting iterated every time i use the batch file. I tried this so far but its not working...</p>

```<code>set laufende_nr=0
if not exist echo %laufende_nr% > %def_log_dir%\laufende_nr.tmp
for /L %%i in (%def_log_dir%\laufende_nr.tmp) set laufende_nr=%%i
echo %laufende_nr%
set /a laufende_nr+=laufende_nr
echo %laufende_nr_neu% > %def_log_dir%\laufende_nr.tmp
</code>```

答:
Here's some quick example code for you to study:

Set "laufende_nr="
If Exist "%def_log_dir%\laufende_nr.tmp" (
    Set/P "laufende_nr="<"%def_log_dir%\laufende_nr.tmp"
)
If Not Defined laufende_nr Set "laufende_nr=0"
Echo %laufende_nr%
Set/A laufende_nr+=1
(Echo %laufende_nr%)>"%def_log_dir%\laufende_nr.tmp"
```

Enter Set/?, If/? & Echo/? as necessary for respective information.

Edit
If you have a relative directory named Set which contains an executable file named either A or P, then you would be best advised to change Set/A to Set /A and/or change Set/P to Set /P as necessary.

Body:
I want a text file with just a number that is getting iterated every time i use the batch file. I tried this so far but its not working...

set laufende_nr=0
if not exist echo %laufende_nr% > %def_log_dir%\laufende_nr.tmp
for /L %%i in (%def_log_dir%\laufende_nr.tmp) set laufende_nr=%%i
echo %laufende_nr%
set /a laufende_nr+=laufende_nr
echo %laufende_nr_neu% > %def_log_dir%\laufende_nr.tmp

Body:
Here's some quick example code for you to study:

Set "laufende_nr="
If Exist "%def_log_dir%\laufende_nr.tmp" (
    Set/P "laufende_nr="<"%def_log_dir%\laufende_nr.tmp"
)
If Not Defined laufende_nr Set "laufende_nr=0"
Echo %laufende_nr%
Set/A laufende_nr+=1
(Echo %laufende_nr%)>"%def_log_dir%\laufende_nr.tmp"

Enter Set/?, If/? & Echo/? as necessary for respective information.

Edit
If you have a relative directory named Set which contains an executable file named either A or P, then you would be best advised to change Set/A to Set /A and/or change Set/P to Set /P as necessary.


问:
How to identify a unix timestamp from a date?
Any ideas how I can make a simple IF-statement that sort 31-10-2017 or 12-01-2016 from 1511431687?

I am converting from a set date, to use unix timestamp, and need a solution to sort out what is what. I want to display the date in human readable format (days/ month/year).

So I have a $data that is inside a loop. It pulls the date from a flat file. The old stuff has just saved the date as a date. For instance 31-10-2017 (exactly like that).

Now I use unix timestamp. For instance 1511431687.

I see people have used a simple IF-statement, but I can not use it as both are 10 units long. Else that would have worked well.

```<code>$data = // either a timestamp, or a date in this format: 31-10-2017

if (strlen($data) === 10) // it's a timestamp
$data =  date("d-m-Y H:i:s", $data);
</code>```

答:
You have several options:

ctype_digit to check whether the string is all digits (probably a UNIX timestamp)

preg_match('/^\d{1,2}-\d{1,2}-\d{4}$/', $date) (either a d-m-Y or m-d-Y date)

checkdate to confirm whether a date you think you've identified is valid

Depending on how many different formats you expect, I'd try in this logical order:

if ctype_digit, check if value is in expected range

if outside expected range, try dividing by 1000 (timestamps in milliseconds)

otherwise, try matching with a regex in whatever formats you expect

confirm with checkdate that the values are sensible

finally convert to DateTime object as standardised internal representation

Body:
Any ideas how I can make a simple IF-statement that sort 31-10-2017 or 12-01-2016 from 1511431687?

I am converting from a set date, to use unix timestamp, and need a solution to sort out what is what. I want to display the date in human readable format (days/ month/year).

So I have a $data that is inside a loop. It pulls the date from a flat file. The old stuff has just saved the date as a date. For instance 31-10-2017 (exactly like that).

Now I use unix timestamp. For instance 1511431687.

I see people have used a simple IF-statement, but I can not use it as both are 10 units long. Else that would have worked well.

$data = // either a timestamp, or a date in this format: 31-10-2017

if (strlen($data) === 10) // it's a timestamp
$data =  date("d-m-Y H:i:s", $data);


问:
TextToColumns without result being evaluated
I have a csv with a "|"-delimeter, so I open the workbook:

```<code>Set wb = Workbooks.Open(xl_newest_export)
Set ws = wb.Sheets(1)
</code>```

and use texttocolumns:

```<code>   ws.Range("A1:A" & CStr(lastRow)).TextToColumns Destination:=Range("A1:A" & CStr(lastRow)), DataType:=xlDelimited, _
        TextQualifier:=xlNone, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, DecimalSeparator:=".", Other:=True, OtherChar _
        :="|"
</code>```

However this fails as the text gets evaluated by Excel - a few doubles are getting converted to date. e.g.
"1" -> "01.01.1900"

How can I achieve the above with no Evaluation?

Edit:
As suggested in the comments - Fieldinfo is the solution. However I tried to build a Array-string... e.g. "Array(Array(3,1)...)" but this fails too..

答:
Once you have filled column A with data, use this instead:

```<code>Sub PiedPipper()
    Dim rng As Range, r As Range, pipe As String

    Cells.NumberFormat = "@"
    Set rng = Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
    pipe = "|"
    For Each r In rng
        ary = Split(r.Value, pipe)
        r.Resize(1, UBound(ary) + 1) = ary
    Next r
End Sub
</code>```

EDIT#1:

Use this to get the .csv data into column A:

```<code>Sub GetCVSData()
   Dim FilesToOpen
   Dim wf As WorksheetFunction
   Set wf = Application.WorksheetFunction
   Dim ary, bry, DQ As String
   DQ = Chr(34)

   FilesToOpen = Application.GetOpenFilename _
      (FileFilter:="Text Files (*.csv), *.csv", Title:="Text Files to Open")

   Close #1
   Open FilesToOpen For Input As #1

   j = 1
   Do While Not EOF(1)
      Line Input #1, TextLine
      With Cells(j, 1)
        .NumberFormat = "@"
        .Value = TextLine
    End With
      j = j + 1
   Loop

   Close #1
End Sub
</code>```

Body:
I have a csv with a "|"-delimeter, so I open the workbook:

Set wb = Workbooks.Open(xl_newest_export)
Set ws = wb.Sheets(1)

and use texttocolumns:

   ws.Range("A1:A" & CStr(lastRow)).TextToColumns Destination:=Range("A1:A" & CStr(lastRow)), DataType:=xlDelimited, _
        TextQualifier:=xlNone, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, DecimalSeparator:=".", Other:=True, OtherChar _
        :="|"

However this fails as the text gets evaluated by Excel - a few doubles are getting converted to date. e.g.
"1" -> "01.01.1900"

How can I achieve the above with no Evaluation?

Edit:
As suggested in the comments - Fieldinfo is the solution. However I tried to build a Array-string... e.g. "Array(Array(3,1)...)" but this fails too..

Body:
Once you have filled column A with data, use this instead:

Sub PiedPipper()
    Dim rng As Range, r As Range, pipe As String

    Cells.NumberFormat = "@"
    Set rng = Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
    pipe = "|"
    For Each r In rng
        ary = Split(r.Value, pipe)
        r.Resize(1, UBound(ary) + 1) = ary
    Next r
End Sub

EDIT#1:

Use this to get the .csv data into column A:

Sub GetCVSData()
   Dim FilesToOpen
   Dim wf As WorksheetFunction
   Set wf = Application.WorksheetFunction
   Dim ary, bry, DQ As String
   DQ = Chr(34)

   FilesToOpen = Application.GetOpenFilename _
      (FileFilter:="Text Files (*.csv), *.csv", Title:="Text Files to Open")

   Close #1
   Open FilesToOpen For Input As #1

   j = 1
   Do While Not EOF(1)
      Line Input #1, TextLine
      With Cells(j, 1)
        .NumberFormat = "@"
        .Value = TextLine
    End With
      j = j + 1
   Loop

   Close #1
End Sub


问:
error C2514: 'BLOCK' : CLASS HAS NO CONSTRUCTOR
I get the error error C2514: 'BLOCK' : CLASS HAS NO CONSTRUCTOR  with a simple class like this:

BLOCK.h

```<code>#pragma once
#include "helpful.h"

class WORLD;

class BLOCK
{
    public:
        short int type;

        void Render();

        BLOCK();
        ~BLOCK(void);
};
</code>```

BLOCK.cpp

```<code>#include "BLOCK.h"
#include "WORLD.h"

BLOCK::BLOCK(void)
{
}
void BLOCK::Render()
{
}
BLOCK::~BLOCK(void)
{
}
</code>```

But the BLOCK class is defined, no?

答: You need to look for it in MYCLASS

Body:
I get the error error C2514: 'BLOCK' : CLASS HAS NO CONSTRUCTOR  with a simple class like this:

BLOCK.h

#pragma once
#include "helpful.h"

class WORLD;

class BLOCK
{
    public:
        short int type;

        void Render();

        BLOCK();
        ~BLOCK(void);
};

BLOCK.cpp

#include "BLOCK.h"
#include "WORLD.h"

BLOCK::BLOCK(void)
{
}
void BLOCK::Render()
{
}
BLOCK::~BLOCK(void)
{
}

But the BLOCK class is defined, no?

Body: You need to look for it in MYCLASS


问:
I can't use new in C++ function to build

I want to new a space for a argument in this function.
</p>

```<code>void Binary::PreAndMid(Qnode* root, char temp1[], char temp2[], int m, int n, int j, int k) {
    if (n - m != k - j || m > n || j > k) {
        return;
    }
    else {
        root = new Qnode;  /*in other function the root is become null*/
        root->val = temp1[m];
        cout << root->val << endl;
        int f = Find(temp2, temp1[m]);
        if (f == -1) {
            return;
        }
        else {
            PreAndMid(root->LC, temp1, temp2, m + 1, m + f - j, j, f - 1);
            PreAndMid(root->RC, temp1, temp2, m + f - j + 1, n, f + 1, k);
        }
    }
}
</code>```

<p>
The result is that the root is null.
</p>

答: This is because you need to do *& root so that the new memory address is returned at the end. Right now you are breaking the rule never use assignment operator on parameter.

Body:
I want to new a space for a argument in this function.

void Binary::PreAndMid(Qnode* root, char temp1[], char temp2[], int m, int n, int j, int k) {
    if (n - m != k - j || m > n || j > k) {
        return;
    }
    else {
        root = new Qnode;  /*in other function the root is become null*/
        root->val = temp1[m];
        cout << root->val << endl;
        int f = Find(temp2, temp1[m]);
        if (f == -1) {
            return;
        }
        else {
            PreAndMid(root->LC, temp1, temp2, m + 1, m + f - j, j, f - 1);
            PreAndMid(root->RC, temp1, temp2, m + f - j + 1, n, f + 1, k);
        }
    }
}

The result is that the root is null.