问:
powershell script for connecting HyperV VMM and create a VM from specific template
does anyone know is there a way we can connect HyperV-VMM and create a VM using particular template using powershell ?</p>

答: Yes it is possible. The best way to get started with this is to create the template in VMM and go through the creation process for the vm. Before you finish creating it though, on the last page in the bottom corner, you will see a view script button. This actually gives you the powershell version of what is being performed from the GUI.</p>


来源: stackexchange

问:
How to embed H2 database into jar file delivered to the client?
I use H2 database for a desktop application in embedded mode. When I compress the application into jar file the database file is omitted. So, when I run MyApplication.jar nothing works. What is the correct way to embed/include/connect h2.jar file with MyApplication.jar? Or maybe there is another way to deliver database and application in the bundle?</p>

答: If you're using maven to build you project take a look maven-assembly-plugin (jar-with-dependencies). This would produce single jar with all dependencies packed into it.</p>

ContentLicense: CC BY-SA 2.5


问:
How to append a div to a container
I implemented a chatroom by HTML and Javascript recently.

I don't know how to append the message(class="chat self") to the "chat-container" when I click the button "Send".

Here is the code:

```<code>    <div id = "chat-container" class="chat-container">
        <div class="chat friend">
            <div class="user-photo"><img src="images/james.jpg"></div>
            <p class="chat-message">How are you?</p>
        </div>
        <div class="chat self">
            <div class="user-photo"><img src="images/curry.jpg"></div>
            <p class="chat-message">Fine, thx!</p>
        </div>
        <div class="chat friend">
            <div class="user-photo"><img src="images/james.jpg"></div>
            <p class="chat-message">How old are you?</p>
        </div>
    </div>

    <div class="chat-form">
        <textarea id="myTextarea" placeholder="Type your message"></textarea>
        <button onclick="sendMes()">Send</button>
    </div>
</code>```

My idea is like this:

```<code><script>
    function sendMes() {
        var x = document.getElementById("myTextarea").value;
        document.getElementById("demo").innerHTML = x;
        vara data =
        '<div class="chat self">
            <div class="user-photo"><img src="images/curry.jpg"></d-wiv>
            <p class="chat-message">Fine, thx!</p>
        </div>';
        data.chat-message = x;
        document.getElementById("chat-container").appendChild(data);

    }
</script>
</code>```

I've read a lot of articles about HTML DOM, but they only tell how to change the .innerHTML...

I don't know how to create an div object with class="chat self", and set the object's chat-message to the value in the textarea.

Thanks a lot!

答:
Instead of appending a DOM element to #chat-container you are simply appending a string to it (and that too seems to be malformed)

Maybe you should checkout W3School

A sample implementation of the sendMes() could be like

```<code>function sendMes() {
    var message = document.getElementById("myTextarea").value  // maybe try to sanitize it if you are sending it to server

    var messageEl = document.createElement('p')
    messageEl.innerHtml = message;
    messageel.className = "chat-message"

    var userImage = new Image()
    userImage.src = "images/curry.jpg"
    var imageContainer = document.createElement("div")
    imageContainer.appendChild(userImage)
    imageContainer.className = "user-photo"

    var container = document.createElement("div")
    container.appendChild(imageContainer)
    container.appendChild(messageEl)
    container.className = "chat self"

    document.getElementById("chat-container").appendChild(container)

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to append a div to a container

Body:
I implemented a chatroom by HTML and Javascript recently.

I don't know how to append the message(class="chat self") to the "chat-container" when I click the button "Send".

Here is the code:

How are you?

Fine, thx!

How old are you?

        <textarea id="myTextarea" placeholder="Type your message"></textarea>
        <button onclick="sendMes()">Send</button>

My idea is like this:

I've read a lot of articles about HTML DOM, but they only tell how to change the .innerHTML...

I don't know how to create an div object with class="chat self", and set the object's chat-message to the value in the textarea.

Thanks a lot!

Body:
Instead of appending a DOM element to #chat-container you are simply appending a string to it (and that too seems to be malformed)

Maybe you should checkout W3School

A sample implementation of the sendMes() could be like

function sendMes() {
    var message = document.getElementById("myTextarea").value  // maybe try to sanitize it if you are sending it to server

    var messageEl = document.createElement('p')
    messageEl.innerHtml = message;
    messageel.className = "chat-message"

    var userImage = new Image()
    userImage.src = "images/curry.jpg"
    var imageContainer = document.createElement("div")
    imageContainer.appendChild(userImage)
    imageContainer.className = "user-photo"

    var container = document.createElement("div")
    container.appendChild(imageContainer)
    container.appendChild(messageEl)
    container.className = "chat self"

    document.getElementById("chat-container").appendChild(container)

}


问:
How to create a seperate thread for in app billing
I am following the android in app billing tutorial where it states:

Warning: Don't call the getSkuDetails method on the main thread. Calling this method triggers a network request that could block your main thread. Instead, create a separate thread and call the getSkuDetails method from inside of that thread.

for the following code:

```<code> IInAppBillingService mService;

