问:
ionic android back button navigation to previous page not working
I am trying to add back button navigation in ionic1 app, I have registered the
back button in .run(function($ionicPlatform) by adding code

```<code>$ionicPlatform.registerBackButtonAction(function (event) {
      event.preventDefault(); // Back button will DO NOTHING.
      //alert("Going back!!!");
    }, 100);
</code>```

and it prevents android back button to close the app but I am unable to go to previous page. SO far I have tried

```<code>$ionicHistory.goBack();
</code>```

and

```<code>$state.go('menu.home');
</code>```

but they dont work. How can I call previous page everytime back button is pressed ?

Here are some of the states from routes.js:

```<code>angular.module('app.routes', [])

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider

      .state('menu.home', {
    url: '/page1',
    views: {
      'side-menu21': {
        templateUrl: 'templates/home.html',
        controller: 'homeCtrl'
      }
    }
  })

  .state('menu', {
    url: '/side-menu21',
    templateUrl: 'templates/menu.html',
    controller: 'menuCtrl'
  })

  .state('menu.policySummaries', {
    url: '/page4',
    views: {
      'side-menu21': {
        templateUrl: 'templates/policySummaries.html',
        controller: 'policySummariesCtrl'
      }
    }
  })
$urlRouterProvider.otherwise('/side-menu21/page1')

});
</code>```

答:
This works just make sure to inject $state and $ionicPopup in .run function:</p>

```<code>$ionicPlatform.registerBackButtonAction(function (event) {
      if ($state.current.name == "menu.hPCompliance") {
        var confirmPopup = $ionicPopup.confirm({
          title: 'Exit',
          template: 'Are you sure you want to close the app?',
          okText: "Yes",
          okType: "button-positive",
          cancelText: "No",
          cancelType: "button-assertive"
        });
        confirmPopup.then(function (res) {
          if (res) {
            navigator.app.exitApp();
          } else {
            console.log('Cancel');
          }
        });
      }
      else {
        window.history.back();
      }
</code>```

Body:
I am trying to add back button navigation in ionic1 app, I have registered the
back button in .run(function($ionicPlatform) by adding code

$ionicPlatform.registerBackButtonAction(function (event) {
      event.preventDefault(); // Back button will DO NOTHING.
      //alert("Going back!!!");
    }, 100);

and it prevents android back button to close the app but I am unable to go to previous page. SO far I have tried

$ionicHistory.goBack();

and

$state.go('menu.home');

but they dont work. How can I call previous page everytime back button is pressed ?

Here are some of the states from routes.js:

angular.module('app.routes', [])

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider

      .state('menu.home', {
    url: '/page1',
    views: {
      'side-menu21': {
        templateUrl: 'templates/home.html',
        controller: 'homeCtrl'
      }
    }
  })

  .state('menu', {
    url: '/side-menu21',
    templateUrl: 'templates/menu.html',
    controller: 'menuCtrl'
  })

  .state('menu.policySummaries', {
    url: '/page4',
    views: {
      'side-menu21': {
        templateUrl: 'templates/policySummaries.html',
        controller: 'policySummariesCtrl'
      }
    }
  })
$urlRouterProvider.otherwise('/side-menu21/page1')

});

Body:
This works just make sure to inject $state and $ionicPopup in .run function:

$ionicPlatform.registerBackButtonAction(function (event) {
      if ($state.current.name == "menu.hPCompliance") {
        var confirmPopup = $ionicPopup.confirm({
          title: 'Exit',
          template: 'Are you sure you want to close the app?',
          okText: "Yes",
          okType: "button-positive",
          cancelText: "No",
          cancelType: "button-assertive"
        });
        confirmPopup.then(function (res) {
          if (res) {
            navigator.app.exitApp();
          } else {
            console.log('Cancel');
          }
        });
      }
      else {
        window.history.back();
      }


来源: stackexchange

问:
Extract Json response Create dynamic variables and assign values
I want to extract values from a json response and assign the values to variables and use them in subsequent requests.

Request 1 Response

```<code>{
  "XXX":"Test Company 1",
  "YYY":"Test Company 2",
  "ZZZ":"Test Company 3"
}
</code>```

I want to create dynamic variables and values like below.

```<code>Company_Name_1 = "Test Company 1"
Company_Code_1 = "XXX"
Company_Name_2 = "Test Company 2"
Company_Code_2 = "YYY"
Company_Name_3 = "Test Company 3"
Company_Code_3 = "ZZZ"
</code>```

and use above variables in subsequent requests like below.

Request 2 Parameter

```<code>{
    "Date": "${MeetingDate}",
    "StartTime": "${StartTime}",
    "EndTime": "${EndTime}",
    "InvestorsByDate": [{
        "Name": "${Company_Name_1}",
        "Code": "${Company_Code_1}"
    },
    {
        "Name": "${Company_Name_2}",
        "Code": "${Company_Code_2}"
    },
    {
        "Name": "${Company_Name_3}",
        "Code": "${Company_Code_3}"
    }]
}
</code>```

Total number of companies is not a constant, its changing continuously. So i need to write a code to capture the dynamic values and assign them to dynamically created variables then use them in subsequent requests. I am totally new to scripting. Please help me to face this challenge. Your help is really appreciated.

答:
Add JSR223 PostProcesor as a child of the first request

Make sure you have groovy as a language and tick Cache compiled script if available box

Put the following code into "Script" area:

```<code>import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def companies = new JsonSlurper().parse(prev.getResponseData())
def jsonBuilder = new JsonBuilder()
jsonBuilder {
    "Date"   vars.get('MeetingDate')
    "StartTime" vars.get('StartTime')
    "EndTime" vars.get('EndTime')
    "InvestorsByDate" companies.collect {
        [
            Name: it.getValue(),
            Code: it.getKey()
        ]
    }
}
vars.put('requestBody', jsonBuilder.toPrettyString())
log.info('Generated body: ' + vars.get('requestBody'))
</code>```

You will be able to refer the generated JSON Payload as ${requestBody} or ${__V(requestBody)} where required

Demo:

References:

Groovy - Parsing and producing JSON

JsonBuilder documentation

Apache Groovy - Why and How You Should Use It

ContentLicense: CC BY-SA 3.0

Body:
I want to extract values from a json response and assign the values to variables and use them in subsequent requests.

Request 1 Response

{
  "XXX":"Test Company 1",
  "YYY":"Test Company 2",
  "ZZZ":"Test Company 3"
}

I want to create dynamic variables and values like below.

Company_Name_1 = "Test Company 1"
Company_Code_1 = "XXX"
Company_Name_2 = "Test Company 2"
Company_Code_2 = "YYY"
Company_Name_3 = "Test Company 3"
Company_Code_3 = "ZZZ"

and use above variables in subsequent requests like below.

Request 2 Parameter

{
    "Date": "${MeetingDate}",
    "StartTime": "${StartTime}",
    "EndTime": "${EndTime}",
    "InvestorsByDate": [{
        "Name": "${Company_Name_1}",
        "Code": "${Company_Code_1}"
    },
    {
        "Name": "${Company_Name_2}",
        "Code": "${Company_Code_2}"
    },
    {
        "Name": "${Company_Name_3}",
        "Code": "${Company_Code_3}"
    }]
}

Total number of companies is not a constant, its changing continuously. So i need to write a code to capture the dynamic values and assign them to dynamically created variables then use them in subsequent requests. I am totally new to scripting. Please help me to face this challenge. Your help is really appreciated.

Body:
Add JSR223 PostProcesor as a child of the first request

Make sure you have groovy as a language and tick Cache compiled script if available box

Put the following code into "Script" area:

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def companies = new JsonSlurper().parse(prev.getResponseData())
def jsonBuilder = new JsonBuilder()
jsonBuilder {
    "Date"   vars.get('MeetingDate')
    "StartTime" vars.get('StartTime')
    "EndTime" vars.get('EndTime')
    "InvestorsByDate" companies.collect {
        [
            Name: it.getValue(),
            Code: it.getKey()
        ]
    }
}
vars.put('requestBody', jsonBuilder.toPrettyString())
log.info('Generated body: ' + vars.get('requestBody'))

You will be able to refer the generated JSON Payload as ${requestBody} or ${__V(requestBody)} where required

Demo:

References:

Groovy - Parsing and producing JSON

JsonBuilder documentation

Apache Groovy - Why and How You Should Use It


问:
What happens with iphone google analytics calls when there's no internet connection?
Hey Fellow  Developers!
I'm doing a little research about Analytics products for iphone apps. I came across google analytics which seems pretty good. Somehow I'm not finding lot's of documentation about it. Basically my concern is:

What happens to a trackPageview or event tracking call when there's no Internet connection?
Are these method calls persisted for future dispatch when there's a connection available or do they generate an error and that's it?

Thank you in advance for your help!

答:
Some of the other services out there are very robust with their batching. Localytics (www.localytics.com) has a free library which is open source so you can see how they batch. If the connection isn't available then the data is stored on the device until the next session when there is a connection.

-- Henry

ContentLicense: CC BY-SA 2.5


问:
How to split string then compare it to fill id's in relation?
I have 2 Tables:

Molecule containing :

-id

-MainName (ex: caffeine)

JsonTextMining containing :

-id

-solrId (ex: PMC54233)

-MoleculeName (ex: caffeine | aspirin | sugar )

They are ManyToMany relation so there is a third table jsonTextMiningMolecule that have:

-json_text_mining_id

-molecule_id

I want to find a postgresql command that can split the moleculeName string and then compare with mainName to attribute id's in jsonTextMiningMolecule

For the moment i got something like this :

edit:

```<code>update json_text_mining_molecule SET molecule_id = molecule.id
FROM molecule, json_text_mining
WHERE split_part(json_text_mining.molecule_name, ' | ', 2 ) = molecule.main_name
</code>```

The result of this command is update 0 (perhap's because i have non null constraint on json_text_mining_id) and split_part don't work as he need to choose one part of the string

答:
Try looking into split_part command.

https://www.postgresql.org/docs/9.1/static/functions-string.html

You can find many other string operations in there!

EDIT:

 Try regexp_split_to_array with IN clause

Body:
I have 2 Tables:

Molecule containing :

-id

-MainName (ex: caffeine)

JsonTextMining containing :

-id

-solrId (ex: PMC54233)

-MoleculeName (ex: caffeine | aspirin | sugar )

They are ManyToMany relation so there is a third table jsonTextMiningMolecule that have:

-json_text_mining_id

-molecule_id

I want to find a postgresql command that can split the moleculeName string and then compare with mainName to attribute id's in jsonTextMiningMolecule

For the moment i got something like this :

edit:

update json_text_mining_molecule SET molecule_id = molecule.id
FROM molecule, json_text_mining
WHERE split_part(json_text_mining.molecule_name, ' | ', 2 ) = molecule.main_name

The result of this command is update 0 (perhap's because i have non null constraint on json_text_mining_id) and split_part don't work as he need to choose one part of the string


问:
using sed to search and replace the first word(string is divide by whitespace) in a string
An input string: "a-random_name /this/is/a/path_to-file 0"

An output string: "arandomname /this/is/a/path_to-file 0"

using sed only replace the first word. word is a random string.

Body:
With GNU sed:

sed ':a;s/^\([^-_ ]*\)[-_]/\1/;ta;' file


问:
Sort a list with a higher value
Good morning, I would like to create a list of content by ordering them from the most visited one.

I have a table called "post", formed by these different fields:

ID

TITLE

VIEWS

I would therefore like the content list to be shown from the post with the largest views.
I did this:

```<code>$pdo->query('SELECT * FROM post ORDER BY views DESC');
</code>```

But unfortunately it does not work properly, and I do not understand why. It sounds casual, sometimes it shows at the top of the post with fewer views than others, let's say everything randomly, otherwise it's correct. Something wrong?

答:
If your views field is a varchar and you want to sort the values as a number so use ABS of MySQL

```<code>$pdo->query('SELECT * FROM post ORDER BY ABS(views) DESC');
</code>```

Title: Sort a list with a higher value

Body:
Good morning, I would like to create a list of content by ordering them from the most visited one.

I have a table called "post", formed by these different fields:

ID

TITLE

VIEWS

I would therefore like the content list to be shown from the post with the largest views.
I did this:

$pdo->query('SELECT * FROM post ORDER BY views DESC');

But unfortunately it does not work properly, and I do not understand why. It sounds casual, sometimes it shows at the top of the post with fewer views than others, let's say everything randomly, otherwise it's correct. Something wrong?

Body:
If your views field is a varchar and you want to sort the values as a number so use ABS of MySQL

$pdo->query('SELECT * FROM post ORDER BY ABS(views) DESC');


问:
Apply order by on a joining table field in eloquent
I have a query which joins one table with another one in a one to one relation. How can I sort the result by a column in the joining relation

```<code>$relation = ModelObject::where('status', '=', 1)
                            ->with('related_table')
                            ->get()
</code>```

I need to sort this with a column(Eg: name) of related_table. How to do this in eloquent.

答:
As per the laravel docs you can add additional constraints like this,

Constraining Eager Loads

Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here's an example:

```<code>$users = App\User::with(['posts' => function ($query) {
    $query->where('title', 'like', '%first%');
}])->get();
</code>```

Finally your code should be something like this,

```<code>$relation = ModelObject::where('status', '=', 1)
->with(['related_table' => function($query) {
        $query->orderBy('field', 'asc|desc');
}])
->get()
</code>```

Body:
I have a query which joins one table with another one in a one to one relation. How can I sort the result by a column in the joining relation

$relation = ModelObject::where('status', '=', 1)
                            ->with('related_table')
                            ->get()

I need to sort this with a column(Eg: name) of related_table. How to do this in eloquent.

Body:
As per the laravel docs you can add additional constraints like this,

Constraining Eager Loads

Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here's an example:

$users = App\User::with(['posts' => function ($query) {
    $query->where('title', 'like', '%first%');
}])->get();

Finally your code should be something like this,

$relation = ModelObject::where('status', '=', 1)
->with(['related_table' => function($query) {
        $query->orderBy('field', 'asc|desc');
}])
->get()

ContentLicense: CC BY-SA 4.0


问:
Trying to stop removing `div` if it's length at `0` or `1`. can someone help me?
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="div">Div one</div>
  <div class="div">Div Two</div>
  <div class="div">Div Three</div>
  <div class="div">Div Four</div>
</div>

<div class="mainLength">
</div></code>```

答:
You must check your condition before removing divs and if length not 1, remove it and decrease divLength variable:

$(document).ready(function() {

  $('.div').click(function() {
    var divLength = $('.main div').length;

    if (divLength !== 1) {
      $(this).remove();
      divLength--;
    }
    $('.mainLength').text(divLength + " " + 'divs');

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="div">Div one</div>
  <div class="div">Div Two</div>
  <div class="div">Div Three</div>
  <div class="div">Div Four</div>
</div>

<div class="mainLength">
</div></code>```

Body:
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});

Div one

Div Two

Div Three

Div Four

Body:
You must check your condition before removing divs and if length not 1, remove it and decrease divLength variable:

$(document).ready(function() {

  $('.div').click(function() {
    var divLength = $('.main div').length;

    if (divLength !== 1) {
      $(this).remove();
      divLength--;
    }
    $('.mainLength').text(divLength + " " + 'divs');

  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="div">Div one</div>
  <div class="div">Div Two</div>
  <div class="div">Div Three</div>
  <div class="div">Div Four</div>
</div>

<div class="mainLength">
</div>


问:
html.textareafor - parse into an array of strings
I am in C# MVC (.NET) and have a form where I have input with @html.TextAreaFor
stored as a string
I am assuming that the data from this text box will store as a string, but what I am wondering is how will the string look, in terms of "/n" elements, will the string delimit new line markers?

Ideally, I need to parse the textbox line-by-line, where the string on each line becomes an element of a List
For example, if we have in the textbox

```<code>  item1
  item2
  item3
</code>```

Then when I submit the form, the model that I specified will be loaded with the string form the textbox, and using that string we will load up our List (somewhere else, in a different model..)with item1, item2, and item3.

答:
Suppose you have TextAreaFor bound to a model property named TextAreaModel which contains strings from user input like this:

```<code>@model ViewModel

@Html.TextAreaFor(m => m.TextAreaModel, new { ... })
</code>```

The proper way to extract lines from model property is splitting the string content using Environment.NewLine as delimiter in POST action method as shown in example below:

```<code>[HttpPost]
public ActionResult SubmitForm(ViewModel model)
{
    // other stuff

    // parse every textarea lines as list elements
    List<string> list = model.TextAreaModel.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

    // assign it to other list property on other model
    OtherModel.OtherList = list;

    // other stuff

    return View(model);
}
</code>```

NB: StringSplitOptions.RemoveEmptyEntries will remove empty lines found in source string, which I think this is more recommended way than using StringSplitOptions.None.

Demos:

.NET Fiddle Example - Splitting By Newline

.NET Fiddle Example - MVC Implementation

Related issue:

How to parse user input from a textarea line by line

Body:
I am in C# MVC (.NET) and have a form where I have input with @html.TextAreaFor
stored as a string
I am assuming that the data from this text box will store as a string, but what I am wondering is how will the string look, in terms of "/n" elements, will the string delimit new line markers?

Ideally, I need to parse the textbox line-by-line, where the string on each line becomes an element of a List
For example, if we have in the textbox

  item1
  item2
  item3

Then when I submit the form, the model that I specified will be loaded with the string form the textbox, and using that string we will load up our List (somewhere else, in a different model..)with item1, item2, and item3.

Body:
Suppose you have TextAreaFor bound to a model property named TextAreaModel which contains strings from user input like this:

@model ViewModel

@Html.TextAreaFor(m => m.TextAreaModel, new { ... })

The proper way to extract lines from model property is splitting the string content using Environment.NewLine as delimiter in POST action method as shown in example below:

[HttpPost]
public ActionResult SubmitForm(ViewModel model)
{
    // other stuff

    // parse every textarea lines as list elements
    List<string> list = model.TextAreaModel.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

    // assign it to other list property on other model
    OtherModel.OtherList = list;

    // other stuff

    return View(model);
}

NB: StringSplitOptions.RemoveEmptyEntries will remove empty lines found in source string, which I think this is more recommended way than using StringSplitOptions.None.

Demos:

.NET Fiddle Example - Splitting By Newline

.NET Fiddle Example - MVC Implementation

Related issue:

How to parse user input from a textarea line by line


问:
jQuery load with GET request
I have created a forum in my spare time and I wanted to add Ajax to it to pick up old knowledge. For a start I just wanted to add it to the thread page which displays the main thread post with the thread reply's (like a normal thread page of a forum) so when a user submitted a reply with the text area underneath the thread reply's, it would just reload the threads with the new reply.

My threads page has the url with the thread id to load from the database (threads_posts.php?threadID=1). How do I send the data (threadID=1) of the current URL to another page using the load function?

thread_posts.php

```<code><div id="content"></div>

<script>
$(document).ready(function() {
    $("#content").load("thread_posts_load.php");
})
</script>
</code>```

thread_posts_load.php

```<code><?php
$threadID = $_GET['threadID'];
?>
</code>```

答:
You can use jQuery ajax function like this

```<code>   $.ajax({
        url: 'thread_posts_load.php',
        type: 'GET',
        data: {threadID:'YOUR_ID'},
        success: function (data) {
             $("#content").html(data);
        }
    });
</code>```

Or load function like this

```<code>  var ID = "YOUR_ID";

  $("#content").load("thread_posts_load.php?threadID=" + ID);
</code>```

Title: jQuery load with GET request

Body:
I have created a forum in my spare time and I wanted to add Ajax to it to pick up old knowledge. For a start I just wanted to add it to the thread page which displays the main thread post with the thread reply's (like a normal thread page of a forum) so when a user submitted a reply with the text area underneath the thread reply's, it would just reload the threads with the new reply.

My threads page has the url with the thread id to load from the database (threads_posts.php?threadID=1). How do I send the data (threadID=1) of the current URL to another page using the load function?

thread_posts.php

thread_posts_load.php

<?php
$threadID = $_GET['threadID'];
?>

Body:
You can use jQuery ajax function like this

   $.ajax({
        url: 'thread_posts_load.php',
        type: 'GET',
        data: {threadID:'YOUR_ID'},
        success: function (data) {
             $("#content").html(data);
        }
    });

Or load function like this

  var ID = "YOUR_ID";

  $("#content").load("thread_posts_load.php?threadID=" + ID);


问:
Comparing two dates i javascript
I want to compare the picked date with the current date. But the if always falls thru to else. I read a couple of posts that the if will always return false because the two dates are two diffretnt object but contains the same time.
I tried getTime() but didnt get it to work either. What i want to achive in the end with this comparison is I want to restrict date input after 09:30 in the morning (24h) if the picked date is today. Is this the right way to go? To filter out the date first and then the time of day? Appriciate all the help I can get! I couldnt get the JSFiddle to work. wanted to give a live sample.

```<code>  $('#startDatePicker').datepicker({

  var fromDate = $('#startDatePicker').datepicker('getDate');
  var today = new Date();
  today.setHours(0, 0, 0, 0).getTime();
  selectedDate.setHours(0, 0, 0, 0).getTime();

  if (today === fromDate ) {
    alert("Today")

  } else {

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

答:
Is that jQuery UI's datepicker? If yes, then you need to add onSelect as a property to your datepicker parameter.

```<code>$('#startDatePicker').datepicker({
  onSelect: function (selectedDate) {
    var today = new Date().setHours(0, 0, 0, 0);
    var selected = new Date(selectedDate).getTime();

    if (today === selected) {
      alert('Today');
    } else {
      // Do something.
      console.log(selected);
    }
  }
});
</code>```

$(function () {
  $('#startDatePicker').datepicker({
    onSelect: function (selectedDate) {
      var today = new Date().setHours(0, 0, 0, 0);
      var selected = new Date(selectedDate).getTime();

      if (today === selected) {
        alert('Today');
      } else {
        // Do something.
        console.log(selected);
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="startDatePicker" /></code>```

Title: Comparing two dates i javascript

Body:
I want to compare the picked date with the current date. But the if always falls thru to else. I read a couple of posts that the if will always return false because the two dates are two diffretnt object but contains the same time.
I tried getTime() but didnt get it to work either. What i want to achive in the end with this comparison is I want to restrict date input after 09:30 in the morning (24h) if the picked date is today. Is this the right way to go? To filter out the date first and then the time of day? Appriciate all the help I can get! I couldnt get the JSFiddle to work. wanted to give a live sample.

  $('#startDatePicker').datepicker({

  var fromDate = $('#startDatePicker').datepicker('getDate');
  var today = new Date();
  today.setHours(0, 0, 0, 0).getTime();
  selectedDate.setHours(0, 0, 0, 0).getTime();

  if (today === fromDate ) {
    alert("Today")

  } else {

  };
});

Body:
Is that jQuery UI's datepicker? If yes, then you need to add onSelect as a property to your datepicker parameter.

$('#startDatePicker').datepicker({
  onSelect: function (selectedDate) {
    var today = new Date().setHours(0, 0, 0, 0);
    var selected = new Date(selectedDate).getTime();

    if (today === selected) {
      alert('Today');
    } else {
      // Do something.
      console.log(selected);
    }
  }
});

$(function () {
  $('#startDatePicker').datepicker({
    onSelect: function (selectedDate) {
      var today = new Date().setHours(0, 0, 0, 0);
      var selected = new Date(selectedDate).getTime();

      if (today === selected) {
        alert('Today');
      } else {
        // Do something.
        console.log(selected);
      }
    }
  });
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="startDatePicker" />


问:
What are the purpose and benefits of using persistent connection in mysql?
According to php manual:

Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

One advantage is efficiency that we do not need to make connection each time script executes. What are other advantages of persistent connection? Like query cache etc?

答: it Allows for resumption of transactions across multiple request as well as Allow connections setting such as character set encoding to persist</p>


问:
How to find the common elements of 2 cell arrays that contain randperm elements?
I have two cell arrays which may not be of the same size. Elements of cell arrays is randperm of an integer number. randperm data Type is double array. How can I find common elements of two cell arrays?

For example:

```<code>Q1 = {[1 2 3 4], [3 2 4 1], [4 2 1 3]}
Q2 = {[2 4 3 1], [1 2 3 4], [1 2 4 3]}
</code>```

As I said elements of cell arrays are randperm. I want the output of above example be "Element-1 of Q1 i.e. [1 2 3 4] since it is also present in Q2.
Note: Cell Arrays may have different number of columns...

答:
You can do it by using two loops and check all off them.  </p>

```<code>q1=[1 2 3 4; 3 2 4 1; 4 2 1 3];
q2=[2 4 3 1; 1 2 3 4; 1 2 4 3];

%find the size of matrix
[m1,n1] = size(q1);
[m2] = size(q2,1);

for (ii=1:m1)
    for (jj=1:m2)
        %if segments are equal, it will return 1
        %if sum of same segment = 4 it means they are same
        if ( sum( q1(ii,:) == q2(jj,:) ) == n1)
            ii %result of q1
            jj %result of q2
            break;
        end
    end
end
</code>```

Body:
I have two cell arrays which may not be of the same size. Elements of cell arrays is randperm of an integer number. randperm data Type is double array. How can I find common elements of two cell arrays?

For example:

Q1 = {[1 2 3 4], [3 2 4 1], [4 2 1 3]}
Q2 = {[2 4 3 1], [1 2 3 4], [1 2 4 3]}

As I said elements of cell arrays are randperm. I want the output of above example be "Element-1 of Q1 i.e. [1 2 3 4] since it is also present in Q2.
Note: Cell Arrays may have different number of columns...

Body:
You can do it by using two loops and check all off them.

q1=[1 2 3 4; 3 2 4 1; 4 2 1 3];
q2=[2 4 3 1; 1 2 3 4; 1 2 4 3];

%find the size of matrix
[m1,n1] = size(q1);
[m2] = size(q2,1);

for (ii=1:m1)
    for (jj=1:m2)
        %if segments are equal, it will return 1
        %if sum of same segment = 4 it means they are same
        if ( sum( q1(ii,:) == q2(jj,:) ) == n1)
            ii %result of q1
            jj %result of q2
            break;
        end
    end
end


问:
CSS full page background height of scrollable div
there is html code:

```<code> <div class="container content">
 <div class="wrap-container row">
   <div class="col-xs-12 col-md-5 text-center text-white left">
     <h2 class="mt-5">Contact</h2>
      <h1> 987 123 456</h1>
   </div>
   <div class="col-xs-12 col-md-6 ml-auto right">
     <div class="form">
        <form>
          <!-- form controls -->
        </form>
     </div>
   </div>
 </div>
</div>
</code>```

now in css

```<code>.content.container {
    height: 80vh;
    overflow: hidden;
    box-sizing: border-box;
}

.wrap-container {
    position: relative;
    height: 80%;
    border-radius: 5px;
    background: rgba(0,0,0,.3);
    overflow: hidden;
    box-sizing: border-box;

}
.left {
    text-shadow: 0px 1px 2px #808080, 2px 2px 1px rgba(47,171,81, 0.8);
    font-family: Verdana, Geneva, Tahoma, sans-serif;

}
.right {
    background: rgba(0,0,0,.8);
    color: #b9b9b9;
    margin: 2rem;
    height: 86%;
    overflow: hidden;
    box-sizing: border-box;
}
.form {
    overflow: auto;
    height:99%;
    padding-right: 3rem;
    position: relative;
    width: 110%;
    left: 0;
    right: -2rem;
}
@media (max-width: 768px) {
    .content.container {
        height: 200vh;
        display: block;
    }

    .wrap-container {
        display: block;
        height: auto;
        overflow: auto;

    }
    .cb-slideshow li div h3 {
        line-height: 0;
    }
    .right, .left {
        margin:0;
    }
    .right {
        height: auto;
    }
    .form {
        padding-right: 1.5rem;
        /*height: auto;*/
        display: block;
    }
 }
</code>```

now, when .form div is getting higher than verticah height (100vh) content is cut. In small devices like phone I can scroll .form div content but only vh is visible, there is no visible submit button :/
I added in media query height 200vh of .content.container what solved problem but I think it's not proper way.

How should I extend scrollable div till its content height?

答:
Children adapting to parents height is best resolved using flexbox.

I have set the wrap-container as flex and flex-direction:column as the children are stacked. I would try to avoid setting different heights to all children.

Then just add overflow-y:scroll to the form.

```<code>.wrap-container {
display: flex;
flex-direction: column;
}
.form {
overflow-y: scroll;
}
</code>```

If you want to achive something like: 100vh for the main container and items in overflow:hidden but .form scrollable, for all devices, it should be done like this:

Fiddle

Body:
there is html code:

Contact

 987 123 456

        <form>

        </form>

now in css

.content.container {
    height: 80vh;
    overflow: hidden;
    box-sizing: border-box;
}

.wrap-container {
    position: relative;
    height: 80%;
    border-radius: 5px;
    background: rgba(0,0,0,.3);
    overflow: hidden;
    box-sizing: border-box;

}
.left {
    text-shadow: 0px 1px 2px #808080, 2px 2px 1px rgba(47,171,81, 0.8);
    font-family: Verdana, Geneva, Tahoma, sans-serif;

}
.right {
    background: rgba(0,0,0,.8);
    color: #b9b9b9;
    margin: 2rem;
    height: 86%;
    overflow: hidden;
    box-sizing: border-box;
}
.form {
    overflow: auto;
    height:99%;
    padding-right: 3rem;
    position: relative;
    width: 110%;
    left: 0;
    right: -2rem;
}
@media (max-width: 768px) {
    .content.container {
        height: 200vh;
        display: block;
    }

    .wrap-container {
        display: block;
        height: auto;
        overflow: auto;

    }
    .cb-slideshow li div h3 {
        line-height: 0;
    }
    .right, .left {
        margin:0;
    }
    .right {
        height: auto;
    }
    .form {
        padding-right: 1.5rem;
        /*height: auto;*/
        display: block;
    }
 }

now, when .form div is getting higher than verticah height (100vh) content is cut. In small devices like phone I can scroll .form div content but only vh is visible, there is no visible submit button :/
I added in media query height 200vh of .content.container what solved problem but I think it's not proper way.

How should I extend scrollable div till its content height?

Body:
Children adapting to parents height is best resolved using flexbox.

I have set the wrap-container as flex and flex-direction:column as the children are stacked. I would try to avoid setting different heights to all children.

Then just add overflow-y:scroll to the form.

.wrap-container {
display: flex;
flex-direction: column;
}
.form {
overflow-y: scroll;
}

If you want to achive something like: 100vh for the main container and items in overflow:hidden but .form scrollable, for all devices, it should be done like this:

Fiddle


问:
Resizing Auto Layout Constraint
I'm developing an iOS application in Xcode 8. I'm having trouble getting my head around the auto-layout constraints even after reading various tutorials. I am trying to find what combination of constraints allows me to have an adjustable spacing between the top layout guide and the top of my image view.

Below is the preview of the view on iPhone 7 Plus:

iPhone 7 Plus Demo

The top constraint of the UIImageView is currently set to =50, which is the perfect size for larger screens. However, I am trying to have this spacing shrink on smaller screens, as seen below:

iPhone 4s Demo

I have tried what feels like all possible combinations of various constraints with different sizes and priorities but the spacing is either small on all screens or large on all screens. Is there something I am missing?

答:
You can specify different constraint for different trait.
You can do it like below

```<code>override var traitCollection: UITraitCollection {
    let trait = super.traitCollection
    if view.bounds.size.height < 500 {
        return UITraitCollection(verticalSizeClass: UIUserInterfaceSizeClass.compact)
    }
    return trait
}
</code>```

Override trait collection

Select constraint

Select + button before constant field for the constraint in the inspector

Select height as compact and width as any

It will create another constant field for this constraint.

Specify lower constant value

Else you can make that constraint an outlet and in code, check if view.bounds.size.height < some_value than use smaller value as constant for the constraint else regular value

Title: Resizing Auto Layout Constraint

Body:
You can specify different constraint for different trait.
You can do it like below

override var traitCollection: UITraitCollection {
    let trait = super.traitCollection
    if view.bounds.size.height < 500 {
        return UITraitCollection(verticalSizeClass: UIUserInterfaceSizeClass.compact)
    }
    return trait
}

Override trait collection

Select constraint

Select + button before constant field for the constraint in the inspector

Select height as compact and width as any

It will create another constant field for this constraint.

Specify lower constant value

Else you can make that constraint an outlet and in code, check if view.bounds.size.height < some_value than use smaller value as constant for the constraint else regular value


问:
How to set a list of integers while preparing SQL queries in Java
I have a query like this - select * from tbl where ... and colname in (2,3,4) </p>

<p>When I prepare the query (... ' colname in (?)' ) using a PreparedStatement in Java, what setter method should I call to set these integers ? The integers are available in an int array and the size varies. If it matters, the database is MySQL and the column in question is of int type. </p>

答:
As an addendum to Learning's explanation:

Creating an Array can be tricky.

There's a creator method in Connection in JDK 1.6 and later.
http://download.java.net/jdk7/docs/api/java/sql/Connection.html#createArrayOf(java.lang.String,%20java.lang.Object[])

Since JDK1.6 is the latest stable release, your JDBC drivers may not support it.

You can try and create your own Array implementation, but that may not work with all JDBC connector implementations.

OwnerDisplayName: Vijay Dev

Body:
I have a query like this - select * from tbl where ... and colname in (2,3,4)

When I prepare the query (... ' colname in (?)' ) using a PreparedStatement in Java, what setter method should I call to set these integers ? The integers are available in an int array and the size varies. If it matters, the database is MySQL and the column in question is of int type.

LastEditorDisplayName: Vijay Dev


问:
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)'
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)' .
cake==lie
1==0

I have no idea what this means ... I get it in this code

```<code>HANDLE CPlugin::CreateWinampThread()    ||
{                                  __VVVVVVVV__
    hWinampThreadHandle = (HANDLE)CreateThread(NULL, 0, StartWinampThread, (void*)this, 0, &dwWinampThreadID);
    if (!hWinampThreadHandle)
        return 0;

     CloseHandle(hWinampThreadHandle);
     return hWinampThreadHandle;
}

.

DWORD  WINAPI CPlugin::StartWinampThread(void* lpParam)[...]
</code>```

答:
Is it to do with objects - there's an implicit 'this' paramter to your object's StartWinampThread method because it's a member of a class.

What happens if you change it to be a standalone method but keep the same signature i.e. from

```<code>DWORD  WINAPI CPlugin::StartWinampThread(void* lpParam)[...]
</code>```

to
    DWORD  WINAPI StartWinampThread(void* lpParam)[...]

(I know it won't work for you, I'm just interested to see if it removes the compiler's complaint)

Body:
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)' .
cake==lie
1==0

I have no idea what this means ... I get it in this code

HANDLE CPlugin::CreateWinampThread()    ||
{                                  __VVVVVVVV__
    hWinampThreadHandle = (HANDLE)CreateThread(NULL, 0, StartWinampThread, (void*)this, 0, &dwWinampThreadID);
    if (!hWinampThreadHandle)
        return 0;

     CloseHandle(hWinampThreadHandle);
     return hWinampThreadHandle;
}

.

DWORD  WINAPI CPlugin::StartWinampThread(void* lpParam)[...]

Body:
Is it to do with objects - there's an implicit 'this' paramter to your object's StartWinampThread method because it's a member of a class.

What happens if you change it to be a standalone method but keep the same signature i.e. from

DWORD  WINAPI CPlugin::StartWinampThread(void* lpParam)[...]

to
    DWORD  WINAPI StartWinampThread(void* lpParam)[...]

(I know it won't work for you, I'm just interested to see if it removes the compiler's complaint)


问:
A few problems with java input exception handling
I need to handle empty input and remove the stack trace from output.

Here's a snippet of my code:

```<code>public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.println("\n" + "NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }

            if (args.length==0 ||args.length>3||Integer.parseInt(args[i])<0)
                throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
        }
</code>```

I have two problems, first is when a user inputs no value on the command line, it's supposed to throw a IllegalArguementException and the appropriate error message. When I run this code and input no values it runs without throwing the exception. It looks something like this:

C:\Users\XXX\Desktop\Folder>java TestShape

C:\Users\XXX\Desktop\Folder>_

The second problem is when I try out the other exceptions (putting a string instead of an int, negative numbers, exceeding more than 3 numbers etc.) it outputs the proper message but it also prints out the stack trace:

C:\Users\Chef Boi Logro\Desktop\Folder\ICS 112\Lab
  Exercises\LE8\New>java TestShape -1 2 -3

Exception in thread "main" java.lang.IllegalArgumentException:

IllegalArgumentException is caught Please input 1, 2 or 3 valid
  numbers only
          at TestShape.main(TestShape.java:19)

What I need is for the terminal to just display the error messages, without the stack trace.

答:
Your loop is not entered when no arguments are supplied, so no exception is thrown and nothing is displayed.

You should add a condition prior to the loop that throws an exception if args.length==0.

As for the stack trace being displayed, that's the default behavior for exception not handled by the main method. You'll have to catch all the exceptions you throw in order to avoid that.

Perhaps you should just replace

```<code>throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
</code>```

with

```<code>System.err.println("\n" + "Please input 1, 2 or 3 valid numbers only");
</code>```

since there's not much point in throwing exceptions from the main method (since there's no other method that can handle such exceptions).

Here's a suggested approach:

```<code>public static void main(String args[])
{
    if (args.length == 0 || args.length > 3) {
        System.err.println("Please input 1, 2 or 3 valid numbers only");
    } else {
        for(int i = 0; i < args.length; i++) {
            try {
                if (Integer.parseInt(args[i]) < 0) {
                    System.err.println("\n" + "Please input 1, 2 or 3 valid numbers only");
                }
            }
            catch(NumberFormatException nfe) {
                System.err.println("\n" + "NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }
        }
    }
}
</code>```

Body:
I need to handle empty input and remove the stack trace from output.

Here's a snippet of my code:

public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.println("\n" + "NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }

            if (args.length==0 ||args.length>3||Integer.parseInt(args[i])<0)
                throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
        }

I have two problems, first is when a user inputs no value on the command line, it's supposed to throw a IllegalArguementException and the appropriate error message. When I run this code and input no values it runs without throwing the exception. It looks something like this:

C:\Users\XXX\Desktop\Folder>java TestShape

C:\Users\XXX\Desktop\Folder>_

The second problem is when I try out the other exceptions (putting a string instead of an int, negative numbers, exceeding more than 3 numbers etc.) it outputs the proper message but it also prints out the stack trace:

C:\Users\Chef Boi Logro\Desktop\Folder\ICS 112\Lab
  Exercises\LE8\New>java TestShape -1 2 -3

Exception in thread "main" java.lang.IllegalArgumentException:

IllegalArgumentException is caught Please input 1, 2 or 3 valid
  numbers only
          at TestShape.main(TestShape.java:19)

What I need is for the terminal to just display the error messages, without the stack trace.

Body:
Your loop is not entered when no arguments are supplied, so no exception is thrown and nothing is displayed.

You should add a condition prior to the loop that throws an exception if args.length==0.

As for the stack trace being displayed, that's the default behavior for exception not handled by the main method. You'll have to catch all the exceptions you throw in order to avoid that.

Perhaps you should just replace

throw new IllegalArgumentException("\n" + "IllegalArgumentException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");

with

System.err.println("\n" + "Please input 1, 2 or 3 valid numbers only");

since there's not much point in throwing exceptions from the main method (since there's no other method that can handle such exceptions).

Here's a suggested approach:

public static void main(String args[])
{
    if (args.length == 0 || args.length > 3) {
        System.err.println("Please input 1, 2 or 3 valid numbers only");
    } else {
        for(int i = 0; i < args.length; i++) {
            try {
                if (Integer.parseInt(args[i]) < 0) {
                    System.err.println("\n" + "Please input 1, 2 or 3 valid numbers only");
                }
            }
            catch(NumberFormatException nfe) {
                System.err.println("\n" + "NumberFormatException is caught" + "\n" + "Please input 1, 2 or 3 valid numbers only");
            }
        }
    }
}


问:
How to remove 'null' values in laravel controller while retrieving data from database
The results in $data variable. I want to remove null values at output.

The following code:

```<code>    $data = json_decode(json_encode($data),true);
</code>```

I am copying $data to $data1 later to merge the two variables using below code:

```<code>$data1 = $data;
$unique= array_merge($data1,$data);
$final =array_values(array_map("unserialize",array_unique(array_map("serialize", $unique))));
</code>```

答:
If both $data adn $data1 are database results I can assume they are collections.

Then you can make 1 collection by applying union: $data->union($data1);

After which you can filter the result set:

$data->filter(function ($element, $key) {
     return $element!==null;
});

Body:
The results in $data variable. I want to remove null values at output.

The following code:

    $data = json_decode(json_encode($data),true);

I am copying $data to $data1 later to merge the two variables using below code:

$data1 = $data;
$unique= array_merge($data1,$data);
$final =array_values(array_map("unserialize",array_unique(array_map("serialize", $unique))));


问:
Rails Marketplace - Spree Gem or Build from Scratch?
I wish to create a marketplace using rails. Currently, there is a ecommerce gem called Spree and I am planning to use it.

BUT a dilemma is stopping me from pursuing it. I am mixed as to whether I should build the marketplace from scratch or build it faster using Spree and its extensions.

I simply want to build an mvp and this is what I gather...

(1) Using the Spree gem will be faster but again, it might be difficult to customize or pivot.
(2) Building from scratch might be slow but I will always be in control of the features of the site.
(3) Some spree extensions are not well maintained.

I hope to seek opinions regarding this. And I hope to get some. Thanks for reading.

答: If you want to build an MVP and stay with Ruby on Rails, then your best option is to use open source version of Sharetribe. We have done tens of custom online and mobile marketplaces and for some clients started with Sharetribe. This option gives you ALL you need in the box for typical peer-to-peer marketplace while you have all the freedom for customization. It is open source Ruby on Rails in github. We publish series of posts on marketplace development including what you need to start with sharetribe, http://syndicode.co/ruby-on-rails-marketplace-development/. Please feel free to reach to me if you have some questions, need advise or feasibility of Sharetribe for your specific idea.</p>


问:
Problem with Fedex Address Verification Web Reference
I'm trying to get the sample FedEx Address Verification application to work in C#. After contacting my FedEx technical contact and having him activate Address Verification on my test account (apparently it is considered an advanced service that requires additional permissions) I was able to compile and run the example application.

However, I wasn't getting quite the results I expected given the settings...

```<code>request.Options.ConvertToUpperCase = true;
request.Options.CheckResidentialStatus = true;
</code>```

Based on these flags, I expected to have the address come back in upper case, and to be able to check the Residential or ResidentialStatus properties to determine commercial vs residential.  Neither were occuring.

So I installed Fiddler to see the exact SOAP exchange that was taking place and found that the outbound Options tag was not populating except for one property, MaximumNumberOfMatches.

Is there something I should check for in the Reference.cs file that is created by Visual Studio? I didn't see anything out of the norm, but something is happening that is preventing the serialization of some of the properties.

--Edit--

Updated my code as per the suggestion below. Unfortunately, it still only populates 2 of the options parameters. I've included the C# settings code and the outbound/inbound SOAP request below. Can anyone think of a reason the rest of the options are not being sent in the SOAP request?

```<code>AddressValidationRequest request = new AddressValidationRequest();
            //
            request.WebAuthenticationDetail = new WebAuthenticationDetail();
            request.WebAuthenticationDetail.UserCredential = new WebAuthenticationCredential();
            request.WebAuthenticationDetail.UserCredential.Key = "XXX-KEY-XXX"; // Replace "XXX" with the Key
            request.WebAuthenticationDetail.UserCredential.Password = "XXX-PWD-XXX"; // Replace "XXX" with the Password
            //
            request.ClientDetail = new ClientDetail();
            request.ClientDetail.AccountNumber = "XXX-ACCT#-XXX"; // Replace "XXX" with client's account number
            request.ClientDetail.MeterNumber = "XXX-MTR#-XXX"; // Replace "XXX" with client's meter number
            //
            request.TransactionDetail = new TransactionDetail();
            request.TransactionDetail.CustomerTransactionId = "***Address Validation v2 Request using VC#***"; // This is just an echo back
            //
            request.Version = new VersionId(); // Creates the Version element with all child elements populated
            //
            request.RequestTimestamp = DateTime.Now;
            //
            request.Options = new AddressValidationOptions();
            request.Options.CheckResidentialStatus = true;
            request.Options.CheckResidentialStatusSpecified = true;
            request.Options.VerifyAddresses = true;
            request.Options.MaximumNumberOfMatches = "5";
            request.Options.StreetAccuracy = AddressValidationAccuracyType.MEDIUM;
            request.Options.DirectionalAccuracy = AddressValidationAccuracyType.MEDIUM;
            request.Options.CompanyNameAccuracy = AddressValidationAccuracyType.MEDIUM;
            request.Options.ConvertToUpperCase = true;
            request.Options.RecognizeAlternateCityNames = true;
            request.Options.ReturnParsedElements = true;
            //
            request.AddressesToValidate = new AddressToValidate[2];
            request.AddressesToValidate[0] = new AddressToValidate();
            request.AddressesToValidate[0].AddressId = "Kimmel";
            request.AddressesToValidate[0].Address = new Address();
            request.AddressesToValidate[0].Address.StreetLines = new String[1] { "425 Morningside Dr" };
            request.AddressesToValidate[0].Address.City = "Deerfield";
            request.AddressesToValidate[0].Address.PostalCode = "53531";
            request.AddressesToValidate[0].Address.CountryCode = "US";
            //
            request.AddressesToValidate[1] = new AddressToValidate();
            request.AddressesToValidate[1].AddressId = "WD";
            request.AddressesToValidate[1].Address = new Address();
            request.AddressesToValidate[1].Address.StreetLines = new String[1] { "2830 Progress Rd" };
            request.AddressesToValidate[1].Address.PostalCode = "53716";
            request.AddressesToValidate[1].CompanyName = "Wingra Direct";
</code>```

The outbound SOAP Request (obtained using Fiddler). Note the missing options:

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <AddressValidationRequest xmlns="http://fedex.com/ws/addressvalidation/v2">
            <WebAuthenticationDetail>
                <UserCredential>
                    <Key>XXX-KEY-XXX</Key>
                    <Password>XXX-PWD-XXX</Password>
                </UserCredential>
            </WebAuthenticationDetail>
            <ClientDetail>
                <AccountNumber>XXX-ACCT#-XXX</AccountNumber>
                <MeterNumber>XXX-MTR#-XXX</MeterNumber>
            </ClientDetail>
            <TransactionDetail>
                <CustomerTransactionId>***Address Validation v2 Request using VC#***</CustomerTransactionId>
            </TransactionDetail>
            <Version>
                <ServiceId>aval</ServiceId>
                <Major>2</Major>
                <Intermediate>0</Intermediate>
                <Minor>0</Minor>
            </Version>
            <RequestTimestamp>2010-08-26T16:40:13.2026134-05:00</RequestTimestamp>
            <Options>
                <CheckResidentialStatus>true</CheckResidentialStatus>
                <MaximumNumberOfMatches>5</MaximumNumberOfMatches>
            </Options>
            <AddressesToValidate>
                <AddressId>Kimmel</AddressId>
                <Address>
                    <StreetLines>425 Morningside Dr</StreetLines>
                    <City>Deerfield</City>
                    <PostalCode>53531</PostalCode>
                    <CountryCode>US</CountryCode>
                    <Residential>true</Residential>
                </Address>
            </AddressesToValidate>
            <AddressesToValidate>
                <AddressId>WD</AddressId>
                <CompanyName>Wingra Direct</CompanyName>
                <Address>
                    <StreetLines>2830 Progress Rd</StreetLines>
                    <PostalCode>53716</PostalCode>
                </Address>
            </AddressesToValidate>
        </AddressValidationRequest>
    </soap:Body>
</soap:Envelope>
</code>```

The response I get back is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <env:Header xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"/>
    <soapenv:Body>
        <v2:AddressValidationReply xmlns:v2="http://fedex.com/ws/addressvalidation/v2">
            <v2:HighestSeverity>SUCCESS</v2:HighestSeverity>
            <v2:Notifications>
                <v2:Severity>SUCCESS</v2:Severity>
                <v2:Source>wsi</v2:Source>
            </v2:Notifications>
            <v2:TransactionDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <v2:CustomerTransactionId>***Address Validation v2 Request using VC#***</v2:CustomerTransactionId>
            </v2:TransactionDetail>
            <v2:Version xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <v2:ServiceId>aval</v2:ServiceId>
                <v2:Major>2</v2:Major>
                <v2:Intermediate>0</v2:Intermediate>
                <v2:Minor>0</v2:Minor>
            </v2:Version>
            <v2:ReplyTimestamp>2010-08-26T21:40:14.140Z</v2:ReplyTimestamp>
            <v2:AddressResults>
                <v2:AddressId>Kimmel</v2:AddressId>
                <v2:ProposedAddressDetails>
                    <v2:Score>93</v2:Score>
                    <v2:Changes>MODIFIED_TO_ACHIEVE_MATCH</v2:Changes>
                    <v2:ResidentialStatus>UNAVAILABLE</v2:ResidentialStatus>
                    <v2:DeliveryPointValidation>CONFIRMED</v2:DeliveryPointValidation>
                    <v2:Address>
                        <v2:StreetLines>425 Morningside Dr</v2:StreetLines>
                        <v2:City>Deerfield</v2:City>
                        <v2:StateOrProvinceCode>WI</v2:StateOrProvinceCode>
                        <v2:PostalCode>53531-9492</v2:PostalCode>
                        <v2:CountryCode>US</v2:CountryCode>
                    </v2:Address>
                    <v2:RemovedNonAddressData/>
                </v2:ProposedAddressDetails>
            </v2:AddressResults>
            <v2:AddressResults>
                <v2:AddressId>WD</v2:AddressId>
                <v2:ProposedAddressDetails>
                    <v2:Score>93</v2:Score>
                    <v2:Changes>MODIFIED_TO_ACHIEVE_MATCH</v2:Changes>
                    <v2:ResidentialStatus>UNAVAILABLE</v2:ResidentialStatus>
                    <v2:DeliveryPointValidation>CONFIRMED</v2:DeliveryPointValidation>
                    <v2:CompanyName>Wingra Direct</v2:CompanyName>
                    <v2:Address>
                        <v2:StreetLines>2830 Progress Rd</v2:StreetLines>
                        <v2:City>Madison</v2:City>
                        <v2:StateOrProvinceCode>WI</v2:StateOrProvinceCode>
                        <v2:PostalCode>53716-3338</v2:PostalCode>
                        <v2:CountryCode>US</v2:CountryCode>
                    </v2:Address>
                    <v2:RemovedNonAddressData/>
                </v2:ProposedAddressDetails>
            </v2:AddressResults>
        </v2:AddressValidationReply>
    </soapenv:Body>
</soapenv:Envelope>
</code>```

答:
Here's another answer from FedEx tech support:

"The address verification API is not available from the test
  environment".

So I'm not sure how you got your test account "activated" for address verification.  Supposedly the FedEx system uses the USPS production address verification system which is why it's not accessible from the FedEx test environment.

I don't know if I believe this 100%, but I know that I'm hitting the FedEx test server with valid credentials and getting a "Authentication Failed" response.

Body:
I'm trying to get the sample FedEx Address Verification application to work in C#. After contacting my FedEx technical contact and having him activate Address Verification on my test account (apparently it is considered an advanced service that requires additional permissions) I was able to compile and run the example application.

However, I wasn't getting quite the results I expected given the settings...

request.Options.ConvertToUpperCase = true;
request.Options.CheckResidentialStatus = true;

Based on these flags, I expected to have the address come back in upper case, and to be able to check the Residential or ResidentialStatus properties to determine commercial vs residential.  Neither were occuring.

So I installed Fiddler to see the exact SOAP exchange that was taking place and found that the outbound Options tag was not populating except for one property, MaximumNumberOfMatches.

Is there something I should check for in the Reference.cs file that is created by Visual Studio? I didn't see anything out of the norm, but something is happening that is preventing the serialization of some of the properties.

--Edit--

Updated my code as per the suggestion below. Unfortunately, it still only populates 2 of the options parameters. I've included the C# settings code and the outbound/inbound SOAP request below. Can anyone think of a reason the rest of the options are not being sent in the SOAP request?

AddressValidationRequest request = new AddressValidationRequest();
            //
            request.WebAuthenticationDetail = new WebAuthenticationDetail();
            request.WebAuthenticationDetail.UserCredential = new WebAuthenticationCredential();
            request.WebAuthenticationDetail.UserCredential.Key = "XXX-KEY-XXX"; // Replace "XXX" with the Key
            request.WebAuthenticationDetail.UserCredential.Password = "XXX-PWD-XXX"; // Replace "XXX" with the Password
            //
            request.ClientDetail = new ClientDetail();
            request.ClientDetail.AccountNumber = "XXX-ACCT#-XXX"; // Replace "XXX" with client's account number
            request.ClientDetail.MeterNumber = "XXX-MTR#-XXX"; // Replace "XXX" with client's meter number
            //
            request.TransactionDetail = new TransactionDetail();
            request.TransactionDetail.CustomerTransactionId = "***Address Validation v2 Request using VC#***"; // This is just an echo back
            //
            request.Version = new VersionId(); // Creates the Version element with all child elements populated
            //
            request.RequestTimestamp = DateTime.Now;
            //
            request.Options = new AddressValidationOptions();
            request.Options.CheckResidentialStatus = true;
            request.Options.CheckResidentialStatusSpecified = true;
            request.Options.VerifyAddresses = true;
            request.Options.MaximumNumberOfMatches = "5";
            request.Options.StreetAccuracy = AddressValidationAccuracyType.MEDIUM;
            request.Options.DirectionalAccuracy = AddressValidationAccuracyType.MEDIUM;
            request.Options.CompanyNameAccuracy = AddressValidationAccuracyType.MEDIUM;
            request.Options.ConvertToUpperCase = true;
            request.Options.RecognizeAlternateCityNames = true;
            request.Options.ReturnParsedElements = true;
            //
            request.AddressesToValidate = new AddressToValidate[2];
            request.AddressesToValidate[0] = new AddressToValidate();
            request.AddressesToValidate[0].AddressId = "Kimmel";
            request.AddressesToValidate[0].Address = new Address();
            request.AddressesToValidate[0].Address.StreetLines = new String[1] { "425 Morningside Dr" };
            request.AddressesToValidate[0].Address.City = "Deerfield";
            request.AddressesToValidate[0].Address.PostalCode = "53531";
            request.AddressesToValidate[0].Address.CountryCode = "US";
            //
            request.AddressesToValidate[1] = new AddressToValidate();
            request.AddressesToValidate[1].AddressId = "WD";
            request.AddressesToValidate[1].Address = new Address();
            request.AddressesToValidate[1].Address.StreetLines = new String[1] { "2830 Progress Rd" };
            request.AddressesToValidate[1].Address.PostalCode = "53716";
            request.AddressesToValidate[1].CompanyName = "Wingra Direct";

The outbound SOAP Request (obtained using Fiddler). Note the missing options:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <AddressValidationRequest xmlns="http://fedex.com/ws/addressvalidation/v2">
            <WebAuthenticationDetail>
                <UserCredential>
                    <Key>XXX-KEY-XXX</Key>
                    <Password>XXX-PWD-XXX</Password>
                </UserCredential>
            </WebAuthenticationDetail>
            <ClientDetail>
                <AccountNumber>XXX-ACCT#-XXX</AccountNumber>
                <MeterNumber>XXX-MTR#-XXX</MeterNumber>
            </ClientDetail>
            <TransactionDetail>
                <CustomerTransactionId>***Address Validation v2 Request using VC#***</CustomerTransactionId>
            </TransactionDetail>
            <Version>
                <ServiceId>aval</ServiceId>
                <Major>2</Major>
                <Intermediate>0</Intermediate>
                <Minor>0</Minor>
            </Version>
            <RequestTimestamp>2010-08-26T16:40:13.2026134-05:00</RequestTimestamp>
            <Options>
                <CheckResidentialStatus>true</CheckResidentialStatus>
                <MaximumNumberOfMatches>5</MaximumNumberOfMatches>
            </Options>
            <AddressesToValidate>
                <AddressId>Kimmel</AddressId>
                <Address>
                    <StreetLines>425 Morningside Dr</StreetLines>
                    <City>Deerfield</City>
                    <PostalCode>53531</PostalCode>
                    <CountryCode>US</CountryCode>
                    <Residential>true</Residential>
                </Address>
            </AddressesToValidate>
            <AddressesToValidate>
                <AddressId>WD</AddressId>
                <CompanyName>Wingra Direct</CompanyName>
                <Address>
                    <StreetLines>2830 Progress Rd</StreetLines>
                    <PostalCode>53716</PostalCode>
                </Address>
            </AddressesToValidate>
        </AddressValidationRequest>
    </soap:Body>
</soap:Envelope>

The response I get back is:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <env:Header xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"/>
    <soapenv:Body>
        <v2:AddressValidationReply xmlns:v2="http://fedex.com/ws/addressvalidation/v2">
            <v2:HighestSeverity>SUCCESS</v2:HighestSeverity>
            <v2:Notifications>
                <v2:Severity>SUCCESS</v2:Severity>
                <v2:Source>wsi</v2:Source>
            </v2:Notifications>
            <v2:TransactionDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <v2:CustomerTransactionId>***Address Validation v2 Request using VC#***</v2:CustomerTransactionId>
            </v2:TransactionDetail>
            <v2:Version xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <v2:ServiceId>aval</v2:ServiceId>
                <v2:Major>2</v2:Major>
                <v2:Intermediate>0</v2:Intermediate>
                <v2:Minor>0</v2:Minor>
            </v2:Version>
            <v2:ReplyTimestamp>2010-08-26T21:40:14.140Z</v2:ReplyTimestamp>
            <v2:AddressResults>
                <v2:AddressId>Kimmel</v2:AddressId>
                <v2:ProposedAddressDetails>
                    <v2:Score>93</v2:Score>
                    <v2:Changes>MODIFIED_TO_ACHIEVE_MATCH</v2:Changes>
                    <v2:ResidentialStatus>UNAVAILABLE</v2:ResidentialStatus>
                    <v2:DeliveryPointValidation>CONFIRMED</v2:DeliveryPointValidation>
                    <v2:Address>
                        <v2:StreetLines>425 Morningside Dr</v2:StreetLines>
                        <v2:City>Deerfield</v2:City>
                        <v2:StateOrProvinceCode>WI</v2:StateOrProvinceCode>
                        <v2:PostalCode>53531-9492</v2:PostalCode>
                        <v2:CountryCode>US</v2:CountryCode>
                    </v2:Address>
                    <v2:RemovedNonAddressData/>
                </v2:ProposedAddressDetails>
            </v2:AddressResults>
            <v2:AddressResults>
                <v2:AddressId>WD</v2:AddressId>
                <v2:ProposedAddressDetails>
                    <v2:Score>93</v2:Score>
                    <v2:Changes>MODIFIED_TO_ACHIEVE_MATCH</v2:Changes>
                    <v2:ResidentialStatus>UNAVAILABLE</v2:ResidentialStatus>
                    <v2:DeliveryPointValidation>CONFIRMED</v2:DeliveryPointValidation>
                    <v2:CompanyName>Wingra Direct</v2:CompanyName>
                    <v2:Address>
                        <v2:StreetLines>2830 Progress Rd</v2:StreetLines>
                        <v2:City>Madison</v2:City>
                        <v2:StateOrProvinceCode>WI</v2:StateOrProvinceCode>
                        <v2:PostalCode>53716-3338</v2:PostalCode>
                        <v2:CountryCode>US</v2:CountryCode>
                    </v2:Address>
                    <v2:RemovedNonAddressData/>
                </v2:ProposedAddressDetails>
            </v2:AddressResults>
        </v2:AddressValidationReply>
    </soapenv:Body>
</soapenv:Envelope>


问:
Why eax gives zero if it contains self?
According to the "Using Assembler in Delphi", eax will contain Self. However, the content of eax is 0 as shown. I wonder what is wrong ?

```<code>procedure TForm1.FormCreate(Sender: TObject);
var
  X, Y: Pointer;
begin
  asm
    mov X, eax
    mov Y, edx
  end;
  ShowMessage(IntToStr(NativeInt(X)) + ' ; ' + IntToStr(NativeInt(Y)));
end;
</code>```

答:
Just use the Push/Pop to get the pointer of SELF, and then use properties freely, like this: </p>

```<code>    asm
      push Self
      pop edx                  //Now, [edx] is the pointer to Self

      mov   ecx, [edx].FItems  //ecx = FItems
      mov   eax, [edx].FCount  //eax = FCount
      dec   eax                //test zero count!
      js    @Exit              //if count was 0 then exit as -1
    @Loop:                     //and so on...
      ......
</code>```

Title: Why eax gives zero if it contains self?

Body:
According to the "Using Assembler in Delphi", eax will contain Self. However, the content of eax is 0 as shown. I wonder what is wrong ?

procedure TForm1.FormCreate(Sender: TObject);
var
  X, Y: Pointer;
begin
  asm
    mov X, eax
    mov Y, edx
  end;
  ShowMessage(IntToStr(NativeInt(X)) + ' ; ' + IntToStr(NativeInt(Y)));
end;

Body:
Just use the Push/Pop to get the pointer of SELF, and then use properties freely, like this:

    asm
      push Self
      pop edx                  //Now, [edx] is the pointer to Self

      mov   ecx, [edx].FItems  //ecx = FItems
      mov   eax, [edx].FCount  //eax = FCount
      dec   eax                //test zero count!
      js    @Exit              //if count was 0 then exit as -1
    @Loop:                     //and so on...
      ......


问:
Accessing Inbox and SentItems folder on EWS using powershell
I'm struggling with some EWS via PowerShell code. It seems I can't access both the Sent Items and the Inbox folders at the same time.

Here's my code:

```<code>$ewsPath = "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
Add-Type -Path $ewsPath
$ews = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList "Exchange2013"
$ews.Credentials = New-Object Net.NetworkCredential('emailbox', 'password')
$ews.AutodiscoverUrl("emailbox@domain.com")
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ews,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
$sentbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ews,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems)
$iv = New-object Microsoft.Exchange.WebServices.Data.ItemView -ArgumentList 10000
$pvSet = New-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$sentItems = $sentbox.FindItems($iv)
</code>```

When I want to get the Sent Items folder in the sentbox variable I get the following error:

Exception when calling "Bind" with "2" argument (s): "The request
  failed. The remote server returned an error: (501) Not implemented.

But if I had the following line between the $inbox and $sentbox initialization it works, but the findItems on $sentbox fails.

```<code>$ews.AutodiscoverUrl("emailbox@domain.com")
</code>```

答:
It was an issue about firewalls.
The code works.</p>

Body:
I'm struggling with some EWS via PowerShell code. It seems I can't access both the Sent Items and the Inbox folders at the same time.

Here's my code:

$ewsPath = "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
Add-Type -Path $ewsPath
$ews = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList "Exchange2013"
$ews.Credentials = New-Object Net.NetworkCredential('emailbox', 'password')
$ews.AutodiscoverUrl("emailbox@domain.com")
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ews,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
$sentbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ews,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems)
$iv = New-object Microsoft.Exchange.WebServices.Data.ItemView -ArgumentList 10000
$pvSet = New-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$sentItems = $sentbox.FindItems($iv)

When I want to get the Sent Items folder in the sentbox variable I get the following error:

Exception when calling "Bind" with "2" argument (s): "The request
  failed. The remote server returned an error: (501) Not implemented.

But if I had the following line between the $inbox and $sentbox initialization it works, but the findItems on $sentbox fails.

$ews.AutodiscoverUrl("emailbox@domain.com")


问:
Azure KeyVaultErrorException on getKey
I'm running AzureClient java sdk. I create keyvault client like this:

```<code>ApplicationTokenCredentials applicationTokenCredentials=new
ApplicationTokenCredentials(APPLICATION_ID, "DOMAIN", CLIENT_SECRET,
AzureEnvironment.AZURE);
vc = new KeyVaultClient(applicationTokenCredentials);
</code>```

And the i write this code to get key from azure directory:

```<code>Future<KeyBundle> keyBundleFuture = vc.getKeyAsync(testKeyIdentifier, new ServiceCallback<KeyBundle>() {
    public void failure(Throwable throwable) {

    }

    public void success(KeyBundle keyBundle) {
        System.out.print(keyBundle.toString());
    }
});
KeyBundle keyBundle = keyBundleFuture.get();
</code>```

But i'm getting this error

```<code>Exception in thread "main" java.util.concurrent.ExecutionException: com.microsoft.azure.keyvault.models.KeyVaultErrorException: Status code 401.
</code>```

Also to note that I have given permissions to my applocation from azure portal to access keyvault

答:
According to the status code 401 of your error and the REST API reference Authentication, requests, and responses of Key Vault, it was caused by using incorrect credentials with Azure Java SDK. To access Key Vault using Azure SDK must be authenticated with KeyVaultCredentials which need to be implemented the method doAuthenticate.

As reference, here is my sample code below.

```<code>ServiceClientCredentials credentials = new KeyVaultCredentials() {

    @Override
    public String doAuthenticate(String authorization, String resource, String scope) {
        AuthenticationResult res = null;

        try {
            res = GetAccessToken(authorization, resource, clientId, secret);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            return res.getAccessToken();
    }

    private AuthenticationResult GetAccessToken(String authorization, String resource, String clientID, String clientKey)
            throws InterruptedException, ExecutionException {
        AuthenticationContext ctx = null;
        ExecutorService service = Executors.newFixedThreadPool(1);
        try {
            ctx = new AuthenticationContext(authorization, false, service);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Future<AuthenticationResult> resp = ctx.acquireToken(resource, new ClientCredential(
            clientID, clientKey), null);
            AuthenticationResult res = resp.get();
            return res;
        }

    };
KeyVaultClient client = new KeyVaultClient(credentials);
String keyIdentifier = "https://<your-keyvault>.vault.azure.net/keys/<your-key>/xxxxxxxxxxxxxxxxxxxxxx";
KeyBundle keyBundle = client.getKey(keyIdentifier);
</code>```

Then, it works.

Title: Azure KeyVaultErrorException on getKey

Body:
I'm running AzureClient java sdk. I create keyvault client like this:

ApplicationTokenCredentials applicationTokenCredentials=new
ApplicationTokenCredentials(APPLICATION_ID, "DOMAIN", CLIENT_SECRET,
AzureEnvironment.AZURE);
vc = new KeyVaultClient(applicationTokenCredentials);

And the i write this code to get key from azure directory:

Future<KeyBundle> keyBundleFuture = vc.getKeyAsync(testKeyIdentifier, new ServiceCallback<KeyBundle>() {
    public void failure(Throwable throwable) {

    }

    public void success(KeyBundle keyBundle) {
        System.out.print(keyBundle.toString());
    }
});
KeyBundle keyBundle = keyBundleFuture.get();

But i'm getting this error

Exception in thread "main" java.util.concurrent.ExecutionException: com.microsoft.azure.keyvault.models.KeyVaultErrorException: Status code 401.

Also to note that I have given permissions to my applocation from azure portal to access keyvault

Body:
According to the status code 401 of your error and the REST API reference Authentication, requests, and responses of Key Vault, it was caused by using incorrect credentials with Azure Java SDK. To access Key Vault using Azure SDK must be authenticated with KeyVaultCredentials which need to be implemented the method doAuthenticate.

As reference, here is my sample code below.

ServiceClientCredentials credentials = new KeyVaultCredentials() {

    @Override
    public String doAuthenticate(String authorization, String resource, String scope) {
        AuthenticationResult res = null;

        try {
            res = GetAccessToken(authorization, resource, clientId, secret);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            return res.getAccessToken();
    }

    private AuthenticationResult GetAccessToken(String authorization, String resource, String clientID, String clientKey)
            throws InterruptedException, ExecutionException {
        AuthenticationContext ctx = null;
        ExecutorService service = Executors.newFixedThreadPool(1);
        try {
            ctx = new AuthenticationContext(authorization, false, service);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Future<AuthenticationResult> resp = ctx.acquireToken(resource, new ClientCredential(
            clientID, clientKey), null);
            AuthenticationResult res = resp.get();
            return res;
        }

    };
KeyVaultClient client = new KeyVaultClient(credentials);
String keyIdentifier = "https://<your-keyvault>.vault.azure.net/keys/<your-key>/xxxxxxxxxxxxxxxxxxxxxx";
KeyBundle keyBundle = client.getKey(keyIdentifier);

Then, it works.


问:
Use fade-in and delay with ng-repeat to display list items
I am trying to display list items one by one with some delay. For that I managed to do something like this:

```<code>  $("#dropDownMenu li").each(function(i) {
    $(this).delay(1000 * i).fadeIn(100);
});
</code>```

It works good when list is something like

```<code>    <li>one</li>
    <li>two</li>
    <li>three</li>
</code>```

JSFiddle

But it does't work when I use ng-repeat in a list, something like this

```<code><li ng-repeat="time in msg.time">{{time}}<li>
</code>```

How can I make it work with ng-repeat?

答:
Since,

The ngRepeat directive instantiates a template once per item from a
  collection.

You would have to manually add a $timeout delay for each item moving them to a new scope of all items together.

var app = angular.module("app", []);

app.controller("ctrl", function($scope, $timeout) {
  $scope.allItems = [];
  $scope.items = ["first", "second", "third", "fourth", "fifth"];

  $timeout(function() {
    $scope.delay();
  }, 1000);

  $scope.delay = function() {
    var dif = $scope.items.length - $scope.allItems.length;
    var currentRow = $scope.allItems.length;
    if (dif > 0) {
      $scope.allItems.push($scope.items[currentRow]);
    }
    if ($scope.items.length > $scope.allItems.length) {
      $timeout(function() {
        $scope.delay();
      }, 1000);
    }
    $scope.$apply();
  }

  $scope.getItems = function() {
    return $scope.allItems;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">
  <ul ng-repeat="item in getItems()">
    <li>{{item}}</li>
  </ul>
</body></code>```

Body:
I am trying to display list items one by one with some delay. For that I managed to do something like this:

  $("#dropDownMenu li").each(function(i) {
    $(this).delay(1000 * i).fadeIn(100);
});

It works good when list is something like

one

two

three

JSFiddle

But it does't work when I use ng-repeat in a list, something like this

{{time}}

How can I make it work with ng-repeat?

Body:
Since,

The ngRepeat directive instantiates a template once per item from a
  collection.

You would have to manually add a $timeout delay for each item moving them to a new scope of all items together.

var app = angular.module("app", []);

app.controller("ctrl", function($scope, $timeout) {
  $scope.allItems = [];
  $scope.items = ["first", "second", "third", "fourth", "fifth"];

  $timeout(function() {
    $scope.delay();
  }, 1000);

  $scope.delay = function() {
    var dif = $scope.items.length - $scope.allItems.length;
    var currentRow = $scope.allItems.length;
    if (dif > 0) {
      $scope.allItems.push($scope.items[currentRow]);
    }
    if ($scope.items.length > $scope.allItems.length) {
      $timeout(function() {
        $scope.delay();
      }, 1000);
    }
    $scope.$apply();
  }

  $scope.getItems = function() {
    return $scope.allItems;
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">
  <ul ng-repeat="item in getItems()">
    <li>{{item}}</li>
  </ul>
</body>


问:
Cannot call method 'trustAsResourceUrl' of undefined
I'm using angular to display an iframe of Youtube. In order to, I've used $sce to trust external URL but I've got an error that I can't solve... Maybe someone could explain it to me

Controller.js

```<code>.controller('DetailsCtrl', ['$scope', '$routeParams', '$http',
    function($scope, $routeParams, $http, $sce) {
        $scope.loading = true;
      $scope.url = $sce.trustAsResourceUrl('//www.youtube.com/embed/4wOoLLDXbDY');
        $http.get('projects/' + $routeParams.projectId + '.json').success(function(data) {
          $scope.project = data;
          $scope.loading = false;
        });
    }]);
</code>```

Details.html

```<code><iframe width="560" height="315" ng-src"{{url}}" frameborder="0" allowfullscreen></iframe>
</code>```

Error in Console

```<code>TypeError: Cannot call method 'trustAsResourceUrl' of undefined
    at new <anonymous> (http://localhost:9000/scripts/controllers/details.js:22:25)
    at invoke (http://localhost:9000/bower_components/angular/angular.js:3869:17)
    at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:3880:23)
    at http://localhost:9000/bower_components/angular/angular.js:7134:28
    at link (http://localhost:9000/bower_components/angular-route/angular-route.js:913:26)
    at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:6579:13)
    at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:5986:15)
    at publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:5891:30)
    at boundTranscludeFn (http://localhost:9000/bower_components/angular/angular.js:6005:21)
    at controllersBoundTransclude (http://localhost:9000/bower_components/angular/angular.js:6600:18) <div ng-view="" class="ng-scope">
</code>```

答:
You must enter $Sec in your controller:

```<code>.controller('DetailsCtrl', ['$scope', '$routeParams', '$http', '$sce',
    function($scope, $routeParams, $http, $sce)

$sce
</code>```

Body:
I'm using angular to display an iframe of Youtube. In order to, I've used $sce to trust external URL but I've got an error that I can't solve... Maybe someone could explain it to me

Controller.js

.controller('DetailsCtrl', ['$scope', '$routeParams', '$http',
    function($scope, $routeParams, $http, $sce) {
        $scope.loading = true;
      $scope.url = $sce.trustAsResourceUrl('//www.youtube.com/embed/4wOoLLDXbDY');
        $http.get('projects/' + $routeParams.projectId + '.json').success(function(data) {
          $scope.project = data;
          $scope.loading = false;
        });
    }]);

Details.html

Error in Console

TypeError: Cannot call method 'trustAsResourceUrl' of undefined
    at new <anonymous> (http://localhost:9000/scripts/controllers/details.js:22:25)
    at invoke (http://localhost:9000/bower_components/angular/angular.js:3869:17)
    at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:3880:23)
    at http://localhost:9000/bower_components/angular/angular.js:7134:28
    at link (http://localhost:9000/bower_components/angular-route/angular-route.js:913:26)
    at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:6579:13)
    at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:5986:15)
    at publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:5891:30)
    at boundTranscludeFn (http://localhost:9000/bower_components/angular/angular.js:6005:21)
    at controllersBoundTransclude (http://localhost:9000/bower_components/angular/angular.js:6600:18)

Body:
You must enter $Sec in your controller:

.controller('DetailsCtrl', ['$scope', '$routeParams', '$http', '$sce',
    function($scope, $routeParams, $http, $sce)

$sce


问:
MOSS 2007 Version History Query
I need to generate a report that sums the number of files uploaded to a document library, including individual versions.

For example, if I have a document library that contains 20 unique documents, with only two items having more than one version (say two versions each), I'd like to be able to return a report that indicates that there have been 22 uploads.

Is this possible using the built-in MOSS 2007 tools? Do I have to query the database directly?

Thanks in advance

答:
You cannot query the database directly. Its not supported.

This is possible using Audit reports. Enable Auditing on library and then you can query the Auditing in sharepoint object model.

Code sample on Item level auditing:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0e4dd1e7-4b1d-4cb1-b906-6d5d272c8e9d&displaylang=en

Enable Auditing:
http://www.shareesblog.com/?p=195

Title: MOSS 2007 Version History Query


问:
How to declare parameter as function without return value?
I have a function in kotlin

```<code>fun printExecutionTime(block: () -> Any) {
    run {
        val currentTimeMillis = System.currentTimeMillis()
        block()
        Logr.d("Execution time of " + block.javaClass.name + " -> " + System.currentTimeMillis().minus(currentTimeMillis))
    }
}
</code>```

In java code, I want to pass void reference function as parameter, but can't bcs of return value

```<code>PerformanceKt.printExecutionTime(this::voidFunc);
</code>```

One way will be to use interface

```<code>interface Action {
    fun call()
}
</code>```

Is it possible to declare it in kotlin without an extra interface, so the code above will work?

答:
Have you tried using Unit?

```<code>fun f(voidFunc: () -> Unit) {
    // <...>
}
</code>```

upd: After some googling I should admit, that this solution won't work for you. There's an open issue covering the use of Java method references with Kotlin functional types.

However, there's still a workaround to use in Java (looks ugly, yes):

```<code>public Unit voidFunc() {
    // <...>
    return null;
}
</code>```

Body:
I have a function in kotlin

fun printExecutionTime(block: () -> Any) {
    run {
        val currentTimeMillis = System.currentTimeMillis()
        block()
        Logr.d("Execution time of " + block.javaClass.name + " -> " + System.currentTimeMillis().minus(currentTimeMillis))
    }
}

In java code, I want to pass void reference function as parameter, but can't bcs of return value

PerformanceKt.printExecutionTime(this::voidFunc);

One way will be to use interface

interface Action {
    fun call()
}

Is it possible to declare it in kotlin without an extra interface, so the code above will work?

Body:
Have you tried using Unit?

fun f(voidFunc: () -> Unit) {
    // <...>
}

upd: After some googling I should admit, that this solution won't work for you. There's an open issue covering the use of Java method references with Kotlin functional types.

However, there's still a workaround to use in Java (looks ugly, yes):

public Unit voidFunc() {
    // <...>
    return null;
}