ServiceConnection mServiceConn = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) {
        mService = null;
    }

    @Override
    public void onServiceConnected(ComponentName name,
                                   IBinder service) {
        mService = IInAppBillingService.Stub.asInterface(service);
        Intent serviceIntent =
                new Intent("com.android.vending.billing.InAppBillingService.BIND");
        serviceIntent.setPackage("com.android.vending");
        getActivity().bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
        ArrayList<String> skuList = new ArrayList<String>();
        skuList.add("iap_one");
        Bundle querySkus = new Bundle();
        querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
        try {
            Bundle skuDetails = mService.getSkuDetails(3,
                    getActivity().getPackageName(), "inapp", querySkus);
            int response = skuDetails.getInt("RESPONSE_CODE");
            if (response == 0) {
                ArrayList<String> responseList
                        = skuDetails.getStringArrayList("DETAILS_LIST");

                for (String thisResponse : responseList) {
                    try {
                        JSONObject object = new JSONObject(thisResponse);
                        String sku = object.getString("productId");
                        String price = object.getString("price");
                        Log.d("Test Price", price);
                    } catch (JSONException e){
                        Log.e("MYAPP", "unexpected JSON exception", e);
                    }
                }
            }

        } catch (RemoteException e) {
            Log.e("MYAPP", "unexpected Remote exception", e);
        }

    }
};
</code>```

答:
You need to create class that implements runnable and insert variables that you need  through constructor or use asynctask class

```<code>class ImplementsRunnable implements Runnable {
  private myvar;

  public ImplementsRunnable(String myvar){
    this.myvar=myvar;
  }

  public void run() {
     System.out.println("ImplementsRunnable : myvar: " + myvar);
  }
</code>```

}

Body:
I am following the android in app billing tutorial where it states:

Warning: Don't call the getSkuDetails method on the main thread. Calling this method triggers a network request that could block your main thread. Instead, create a separate thread and call the getSkuDetails method from inside of that thread.

for the following code:

 IInAppBillingService mService;

ServiceConnection mServiceConn = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) {
        mService = null;
    }

    @Override
    public void onServiceConnected(ComponentName name,
                                   IBinder service) {
        mService = IInAppBillingService.Stub.asInterface(service);
        Intent serviceIntent =
                new Intent("com.android.vending.billing.InAppBillingService.BIND");
        serviceIntent.setPackage("com.android.vending");
        getActivity().bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
        ArrayList<String> skuList = new ArrayList<String>();
        skuList.add("iap_one");
        Bundle querySkus = new Bundle();
        querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
        try {
            Bundle skuDetails = mService.getSkuDetails(3,
                    getActivity().getPackageName(), "inapp", querySkus);
            int response = skuDetails.getInt("RESPONSE_CODE");
            if (response == 0) {
                ArrayList<String> responseList
                        = skuDetails.getStringArrayList("DETAILS_LIST");

                for (String thisResponse : responseList) {
                    try {
                        JSONObject object = new JSONObject(thisResponse);
                        String sku = object.getString("productId");
                        String price = object.getString("price");
                        Log.d("Test Price", price);
                    } catch (JSONException e){
                        Log.e("MYAPP", "unexpected JSON exception", e);
                    }
                }
            }

        } catch (RemoteException e) {
            Log.e("MYAPP", "unexpected Remote exception", e);
        }

    }
};

Body:
You need to create class that implements runnable and insert variables that you need  through constructor or use asynctask class

class ImplementsRunnable implements Runnable {
  private myvar;

  public ImplementsRunnable(String myvar){
    this.myvar=myvar;
  }

  public void run() {
     System.out.println("ImplementsRunnable : myvar: " + myvar);
  }

}


问:
How do I alert the user that multiple fields are left blank in an HTML form after clicking submit?
If the user leaves multiple fields blank, I want to let the user know which fields he left blank in one alert message after they click submit. How would I do this? Any help is appreciated!

Here is the HTML code:

```<code><form id="contactform" action="">
    <label> Name
        <input name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus" />
    </label>
    <label> Last Name
        <input name="lastname" type="text" id="lastname" maxlength="150" />
    </label>
    <label> Address
        <input name="address" type="text" id="address" maxlength="200" />
    </label>
    <label> Postcode
        <input name="postcode" type="text" id="postcode" maxlength="50" />
    </label>
    <label> City
        <input name="city" type="text" id="city" maxlength="100" />
    </label>
</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />
</code>```

Here is the javascript code:

```<code>function validate() {

    var firstname = document.getElementById('firstname');
    var lastname = document.getElementById('lastname');
    var address = document.getElementById('address');
    var postcode = document.getElementById('postcode');
    var city = document.getElementById('city');

    if (firstname.value == "") {
        alert("Make sure the first name field is filled");
        return false;
    }

    if (lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
    }
    if (address.value == "") {
        alert("Make sure the address field is filled");
        return false;
    }
    if (postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
    }
    if (city.value == "") {
        alert("Make sure the city field is filled");
        return false;
    }
    return true;
}
</code>```

答:
You can put all the blank fields in a string, like this:

function validate() {

  var firstname = document.getElementById('firstname');
  var lastname = document.getElementById('lastname');
  var address = document.getElementById('address');
  var postcode = document.getElementById('postcode');
  var city = document.getElementById('city');
  var missedFields = ""
  if (firstname.value == "") {
    missedFields += "First name.\n";
    //alert("Make sure the first name field is filled");
    //return false;
  }

  if (lastname.value == "") {
    missedFields += "Last name.\n";
    //alert("Make sure the last name field is filled");
    //return false;
  }
  if (address.value == "") {
    missedFields += "Adress.\n";
    //alert("Make sure the address field is filled");
    //return false;
  }
  if (postcode.value == "") {
    missedFields += "Post code.\n";
    //alert("Make sure the post code field is filled");
    //return false;
  }
  if (city.value == "") {
    missedFields += "City.\n";
    //alert("Make sure the city field is filled");
    //return false;
  }

  if (missedFields.length > 0) {
    alert("Complete all fields:\n" + missedFields);
    return false
  }
  return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="contactform" action="">
  <label> Name
<input name = "firstname" type = "text" id = "firstname" maxlength = "50" autofocus = "autofocus"/>
</label>
  <label> Last Name
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
  <label> Address
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
  <label> Postcode
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
  <label> City
<input name = "city" type = "text" id = "city" maxlength = "100" />
</label>
</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" /></code>```

Body:
If the user leaves multiple fields blank, I want to let the user know which fields he left blank in one alert message after they click submit. How would I do this? Any help is appreciated!

Here is the HTML code:

<form id="contactform" action="">
     Name
        <input name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus" />

     Last Name
        <input name="lastname" type="text" id="lastname" maxlength="150" />

     Address
        <input name="address" type="text" id="address" maxlength="200" />

     Postcode
        <input name="postcode" type="text" id="postcode" maxlength="50" />

     City
        <input name="city" type="text" id="city" maxlength="100" />

</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />

Here is the javascript code:

function validate() {

    var firstname = document.getElementById('firstname');
    var lastname = document.getElementById('lastname');
    var address = document.getElementById('address');
    var postcode = document.getElementById('postcode');
    var city = document.getElementById('city');

    if (firstname.value == "") {
        alert("Make sure the first name field is filled");
        return false;
    }

    if (lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
    }
    if (address.value == "") {
        alert("Make sure the address field is filled");
        return false;
    }
    if (postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
    }
    if (city.value == "") {
        alert("Make sure the city field is filled");
        return false;
    }
    return true;
}

Body:
You can put all the blank fields in a string, like this:

function validate() {

  var firstname = document.getElementById('firstname');
  var lastname = document.getElementById('lastname');
  var address = document.getElementById('address');
  var postcode = document.getElementById('postcode');
  var city = document.getElementById('city');
  var missedFields = ""
  if (firstname.value == "") {
    missedFields += "First name.\n";
    //alert("Make sure the first name field is filled");
    //return false;
  }

  if (lastname.value == "") {
    missedFields += "Last name.\n";
    //alert("Make sure the last name field is filled");
    //return false;
  }
  if (address.value == "") {
    missedFields += "Adress.\n";
    //alert("Make sure the address field is filled");
    //return false;
  }
  if (postcode.value == "") {
    missedFields += "Post code.\n";
    //alert("Make sure the post code field is filled");
    //return false;
  }
  if (city.value == "") {
    missedFields += "City.\n";
    //alert("Make sure the city field is filled");
    //return false;
  }

  if (missedFields.length > 0) {
    alert("Complete all fields:\n" + missedFields);
    return false
  }
  return true;
}

<form id="contactform" action="">
  <label> Name
<input name = "firstname" type = "text" id = "firstname" maxlength = "50" autofocus = "autofocus"/>
</label>
  <label> Last Name
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
  <label> Address
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
  <label> Postcode
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
  <label> City
<input name = "city" type = "text" id = "city" maxlength = "100" />
</label>
</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />


问:
Remove local git tags that are no longer on the remote repository
We use tags in git as part of our deployment process.  From time to time, we want to clean up these tags by removing them from our remote repository.

This is pretty straightforward.  One user deletes the local tag and the remote tag in one set of commands.  We have a little shell script that combines both steps.

The 2nd (3rd, 4th,...) user now has local tags that are no longer reflected on the remote.

I am looking for a command similar to git remote prune origin which cleans up locally tracking branches for which the remote branch has been deleted.

Alternatively, a simple command to list remote tags could be used to compare to the local tags returned via git tag -l.

答:
Just added a git sync-local-tags command to pivotal_git_scripts Gem fork on GitHub:

https://github.com/kigster/git_scripts

Install the gem, then run "git sync-local-tags" in your repository to delete the local tags that do not exist on the remote.

Alternatively you can just install this script below and call it "git-sync-local-tags":

```<code>#!/usr/bin/env ruby

# Delete tags from the local Git repository, which are not found on
# a remote origin
#
# Usage: git sync-local-tags [-n]
#        if -n is passed, just print the tag to be deleted, but do not
#        actually delete it.
#
# Author: Konstantin Gredeskoul (http://tektastic.com)
#
#######################################################################

class TagSynchronizer
  def self.local_tags
    `git show-ref --tags | awk '{print $2}'`.split(/\n/)
  end

  def self.remote_tags
    `git ls-remote --tags origin | awk '{print $2}'`.split(/\n/)
  end

  def self.orphaned_tags
    self.local_tags - self.remote_tags
  end

  def self.remove_unused_tags(print_only = false)
    self.orphaned_tags.each do |ref|
      tag = ref.gsub /refs\/tags\//, ''
      puts "deleting local tag #{tag}"
      `git tag -d #{tag}` unless print_only
    end
  end
end

unless File.exists?(".git")
  puts "This doesn't look like a git repository."
  exit 1
end

print_only = ARGV.include?("-n")
TagSynchronizer.remove_unused_tags(print_only)
</code>```

Body:
Just added a git sync-local-tags command to pivotal_git_scripts Gem fork on GitHub:

https://github.com/kigster/git_scripts

Install the gem, then run "git sync-local-tags" in your repository to delete the local tags that do not exist on the remote.

Alternatively you can just install this script below and call it "git-sync-local-tags":

#!/usr/bin/env ruby

# Delete tags from the local Git repository, which are not found on
# a remote origin
#
# Usage: git sync-local-tags [-n]
#        if -n is passed, just print the tag to be deleted, but do not
#        actually delete it.
#
# Author: Konstantin Gredeskoul (http://tektastic.com)
#
#######################################################################

class TagSynchronizer
  def self.local_tags
    `git show-ref --tags | awk '{print $2}'`.split(/\n/)
  end

  def self.remote_tags
    `git ls-remote --tags origin | awk '{print $2}'`.split(/\n/)
  end

  def self.orphaned_tags
    self.local_tags - self.remote_tags
  end

  def self.remove_unused_tags(print_only = false)
    self.orphaned_tags.each do |ref|
      tag = ref.gsub /refs\/tags\//, ''
      puts "deleting local tag #{tag}"
      `git tag -d #{tag}` unless print_only
    end
  end
end

unless File.exists?(".git")
  puts "This doesn't look like a git repository."
  exit 1
end

print_only = ARGV.include?("-n")
TagSynchronizer.remove_unused_tags(print_only)


问:
Trouble with Code Executing After startActivity()
I am creating a quiz app. In the code below, I want the code after startActivity(intent); to execute once that Activity has finished. The app in its current state will display the question text and answer buttons. Once the user makes a choice, the next question and corresponding answer buttons will be displayed for a split second before the new activity is launched. What I want is for the app to go straight to the new Activity upon answer selection, and once the new Activity has finished, to display the next question.

My code:

```<code>Intent intent = new Intent(getApplicationContext(), NewActivity.class);
startActivity(intent);

// helper variable to keep track of the current question
questionCounter++;
if(questionCounter < numGameQuestions)
{
    // displays the next question
    playGame(randQuestionsArr[questionCounter]);
}
</code>```

答:
use

finish()

to stop the execution of current activity after starting the new intent

Body:
I am creating a quiz app. In the code below, I want the code after startActivity(intent); to execute once that Activity has finished. The app in its current state will display the question text and answer buttons. Once the user makes a choice, the next question and corresponding answer buttons will be displayed for a split second before the new activity is launched. What I want is for the app to go straight to the new Activity upon answer selection, and once the new Activity has finished, to display the next question.

My code:

Intent intent = new Intent(getApplicationContext(), NewActivity.class);
startActivity(intent);

// helper variable to keep track of the current question
questionCounter++;
if(questionCounter < numGameQuestions)
{
    // displays the next question
    playGame(randQuestionsArr[questionCounter]);
}


问:
Ionic - Huge logo doesn't show fully
I am very new to ionic. Trying to put a nice looking picture into the header. So right after I added the ion-nav-title in index.html it becomes like this http://imgur.com/a/XzCpS , the picture was too big. I need the image to fully be shown and also the top nav to not block the form the page.All help will be greatly appreciated :)

index.html

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link rel="manifest" href="manifest.json">

    <!-- un-comment this code to enable service worker
    <script>
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('service-worker.js')
          .then(() => console.log('service worker installed'))
          .catch(err => console.log('Error', err));
      }
    </script>-->

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="lib/ngStorage.min.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>
  </head>
  <body ng-app="starter">
    <!--
      The nav bar that will be updated as we navigate between views.
    -->
    <ion-nav-bar class="bar bar-header navBar" align-title="center">

   <ion-nav-back-button>
   </ion-nav-back-button>

   <ion-nav-title>
        <img alt="Company Logo" height="100" src="img/logo.png">
   </ion-nav-title>

   </ion-nav-bar>
    <!--
      The views will be rendered in the <ion-nav-view> directive below
      Templates are in the /templates folder (but you could also
      have templates inline in this html file if you'd like).
    -->
   <ion-nav-view></ion-nav-view>
  </body>
</html>
</code>```

style.css*

```<code>.navBar {
    height: 100px;
    background: #fffef1;
}
</code>```

Eventsearch.html

```<code><ion-view>
  <ion-content padding="true" class="has-header">
    <form id="othername-form1" class="list">
        <label class="item item-input">
        <span class="input-label">Name</span>
        <input type="text">
      </label>
        <label class="item item-input">
        <span class="input-label">Date</span>
        <input type="date">
      </label>
      <label class="item item-select" >
        <span class="input-label">Country</span>
        <select ng-model="selected">
          <option>Hong Kong</option>
          <option>Tokyo</option>
          <option>Paris</option>
        </select>
      </label>
    </form>
    <a  class="button button-positive  button-block" ui-sref="tab.schedule({country:selected})">Go</a>
    <p>You are searching for events in {{selected}}</p>
  </ion-content>
</ion-view>
</code>```

答:
Try setting the height to auto and the maximum to a huge value:

.navBar {
    height: 100;
    background: #fffef1;
}

ion-nav-title {
    height: 100;
}
```

Title: Ionic - Huge logo doesn't show fully

Body:
I am very new to ionic. Trying to put a nice looking picture into the header. So right after I added the ion-nav-title in index.html it becomes like this http://imgur.com/a/XzCpS , the picture was too big. I need the image to fully be shown and also the top nav to not block the form the page.All help will be greatly appreciated :)

index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link rel="manifest" href="manifest.json">

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <ion-nav-bar class="bar bar-header navBar" align-title="center">

   <ion-nav-back-button>
   </ion-nav-back-button>

   <ion-nav-title>

   </ion-nav-title>

   </ion-nav-bar>

   <ion-nav-view></ion-nav-view>

style.css*

.navBar {
    height: 100px;
    background: #fffef1;
}

Eventsearch.html

<ion-view>
  <ion-content padding="true" class="has-header">
    <form id="othername-form1" class="list">

        Name
        <input type="text">

        Date
        <input type="date">

        Country
        <select ng-model="selected">
          <option>Hong Kong</option>
          <option>Tokyo</option>
          <option>Paris</option>
        </select>

    </form>
    Go

You are searching for events in {{selected}}

  </ion-content>
</ion-view>


答:
function validate() {
  var firstname = document.getElementById('firstname');
  var lastname = document.getElementById('lastname');
  var address = document.getElementById('address');
  var postcode = document.getElementById('postcode');
  var city = document.getElementById('city');
  var errMsg = "";

  if(firstname.value == "") {
    errMsg+="Make sure the first name field is filled\n";
  }
  if(lastname.value == "") {
    errMsg+="Make sure the last name field is filled\n";
  }
  if(address.value == "") {
    errMsg+="Make sure the address field is filled\n";
  }
  if(postcode.value == "") {
    errMsg+="Make sure the post code field is filled\n";
  }
  if(city.value == "") {
    errMsg+="Make sure the city field is filled\n";
  }
  if(errMsg != "") {
    alert(errMsg);
    return false;
  }else {
    return true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id = "contactform" action = "">
<label> Name
<input name = "firstname" type = "text" id = "firstname" maxlength = "50" autofocus = "autofocus"/>
</label>
<label> Last Name
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<label> City
<input name = "city" type = "text" id = "city" maxlength = "100" />
</label>
</form>
<input type = "submit" value = "Submit" onclick = " return validate()" />
<input type = "reset" value = "Clear" /></code>```

This should do it, would need to format it how you like. Also there are several libs out there that handle this for you eg. http://formvalidation.io/

Title: How do I alert the user that multiple fields are left blank in an HTML form after clicking submit?

Body:
function validate() {
  var firstname = document.getElementById('firstname');
  var lastname = document.getElementById('lastname');
  var address = document.getElementById('address');
  var postcode = document.getElementById('postcode');
  var city = document.getElementById('city');
  var errMsg = "";

  if(firstname.value == "") {
    errMsg+="Make sure the first name field is filled\n";
  }
  if(lastname.value == "") {
    errMsg+="Make sure the last name field is filled\n";
  }
  if(address.value == "") {
    errMsg+="Make sure the address field is filled\n";
  }
  if(postcode.value == "") {
    errMsg+="Make sure the post code field is filled\n";
  }
  if(city.value == "") {
    errMsg+="Make sure the city field is filled\n";
  }
  if(errMsg != "") {
    alert(errMsg);
    return false;
  }else {
    return true;
  }
}

<form id = "contactform" action = "">
<label> Name
<input name = "firstname" type = "text" id = "firstname" maxlength = "50" autofocus = "autofocus"/>
</label>
<label> Last Name
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<label> City
<input name = "city" type = "text" id = "city" maxlength = "100" />
</label>
</form>
<input type = "submit" value = "Submit" onclick = " return validate()" />
<input type = "reset" value = "Clear" />

This should do it, would need to format it how you like. Also there are several libs out there that handle this for you eg. http://formvalidation.io/


问:
Effect of assigning an empty initializer list to an existing vector or map?
I have 2 containers, a std::vector and a std::map:

```<code>vector<int> my_vector;
map<string,int> my_map;
my_vector.push_back(3);

// elaboration of my_vector;
...

my_map["Hello"] = 1;

// elaboration of my_map
...
</code>```

Later I do:

```<code>my_map = {};
my_vector = {};
</code>```

This should make the 2 containers 2 empty containers, right? Furthermore, what happens to the memory previously pointed to from my_map and my_vector?

(I'm on C++11)

答:
Both operators copy the values from the initializer list into your container, as referenced below. Since your initializer lists are empty, your collections will be empty after copy-assignment.

http://www.cplusplus.com/reference/vector/vector/operator=/
http://www.cplusplus.com/reference/map/map/operator=/

Your old map and vector are destructed by their copy assign operators. "The elements stored in the container before the call are either assigned to or destroyed", as referenced in the comments to this post.

Body:
I have 2 containers, a std::vector and a std::map:

vector<int> my_vector;
map<string,int> my_map;
my_vector.push_back(3);

// elaboration of my_vector;
...

my_map["Hello"] = 1;

// elaboration of my_map
...

Later I do:

my_map = {};
my_vector = {};

This should make the 2 containers 2 empty containers, right? Furthermore, what happens to the memory previously pointed to from my_map and my_vector?

(I'm on C++11)


问:
Where are jQuery UI colors and widget styles set?
When you download jQuery UI from the jQuery web site, you get a file of javascript code and a file of css code.

I understand that CSS code has to do with various elements of the style and appearance of various web page elements.

I would like to know if there is anything having to do with the style of the jQuery elements that is part of the jQuery UI javascript code.  Can I rip and replace the css file to change the style of the jQuery elements on my web site, or are there some parts of the style hard-coded into the javascript code?

答: The CSS is only for styling. If you need a different styling you can adjust the CSS. It's just there to make your life easier....</p>


问:
Add new task to JobScheduler by PendingIntent
As new Background Service Limitations was released by Android Team "here", there is a problem to start Intent Service by setting a click Pending Intent on Widget(home-screen) Button in Android O. My question is: How can i add a new task to JobScheduler by click on Widget Button? </p>

答:
If there is little to no I/O involved in scheduling the job, have the app widget button use a broadcast PendingIntent to trigger onReceive() in a BroadcastReceiver. In onReceive(), schedule your job.

In principle, you can use that even for work that involves I/O, using goAsync() in the BroadcastReceiver to do a tiny bit of work on a background thread. Or, use a service PendingIntent to invoke an IntentService that only does the I/O necessary to schedule the job.


问:
Validade date in PreviewTextInput DatePicker
I have a DatePicker and a problem in PreviewTextInput event.
I need to include the "/" digit when length is 2 for days and 4 for months.

So, after input goes to 12 for example, i need to include "/" to keep "12/", but if i do that, the text reset and goes for another date.

```<code>private void dpDataEmissao_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        if ((dpDataEmissao.Text + e.Text).Length == 2)
            dpDataEmissao.Text += e.Text + "/";

        if ((dpDataEmissao.Text + e.Text).Length == 4)
            dpDataEmissao.Text += e.Text + "/";
    }
</code>```

The final result must be: "12/04/2017" and user need only put "12042017" and "/" will be included automatically.

Someone already get this problem ?

答:
Using a TextBox:

You need to set e.Handled to true an adjust the position of the cursor:

```<code>if ((dpDataEmissao.Text + e.Text).Length == 2)
{
   e.Handled = true;
   dpDataEmissao.Text += e.Text + "/";
}

if ((dpDataEmissao.Text + e.Text).Length == 5)
{
   e.Handled = true;
   dpDataEmissao.Text += e.Text + "/";
}

if (e.Handled)
{
   dpDataEmissao.CaretIndex = dpDataEmissao.Text.Length;
}
</code>```

Using DatePicker: (Not that nice)

```<code>private void dpDataEmissao_KeyUp(object sender, KeyEventArgs e)
{
    if (new int[] { 2, 5 }.Contains(dpDataEmissao.Text.Length))
    {
        InputSimulator.SimulateTextEntry("/");
    }
}
</code>```

InputSimulator is part of: Windows Input Simulator

PS:

Don't forget to change the 4 to 5!

Body:
I have a DatePicker and a problem in PreviewTextInput event.
I need to include the "/" digit when length is 2 for days and 4 for months.

So, after input goes to 12 for example, i need to include "/" to keep "12/", but if i do that, the text reset and goes for another date.

private void dpDataEmissao_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        if ((dpDataEmissao.Text + e.Text).Length == 2)
            dpDataEmissao.Text += e.Text + "/";

        if ((dpDataEmissao.Text + e.Text).Length == 4)
            dpDataEmissao.Text += e.Text + "/";
    }

The final result must be: "12/04/2017" and user need only put "12042017" and "/" will be included automatically.

Someone already get this problem ?

Body:
Using a TextBox:

You need to set e.Handled to true an adjust the position of the cursor:

if ((dpDataEmissao.Text + e.Text).Length == 2)
{
   e.Handled = true;
   dpDataEmissao.Text += e.Text + "/";
}

if ((dpDataEmissao.Text + e.Text).Length == 5)
{
   e.Handled = true;
   dpDataEmissao.Text += e.Text + "/";
}

if (e.Handled)
{
   dpDataEmissao.CaretIndex = dpDataEmissao.Text.Length;
}

Using DatePicker: (Not that nice)

private void dpDataEmissao_KeyUp(object sender, KeyEventArgs e)
{
    if (new int[] { 2, 5 }.Contains(dpDataEmissao.Text.Length))
    {
        InputSimulator.SimulateTextEntry("/");
    }
}

InputSimulator is part of: Windows Input Simulator

PS:

Don't forget to change the 4 to 5!


问:
how to get the days and exact minutes,exact hours from two dates in javascript?
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

```<code>var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}
</code>```

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance

答:
It looks to me like your calculation for hours still has the days in it. Once you have established the days, just subtract those out when you calculate the hours.

var start = new Date("June 09, 2017 10:30:00");
var end = new Date("June 10, 2017 11:45:00");
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
console.log(time);
function display(a)
{
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var hours = Math.trunc((a-(days*1440))/60);
    var time = [hours,minutes,days];
    return time;
}```

Having said that, I highly recommend moment.js to handle this type of thing, if you can.

Body:
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance

Body:
It looks to me like your calculation for hours still has the days in it. Once you have established the days, just subtract those out when you calculate the hours.

var start = new Date("June 09, 2017 10:30:00");
var end = new Date("June 10, 2017 11:45:00");
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
console.log(time);
function display(a)
{
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var hours = Math.trunc((a-(days*1440))/60);
    var time = [hours,minutes,days];
    return time;
}

Having said that, I highly recommend moment.js to handle this type of thing, if you can.


问:
Angular Typescript libraries suddenly not compiling in Visual Studio
While I was developing Angular 4 application using Visual Studio, I tried to install and uninstall some Angular libraries. And suddenly I found the following compilation errors in visual studio

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   TS2300  Duplicate identifier 'PropertyKey'. TypeScript Virtual Projects C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TypeScript\lib.es2015.core.d.ts  21  Active
Error   TS2403  Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakSet<object>', but here has type 'WeakSet<any>'.    TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  620 Active
Error   TS2403  Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakSet<object>', but here has type 'WeakSet<any>'.    TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  620 Active
Error   TS2403  Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakMap<object, any>', but here has type 'WeakMap<any, any>'.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  606 Active
Error   TS2403  Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakMap<object, any>', but here has type 'WeakMap<any, any>'.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  606 Active
Error   TS2300  Duplicate identifier 'PropertyKey'. TypeScript Virtual Projects C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TypeScript\lib.es2015.core.d.ts  21  Active
Error   TS2300  Duplicate identifier 'PropertyKey'. TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  7   Active
Error   TS2300  Duplicate identifier 'PropertyKey'. TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  7   Active
Error       Build:Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakSet<object>', but here has type 'WeakSet<any>'.  XX  XX\node_modules\@types\es6-shim\index.d.ts  620
Error       Build:Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakMap<object, any>', but here has type 'WeakMap<any, any>'.    XX  XX\node_modules\@types\es6-shim\index.d.ts  606
Error       Build:Duplicate identifier 'PropertyKey'.   XX  C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.3\lib.es2015.core.d.ts   21
Error       Build:Duplicate identifier 'PropertyKey'.   XX  XX\node_modules\@types\es6-shim\index.d.ts  7
Error       Build:All declarations of 'value' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  11
Error       Build:All declarations of 'size' must have identical modifiers. XX  XX\node_modules\@types\es6-shim\index.d.ts  561
Error       Build:All declarations of 'size' must have identical modifiers. XX  XX\node_modules\@types\es6-shim\index.d.ts  581
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  498
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  570
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  591
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  606
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  620
Error       Build:All declarations of 'MIN_SAFE_INTEGER' must have identical modifiers. XX  XX\node_modules\@types\es6-shim\index.d.ts  290
Error       Build:All declarations of 'MAX_SAFE_INTEGER' must have identical modifiers. XX  XX\node_modules\@types\es6-shim\index.d.ts  283
Error       Build:All declarations of 'flags' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  346
Error       Build:All declarations of 'EPSILON' must have identical modifiers.  XX  XX\node_modules\@types\es6-shim\index.d.ts  248
Error   TS2687  All declarations of 'value' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  11  Active
Error   TS2687  All declarations of 'value' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  11  Active
Error   TS2687  All declarations of 'size' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  561 Active
Error   TS2687  All declarations of 'size' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  561 Active
Error   TS2687  All declarations of 'size' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  581 Active
Error   TS2687  All declarations of 'size' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  581 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  498 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  498 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  570 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  570 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  591 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  591 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  606 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  606 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  620 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  620 Active
Error   TS2687  All declarations of 'MIN_SAFE_INTEGER' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  290 Active
Error   TS2687  All declarations of 'MIN_SAFE_INTEGER' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  290 Active
Error   TS2687  All declarations of 'MAX_SAFE_INTEGER' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  283 Active
Error   TS2687  All declarations of 'MAX_SAFE_INTEGER' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  283 Active
Error   TS2687  All declarations of 'flags' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  346 Active
Error   TS2687  All declarations of 'flags' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  346 Active
Error   TS2687  All declarations of 'EPSILON' must have identical modifiers.    TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  248 Active
Error   TS2687  All declarations of 'EPSILON' must have identical modifiers.    TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  248 Active
</code>```

How do I fix these compilation errors?

答:
I have fixed these compilation errors by Deleting the npm packages from my visual studio project and re-install them again as following

Go to web project folder and delete "node_modules" folder

Open windows command as administrator

write cd "{project folder path that contains package.json}"

then write npm install

Body:
While I was developing Angular 4 application using Visual Studio, I tried to install and uninstall some Angular libraries. And suddenly I found the following compilation errors in visual studio

Severity    Code    Description Project File    Line    Suppression State
Error   TS2300  Duplicate identifier 'PropertyKey'. TypeScript Virtual Projects C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TypeScript\lib.es2015.core.d.ts  21  Active
Error   TS2403  Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakSet<object>', but here has type 'WeakSet<any>'.    TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  620 Active
Error   TS2403  Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakSet<object>', but here has type 'WeakSet<any>'.    TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  620 Active
Error   TS2403  Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakMap<object, any>', but here has type 'WeakMap<any, any>'.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  606 Active
Error   TS2403  Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakMap<object, any>', but here has type 'WeakMap<any, any>'.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  606 Active
Error   TS2300  Duplicate identifier 'PropertyKey'. TypeScript Virtual Projects C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TypeScript\lib.es2015.core.d.ts  21  Active
Error   TS2300  Duplicate identifier 'PropertyKey'. TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  7   Active
Error   TS2300  Duplicate identifier 'PropertyKey'. TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  7   Active
Error       Build:Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakSet<object>', but here has type 'WeakSet<any>'.  XX  XX\node_modules\@types\es6-shim\index.d.ts  620
Error       Build:Subsequent variable declarations must have the same type.  Variable 'prototype' must be of type 'WeakMap<object, any>', but here has type 'WeakMap<any, any>'.    XX  XX\node_modules\@types\es6-shim\index.d.ts  606
Error       Build:Duplicate identifier 'PropertyKey'.   XX  C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.3\lib.es2015.core.d.ts   21
Error       Build:Duplicate identifier 'PropertyKey'.   XX  XX\node_modules\@types\es6-shim\index.d.ts  7
Error       Build:All declarations of 'value' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  11
Error       Build:All declarations of 'size' must have identical modifiers. XX  XX\node_modules\@types\es6-shim\index.d.ts  561
Error       Build:All declarations of 'size' must have identical modifiers. XX  XX\node_modules\@types\es6-shim\index.d.ts  581
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  498
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  570
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  591
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  606
Error       Build:All declarations of 'prototype' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  620
Error       Build:All declarations of 'MIN_SAFE_INTEGER' must have identical modifiers. XX  XX\node_modules\@types\es6-shim\index.d.ts  290
Error       Build:All declarations of 'MAX_SAFE_INTEGER' must have identical modifiers. XX  XX\node_modules\@types\es6-shim\index.d.ts  283
Error       Build:All declarations of 'flags' must have identical modifiers.    XX  XX\node_modules\@types\es6-shim\index.d.ts  346
Error       Build:All declarations of 'EPSILON' must have identical modifiers.  XX  XX\node_modules\@types\es6-shim\index.d.ts  248
Error   TS2687  All declarations of 'value' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  11  Active
Error   TS2687  All declarations of 'value' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  11  Active
Error   TS2687  All declarations of 'size' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  561 Active
Error   TS2687  All declarations of 'size' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  561 Active
Error   TS2687  All declarations of 'size' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  581 Active
Error   TS2687  All declarations of 'size' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  581 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  498 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  498 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  570 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  570 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  591 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  591 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  606 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  606 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  620 Active
Error   TS2687  All declarations of 'prototype' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  620 Active
Error   TS2687  All declarations of 'MIN_SAFE_INTEGER' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  290 Active
Error   TS2687  All declarations of 'MIN_SAFE_INTEGER' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  290 Active
Error   TS2687  All declarations of 'MAX_SAFE_INTEGER' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  283 Active
Error   TS2687  All declarations of 'MAX_SAFE_INTEGER' must have identical modifiers.   TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  283 Active
Error   TS2687  All declarations of 'flags' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  346 Active
Error   TS2687  All declarations of 'flags' must have identical modifiers.  TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  346 Active
Error   TS2687  All declarations of 'EPSILON' must have identical modifiers.    TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  248 Active
Error   TS2687  All declarations of 'EPSILON' must have identical modifiers.    TypeScript Virtual Projects XX\node_modules\@types\es6-shim\index.d.ts  248 Active

How do I fix these compilation errors?


问:
GSCRIPT - How to cache HTML page content?
I'm kinda stuck with something here.

I've a HTML template that i'm loading, and within this page there's a lot of JavaScript going on.

I'm trying to accelerate the operation by caching the template with the onOpen() of my Google Sheet. I can't figure how to cache my HTML page CalForm.html (from my internal Google Sheet scripts).

Here's what I have for now:

Creating the cache

```<code>function CacheCreate() {

CacheService.getScriptCache().put('CalCache', 'CalForm');
 Browser.msgBox("done");
}
</code>```

Get the cache

```<code>var evalSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Evaluation');
  var row = evalSheet.getActiveCell().getRow();

  var CalCache2 = CacheService.getScriptCache().get('CalCache');

  Browser.msgBox(CacheService.getScriptCache().get('CalCache'))

  initialize(row);

  //var cache = CacheService.getScriptCache();
  //var cache2 = cache.get('rss-feed-contents');

  //Browser.msgBox(cache.get('rss-feed-contents'));

var html = HtmlService
      .createTemplateFromFile(CalCache2)
      .evaluate()
      .setWidth(1200)
      .setHeight(560)
      .setSandboxMode(HtmlService.SandboxMode.NATIVE);
  SpreadsheetApp.getUi().showModalDialog(html, 'Calculatrice');
</code>```

Thanks for your help!

答:
First you'll want to get the HTML from your "internal Google Sheet scripts", the following code will get the HTML (in string format), given that you have a File in your Script called "template.html".

```<code>var template = HtmlService.createHtmlOutputFromFile('template').getContent();
</code>```

I run a check to see if the data is already in the cache...

```<code>function getObjectsFromCache(key, objects, flush)
{
  Logger.log("Running:  getObjectsFromCache(" + key + ", objects)");
  var cache = CacheService.getScriptCache();
  var cached = cache.get(key);
  flush = false;  // 1st run 45.33, 2nd run 46.475
  //flush = true;// 65.818 seconds
  if (cached != null && flush != true)
  {
    Logger.log("\tEXISTING DATA -> ");
    cached = cache.get(key);
  }
  else
  {
    Logger.log("\tNEW DATA -> ");
    //Logger.log("\tJSON.stringify(objects):  " + JSON.stringify(objects) + ", length:  " + objects.length);
    //If you're working with spreadsheet objects, or array data, you'll want to put the data in the cache as a string, and then reformat the data to it's original format, when it is returned.
    //cache.put(key, JSON.stringify(objects), 1500); // cache for 25 minutes
    //In your case, the HTML does not need to be stringified.
    cache.put(key, objects, 1500); // cache for 25 minutes
    cached = objects;
  }
  return cached;
}
</code>```

I commented-out the JSON.Stringify(objects), because in my original code I use another function called formatCachedData(cache, key) to return the different types of data - a multi-dimensional array (spreadsheet data), or Google user data from AdminDirectory.Users.list({...}).

Body:
I'm kinda stuck with something here.

I've a HTML template that i'm loading, and within this page there's a lot of JavaScript going on.

I'm trying to accelerate the operation by caching the template with the onOpen() of my Google Sheet. I can't figure how to cache my HTML page CalForm.html (from my internal Google Sheet scripts).

Here's what I have for now:

Creating the cache

function CacheCreate() {

CacheService.getScriptCache().put('CalCache', 'CalForm');
 Browser.msgBox("done");
}

Get the cache

var evalSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Evaluation');
  var row = evalSheet.getActiveCell().getRow();

  var CalCache2 = CacheService.getScriptCache().get('CalCache');

  Browser.msgBox(CacheService.getScriptCache().get('CalCache'))

  initialize(row);

  //var cache = CacheService.getScriptCache();
  //var cache2 = cache.get('rss-feed-contents');

  //Browser.msgBox(cache.get('rss-feed-contents'));

var html = HtmlService
      .createTemplateFromFile(CalCache2)
      .evaluate()
      .setWidth(1200)
      .setHeight(560)
      .setSandboxMode(HtmlService.SandboxMode.NATIVE);
  SpreadsheetApp.getUi().showModalDialog(html, 'Calculatrice');

Thanks for your help!

Body:
First you'll want to get the HTML from your "internal Google Sheet scripts", the following code will get the HTML (in string format), given that you have a File in your Script called "template.html".

var template = HtmlService.createHtmlOutputFromFile('template').getContent();

I run a check to see if the data is already in the cache...

function getObjectsFromCache(key, objects, flush)
{
  Logger.log("Running:  getObjectsFromCache(" + key + ", objects)");
  var cache = CacheService.getScriptCache();
  var cached = cache.get(key);
  flush = false;  // 1st run 45.33, 2nd run 46.475
  //flush = true;// 65.818 seconds
  if (cached != null && flush != true)
  {
    Logger.log("\tEXISTING DATA -> ");
    cached = cache.get(key);
  }
  else
  {
    Logger.log("\tNEW DATA -> ");
    //Logger.log("\tJSON.stringify(objects):  " + JSON.stringify(objects) + ", length:  " + objects.length);
    //If you're working with spreadsheet objects, or array data, you'll want to put the data in the cache as a string, and then reformat the data to it's original format, when it is returned.
    //cache.put(key, JSON.stringify(objects), 1500); // cache for 25 minutes
    //In your case, the HTML does not need to be stringified.
    cache.put(key, objects, 1500); // cache for 25 minutes
    cached = objects;
  }
  return cached;
}

I commented-out the JSON.Stringify(objects), because in my original code I use another function called formatCachedData(cache, key) to return the different types of data - a multi-dimensional array (spreadsheet data), or Google user data from AdminDirectory.Users.list({...}).


问:
Search method on Word's paragraph object not working
I have a paragraphsArray of paragraph objects. I have keywordRanges of indexes of some paragraphs and keywords. I am trying to iterate over keywordRanges and get the RangeObject of the keyword from the paragraph object.

But the code fails after first iteration with this error:
PropertyNotLoaded: The property 'items' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context.

Code for reference:

```<code>var myObject = {
  "2":{
    "keywords":["the","which","eye"]
  },
  "4":{
    "keywords":["lorem","ipsum"]
  },
  "9":{
    "keywords":["hellow","world","foo","bar"]
  }
},
paragraphsArray = [],
keywordRanges = []

Word.run((context) => {

  // Create a proxy object for the document body.
  var paragraphs = context.document.body.paragraphs

  // Queue a commmand to get the OOXML contents of the body.
  context.load(paragraphs, 'text, font, style');

  // Synchronize the document state by executing the queued commands,
  // and return a promise to indicate task completion.
  return context.sync()
  .then(() => {
    // push paragraph range objects to an array
    for (var i = 0; i < paragraphs.items.length; i++) {
      paragraphsArray.push(paragraphs.items[i])
    }

    $.each(myObject, (key, value) => {
      $.each(value.keywords, (idx, keyword) => {
        // add the paragraph range object for the corresponding keyword to an array
        var obj = {range:paragraphsArray[key], keyword:keyword}
        keywordRanges.push(obj);
      })
    })
  })
  .then(()=>{
    if(keywordRanges.length > 0){
       $.each(keywordRanges, (idx, obj) =>{

        // search keyword in the paragraph range object
        // obj.range is Paragraph Range object
        var searchKeywordResults = obj.range.search(obj.keyword, { matchWholeWord: true})
        context.load(searchKeywordResults, 'text, font')

        return context.sync().then(() => {
          for (var i = 0; i < searchKeywordResults.items.length; i++) {
            console.log(searchKeywordResults.items[i])
          }
        })
      })
    }
  })
})
</code>```

答: You have a context.sync in a loop that is followed by a then(), which means you have a new Promise chain with each iteration of the loop. All the promises have to be resolved before the Word.run() ends. </p>

Body:
I have a paragraphsArray of paragraph objects. I have keywordRanges of indexes of some paragraphs and keywords. I am trying to iterate over keywordRanges and get the RangeObject of the keyword from the paragraph object.

But the code fails after first iteration with this error:
PropertyNotLoaded: The property 'items' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context.

Code for reference:

var myObject = {
  "2":{
    "keywords":["the","which","eye"]
  },
  "4":{
    "keywords":["lorem","ipsum"]
  },
  "9":{
    "keywords":["hellow","world","foo","bar"]
  }
},
paragraphsArray = [],
keywordRanges = []

Word.run((context) => {

  // Create a proxy object for the document body.
  var paragraphs = context.document.body.paragraphs

  // Queue a commmand to get the OOXML contents of the body.
  context.load(paragraphs, 'text, font, style');

  // Synchronize the document state by executing the queued commands,
  // and return a promise to indicate task completion.
  return context.sync()
  .then(() => {
    // push paragraph range objects to an array
    for (var i = 0; i < paragraphs.items.length; i++) {
      paragraphsArray.push(paragraphs.items[i])
    }

    $.each(myObject, (key, value) => {
      $.each(value.keywords, (idx, keyword) => {
        // add the paragraph range object for the corresponding keyword to an array
        var obj = {range:paragraphsArray[key], keyword:keyword}
        keywordRanges.push(obj);
      })
    })
  })
  .then(()=>{
    if(keywordRanges.length > 0){
       $.each(keywordRanges, (idx, obj) =>{

        // search keyword in the paragraph range object
        // obj.range is Paragraph Range object
        var searchKeywordResults = obj.range.search(obj.keyword, { matchWholeWord: true})
        context.load(searchKeywordResults, 'text, font')

        return context.sync().then(() => {
          for (var i = 0; i < searchKeywordResults.items.length; i++) {
            console.log(searchKeywordResults.items[i])
          }
        })
      })
    }
  })
})


问:
How can I get the URI from the Cling Renderer?
I've now made my cling renderer work after some efforts, that is, the media commanded by a remote control point, can be played/rendered by my renderer(run on Linux, using cling library).

The next I want to achieve is to do something interesting with the media, which requires knowing the URI of the playing media. Does Cling provide some API to achieve this?

答:
See the Cling manual and the MediaRenderer spec:
http://4thline.org/projects/cling/support/manual/cling-support-manual.xhtml#javadoc.example.mediarenderer.AVTransportTest.testCustomPlayer..</p>


问:
How to make UIButton's text alignment center? Using IB
I can't set the title of UIButton using IB as center. My title is multi line.
It is giving like this one

But I want like this one

I have given space in this but I don't want to do that. As it is not aligned exactly for some cases and I know there is a property of UILabel to set the alignment but I don't want to write a code for that.. just want to set everything from IB.

Thanks

答:
For Swift 3.0</p>

```<code>btn.titleLabel?.textAlignment = .center
</code>```

Body:
For Swift 3.0

btn.titleLabel?.textAlignment = .center


问:
Kaa cluster architecture
I am not really understand with Kaa cluster architecture. First is i need to  install and configure Kaa components on a single Linux node by using this link: http://kaaproject.github.io/kaa/docs/v0.10.0/Administration-guide/System-installation/Single-node-installation/

I need to install SQL, NOSQL and Zookeeper in it. Does it means this single node is actually a cluster? i want to implement scalability and high availability. Do i need to clone the single node to implement fail over process?

The Kaa cluster architecture is:
http://kaaproject.github.io/kaa/docs/v0.10.0/Architecture-overview/

答:
To setup and configure Kaa cluster you should follow the instructions on the Kaa Cluster setup documentation page. The Single Node Installation page describes what Kaa dependencies should be installed and how they should be configured, but as it for a single node installation, they all are placed at single node and configured respectively.

The cluster setup is most like single-node installation, but requires more nodes and configuration for their correct cooperation.

Thus, the difference between Kaa cluster and single-node operation is generally in configuration of the components rather than in the components themself.

Therefore, you can clone a single-node Kaa server as a basis for a cluster node, but you will need to change its configuration accordingly before it can operate as a cluter node correctly.

Title: Kaa cluster architecture


问:
Selenium Webdriver with Python: Element is not clickable & Cannot read property 'click' of null
when running this command, I'm getting an error:

```<code>driver.find_element_by_link_text("Confirm").click()

selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a href="javascript:void(0);" class="c-button u-fontSize13 c-button--blue transparent-button js-connect-button js-request-connection" data-href="https://angel.co/user_graph_requests" data-invited-id="5911955">...</a> is not clickable at point (67, 581). Other element would receive the click: `<div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>`
</code>```

After searching answers on this issue, I've changed the above code to:

```<code>element = driver.find_element_by_link_text("Confirm").click()
driver.execute_script("arguments[0].click();", element)
</code>```

For the first click it worked and then printed this error:

```<code>selenium.common.exceptions.WebDriverException: Message: unknown error: Cannot read property 'click' of null
</code>```

The HTML code is:

```<code><a href="javascript:void(0);" class="c-button js-close s-vgLeft0_5 c-button--blue" data-modal="true" data-url="https://angel.co/user_graph_requests/102006082/verify">Confirm</a>
</code>```

答:
If you look at the error message, you will see that another element is intercepting the click. I don't know for sure without looking at the page but generally it's something like a loader screen, popup, etc. that appears temporarily and then disappears. There is also the hint of one of the classes of the intercepting DIV, mfp-s-loading, that further makes me think it's some sort of loading popup. The problem here is that the script proceeds and tries to click the link faster than the popup loads and unloads. What I typically do in a situation like this is to wait for the popup to be invisible and then click the link.

The HTML of the popup is in the error message,

```<code><div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>
</code>```

So you can locate the element using a CSS selector like, div.mfp-s-loading, to wait for it to be invisible and then try your click.

Body:
when running this command, I'm getting an error:

driver.find_element_by_link_text("Confirm").click()

selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (67, 581). Other element would receive the click: `<div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>`

After searching answers on this issue, I've changed the above code to:

element = driver.find_element_by_link_text("Confirm").click()
driver.execute_script("arguments[0].click();", element)

For the first click it worked and then printed this error:

selenium.common.exceptions.WebDriverException: Message: unknown error: Cannot read property 'click' of null

The HTML code is:

Confirm

Body:
If you look at the error message, you will see that another element is intercepting the click. I don't know for sure without looking at the page but generally it's something like a loader screen, popup, etc. that appears temporarily and then disappears. There is also the hint of one of the classes of the intercepting DIV, mfp-s-loading, that further makes me think it's some sort of loading popup. The problem here is that the script proceeds and tries to click the link faster than the popup loads and unloads. What I typically do in a situation like this is to wait for the popup to be invisible and then click the link.

The HTML of the popup is in the error message,

<div class="mfp-container mfp-ajax-holder mfp-s-loading">...</div>

So you can locate the element using a CSS selector like, div.mfp-s-loading, to wait for it to be invisible and then try your click.


问:
How to fix this N+1. Rails. Also, why are N+1 queries so bad?
So I just want to make sure that this is an N+1 query and I want to know how to fix it. ON a high level, where am I losing the most time in an N+1 query? Is it the request over the network to the database url that is costing me the most time? Or is the actual query IN the database that is costing me the most time?

Say we have this:

```<code>products = Product.where(user_id: user.id)  # This is one network database query right?

products.select { |product| !product.restrictions.map(&:state).includes?(user.address.state) }
# restriction is another table. We're trying to filter out products that are restricted to the user's state.
</code>```

Questions

So technically, is this an N+1 query? It is because we're making 1 query to get all products for the user AND another to filter out the restricted products by comparing the product's restrictions by state to the user's state.

So, on a high level, what can I do? Can I eager load the restrictions table in my first query? Or should I just make one trip and do everything in the first query? Are these my two options?

Update

So assume I did Product.includes(:restrictions).where(user_id: user.id), this is all stil oone query right?

Is this also one query if this was all in one method:

```<code>products = Product.where(user_id: user.id)`
products.includes(:restrictions).select do |product|
!product.restrictions.map(&:state_name).include?("CT")
end
</code>```

答:
After @codelitt's answer, here is how you solve this.
You should call

products = Product.includes(:restrictions).where(user_id: user.id) // or you can write the includes in your scope

This will fetch all the related restriction records with the products in the memory. So, in the next line, there won't be a bunch of db query which is costly. Rather it will fetch the records from the memory.

Body:
So I just want to make sure that this is an N+1 query and I want to know how to fix it. ON a high level, where am I losing the most time in an N+1 query? Is it the request over the network to the database url that is costing me the most time? Or is the actual query IN the database that is costing me the most time?

Say we have this:

products = Product.where(user_id: user.id)  # This is one network database query right?

products.select { |product| !product.restrictions.map(&:state).includes?(user.address.state) }
# restriction is another table. We're trying to filter out products that are restricted to the user's state.

Questions

So technically, is this an N+1 query? It is because we're making 1 query to get all products for the user AND another to filter out the restricted products by comparing the product's restrictions by state to the user's state.

So, on a high level, what can I do? Can I eager load the restrictions table in my first query? Or should I just make one trip and do everything in the first query? Are these my two options?

Update

So assume I did Product.includes(:restrictions).where(user_id: user.id), this is all stil oone query right?

Is this also one query if this was all in one method:

products = Product.where(user_id: user.id)`
products.includes(:restrictions).select do |product|
!product.restrictions.map(&:state_name).include?("CT")
end


问:
HttpClient won't import in Android Studio
I have a simple class written in Android Studio:

```<code>package com.mysite.myapp;

import org.apache.http.client.HttpClient;

public class Whatever {
    public void headBangingAgainstTheWallExample () {
        HttpClient client = new DefaultHttpClient();
    }
}
</code>```

and from this I get the following compile time error:

Cannot resolve symbol HttpClient

Isn't HttpClient included in the Android Studio SDK? Even if it is not, I added it to my Gradle build like this:

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'org.apache.httpcomponents:httpclient:4.5'
}
</code>```

With or without the last compile line, the error is the same. What am I missing?

答:
As mentioned before, org.apache.http.client.HttpClient is not supported any more in:

SDK (API level) #23.

You have to use java.net.HttpURLConnection.

If you want to make your code (and life) easier when using HttpURLConnection, here is a Wrapper of this class that will let you do simple operations with GET, POST and PUT using JSON, like for example, doing a HTTP PUT.

```<code>HttpRequest request = new HttpRequest(API_URL + PATH).addHeader("Content-Type", "application/json");
int httpCode = request.put(new JSONObject().toString());
if (HttpURLConnection.HTTP_OK == httpCode) {
    response = request.getJSONObjectResponse();
} else {
  // log error
}
httpRequest.close()
</code>```

Feel free to use it.

```<code>package com.calculistik.repository;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * <p>
 * Copyright © 2017, Calculistik . All rights reserved.
 * <p>
 * Oracle and Java are registered trademarks of Oracle and/or its
 * affiliates. Other names may be trademarks of their respective owners.
 * <p>
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * https://netbeans.org/cddl-gplv2.html or
 * nbbuild/licenses/CDDL-GPL-2-CP. See the License for the specific
 * language governing permissions and limitations under the License.
 * When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this particular file
 * as subject to the "Classpath" exception as provided by Oracle in the
 * GPL Version 2 section of the License file that accompanied this code. If
 * applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 * <p>
 * Contributor(s):
 * Created by alejandro tkachuk @aletkachuk
 * www.calculistik.com
 */
public class HttpRequest {

    public static enum Method {
        POST, PUT, DELETE, GET;
    }

    private URL url;
    private HttpURLConnection connection;
    private OutputStream outputStream;
    private HashMap<String, String> params = new HashMap<String, String>();

    public HttpRequest(String url) throws IOException {
        this.url = new URL(url);
        connection = (HttpURLConnection) this.url.openConnection();
    }

    public int get() throws IOException {
        return this.send();
    }

    public int post(String data) throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.POST.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        this.sendData(data);
        return this.send();
    }

    public int post() throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.POST.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        return this.send();
    }

    public int put(String data) throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.PUT.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        this.sendData(data);
        return this.send();
    }

    public int put() throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.PUT.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        return this.send();
    }

    public HttpRequest addHeader(String key, String value) {
        connection.setRequestProperty(key, value);
        return this;
    }

    public HttpRequest addParameter(String key, String value) {
        this.params.put(key, value);
        return this;
    }

    public JSONObject getJSONObjectResponse() throws JSONException, IOException {
        return new JSONObject(getStringResponse());
    }

    public JSONArray getJSONArrayResponse() throws JSONException, IOException {
        return new JSONArray(getStringResponse());
    }

    public String getStringResponse() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        for (String line; (line = br.readLine()) != null; ) response.append(line + "\n");
        return response.toString();
    }

    public byte[] getBytesResponse() throws IOException {
        byte[] buffer = new byte[8192];
        InputStream is = connection.getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        for (int bytesRead; (bytesRead = is.read(buffer)) >= 0; )
            output.write(buffer, 0, bytesRead);
        return output.toByteArray();
    }

    public void close() {
        if (null != connection)
            connection.disconnect();
    }

    private int send() throws IOException {
        int httpStatusCode = HttpURLConnection.HTTP_BAD_REQUEST;

        if (!this.params.isEmpty()) {
            this.sendData();
        }
        httpStatusCode = connection.getResponseCode();

        return httpStatusCode;
    }

    private void sendData() throws IOException {
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            result.append((result.length() > 0 ? "&" : "") + entry.getKey() + "=" + entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
        }
        sendData(result.toString());
    }

    private HttpRequest sendData(String query) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(query);
        writer.close();
        return this;
    }

}
</code>```

Body:
I have a simple class written in Android Studio:

package com.mysite.myapp;

import org.apache.http.client.HttpClient;

public class Whatever {
    public void headBangingAgainstTheWallExample () {
        HttpClient client = new DefaultHttpClient();
    }
}

and from this I get the following compile time error:

Cannot resolve symbol HttpClient

Isn't HttpClient included in the Android Studio SDK? Even if it is not, I added it to my Gradle build like this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'org.apache.httpcomponents:httpclient:4.5'
}

With or without the last compile line, the error is the same. What am I missing?

Body:
As mentioned before, org.apache.http.client.HttpClient is not supported any more in:

SDK (API level) #23.

You have to use java.net.HttpURLConnection.

If you want to make your code (and life) easier when using HttpURLConnection, here is a Wrapper of this class that will let you do simple operations with GET, POST and PUT using JSON, like for example, doing a HTTP PUT.

HttpRequest request = new HttpRequest(API_URL + PATH).addHeader("Content-Type", "application/json");
int httpCode = request.put(new JSONObject().toString());
if (HttpURLConnection.HTTP_OK == httpCode) {
    response = request.getJSONObjectResponse();
} else {
  // log error
}
httpRequest.close()

Feel free to use it.

package com.calculistik.repository;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * <p>
 * Copyright © 2017, Calculistik . All rights reserved.
 * <p>
 * Oracle and Java are registered trademarks of Oracle and/or its
 * affiliates. Other names may be trademarks of their respective owners.
 * <p>
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * https://netbeans.org/cddl-gplv2.html or
 * nbbuild/licenses/CDDL-GPL-2-CP. See the License for the specific
 * language governing permissions and limitations under the License.
 * When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this particular file
 * as subject to the "Classpath" exception as provided by Oracle in the
 * GPL Version 2 section of the License file that accompanied this code. If
 * applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 * <p>
 * Contributor(s):
 * Created by alejandro tkachuk @aletkachuk
 * www.calculistik.com
 */
public class HttpRequest {

    public static enum Method {
        POST, PUT, DELETE, GET;
    }

    private URL url;
    private HttpURLConnection connection;
    private OutputStream outputStream;
    private HashMap<String, String> params = new HashMap<String, String>();

    public HttpRequest(String url) throws IOException {
        this.url = new URL(url);
        connection = (HttpURLConnection) this.url.openConnection();
    }

    public int get() throws IOException {
        return this.send();
    }

    public int post(String data) throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.POST.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        this.sendData(data);
        return this.send();
    }

    public int post() throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.POST.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        return this.send();
    }

    public int put(String data) throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.PUT.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        this.sendData(data);
        return this.send();
    }

    public int put() throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.PUT.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        return this.send();
    }

    public HttpRequest addHeader(String key, String value) {
        connection.setRequestProperty(key, value);
        return this;
    }

    public HttpRequest addParameter(String key, String value) {
        this.params.put(key, value);
        return this;
    }

    public JSONObject getJSONObjectResponse() throws JSONException, IOException {
        return new JSONObject(getStringResponse());
    }

    public JSONArray getJSONArrayResponse() throws JSONException, IOException {
        return new JSONArray(getStringResponse());
    }

    public String getStringResponse() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        for (String line; (line = br.readLine()) != null; ) response.append(line + "\n");
        return response.toString();
    }

    public byte[] getBytesResponse() throws IOException {
        byte[] buffer = new byte[8192];
        InputStream is = connection.getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        for (int bytesRead; (bytesRead = is.read(buffer)) >= 0; )
            output.write(buffer, 0, bytesRead);
        return output.toByteArray();
    }

    public void close() {
        if (null != connection)
            connection.disconnect();
    }

    private int send() throws IOException {
        int httpStatusCode = HttpURLConnection.HTTP_BAD_REQUEST;

        if (!this.params.isEmpty()) {
            this.sendData();
        }
        httpStatusCode = connection.getResponseCode();

        return httpStatusCode;
    }

    private void sendData() throws IOException {
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            result.append((result.length() > 0 ? "&" : "") + entry.getKey() + "=" + entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
        }
        sendData(result.toString());
    }

    private HttpRequest sendData(String query) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(query);
        writer.close();
        return this;
    }

}


问:
super and base class should have different instances of same attribute name
I'm new to python, I'm trying to learn basic inheritance and I want the super and base class to have attributes with same name, but they should have different instances. Below is the code I've written to experiment with this Idea.

```<code>class master(object):

    def __init__(self, name):
        self.name = name

    def print_name(self):
        print (self.name)

class slave(master):

    def __init__(self, master_name, slave_name):

        self.name = slave_name
        super(slave, self).__init__(master_name)

    def print_name(self):

        super(slave, self).print_name()
        print (self.name)

def main():
    obj = slave('hello', 'world')
    obj.print_name()

if __name__ == '__main__':
    main()
</code>```

The out put I'm getting is :
hello
hello

But I want want the output to be
world
hello

答:
Super class and base class are different names for the same thing, in this case the master class.  That is the base class for slave as well as its super class.

You could have an attribute with the same name on the classes, but not on the instance obj, which is an instance of master and slave at the same time.  So self in both methods master.print_name() and slave.print_name() refers to the very same object.

An attribute on an object can only be assigned one value at a given time, so you need different names.  But you can get the appearance of the same name with the name mangling that is done behind the scenes for attributes with two leading underscores:

```<code>class Master(object):

    def __init__(self, name):
        self.__name = name

    def print_name(self):
        print self.__name

class Slave(Master):

    def __init__(self, master_name, slave_name):

        self.__name = slave_name
        Master.__init__(self, master_name)

    def print_name(self):

        Master.print_name(self)
        print self.__name

def main():
    obj = Slave('hello', 'world')
    obj.print_name()
    # The *actual* names of the attributes:
    print obj._Master__name, obj._Slave__name

if __name__ == '__main__':
    main()
</code>```

Body:
I'm new to python, I'm trying to learn basic inheritance and I want the super and base class to have attributes with same name, but they should have different instances. Below is the code I've written to experiment with this Idea.

class master(object):

    def __init__(self, name):
        self.name = name

    def print_name(self):
        print (self.name)

class slave(master):

    def __init__(self, master_name, slave_name):

        self.name = slave_name
        super(slave, self).__init__(master_name)

    def print_name(self):

        super(slave, self).print_name()
        print (self.name)

def main():
    obj = slave('hello', 'world')
    obj.print_name()

if __name__ == '__main__':
    main()

The out put I'm getting is :
hello
hello

But I want want the output to be
world
hello

Body:
Super class and base class are different names for the same thing, in this case the master class.  That is the base class for slave as well as its super class.

You could have an attribute with the same name on the classes, but not on the instance obj, which is an instance of master and slave at the same time.  So self in both methods master.print_name() and slave.print_name() refers to the very same object.

An attribute on an object can only be assigned one value at a given time, so you need different names.  But you can get the appearance of the same name with the name mangling that is done behind the scenes for attributes with two leading underscores:

class Master(object):

    def __init__(self, name):
        self.__name = name

    def print_name(self):
        print self.__name

class Slave(Master):

    def __init__(self, master_name, slave_name):

        self.__name = slave_name
        Master.__init__(self, master_name)

    def print_name(self):

        Master.print_name(self)
        print self.__name

def main():
    obj = Slave('hello', 'world')
    obj.print_name()
    # The *actual* names of the attributes:
    print obj._Master__name, obj._Slave__name

if __name__ == '__main__':
    main()


问:
How do I parse time in another locale to US locale?
I have a time picker that a user can change, and I need to take the time that they selected and convert it back into US format. I am currently trying to use the DateFormatter so I can easily convert it from one date format to another that I can easily work with.

Here is the code that I am been trying to use, but it does not work:

```<code>let time = "上午11:42"  //11:42 AM
let timeFormatter = DateFormatter()
timeFormatter.locale = Locale(identifier: "en_US_POSIX")
timeFormatter.timeStyle = .short
timeFormatter.dateStyle = .none
timeFormatter.isLenient = true
timeFormatter.date(from: time)  //returns nil
</code>```

The time format should be pretty dynamic since a user can change their language to anything supported by the iOS device.

答:
To put it simply, the parser has to use the locale that was used to generate that string.

However, parsing localized strings is an antipattern. If the users enter dates using a picker, you should use the date from that picker. You shouldn't format it to a string and than parse it back.

That introduces a lot of complexity (including timezones, daylight saving time changes etc).

Body:
I have a time picker that a user can change, and I need to take the time that they selected and convert it back into US format. I am currently trying to use the DateFormatter so I can easily convert it from one date format to another that I can easily work with.

Here is the code that I am been trying to use, but it does not work:

let time = "上午11:42"  //11:42 AM
let timeFormatter = DateFormatter()
timeFormatter.locale = Locale(identifier: "en_US_POSIX")
timeFormatter.timeStyle = .short
timeFormatter.dateStyle = .none
timeFormatter.isLenient = true
timeFormatter.date(from: time)  //returns nil

The time format should be pretty dynamic since a user can change their language to anything supported by the iOS device.