问:
Final app status: FAILED, exitCode: 16 RECEIVED SIGNAL 15: SIGTERM
I am getting below error in driver when running a spark yarn application on spark-1.6.2 cluster:</p>

```<code>2017-03-27 18:41:50 SIGTERM handler [INFO ] ApplicationMaster - Final app status: FAILED, exitCode: 16
2017-03-27 18:41:50 SIGTERM handler [ERROR] ApplicationMaster - RECEIVED SIGNAL 15: SIGTERM
2017-03-27 18:41:50 Driver [ERROR] SparkDriver - Failed to start the driver for TestApp
java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.reportInterruptAfterWait(AbstractQueuedSynchronizer.java:2014)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2048)
    at org.apache.spark.streaming.ContextWaiter.waitForStopOrError(ContextWaiter.scala:63)
    at org.apache.spark.streaming.StreamingContext.awaitTermination(StreamingContext.scala:642)
    at org.apache.spark.streaming.api.java.JavaStreamingContext.awaitTermination(JavaStreamingContext.scala:632)
    at com.test.example.SparkDriver.submit(SparkDriver.java:119)
    at com.test.example.SparkDriver.main(SparkDriver.java:94)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
</code>```

答: This issue was coming on HDP(hortonworks) Cluster and it was HDP upgrade issue. The upgrade for the HDP environment was in between and upgrade was paused on this HDP Cluster. Once the upgrade got finalized the issue got fixed and I was able to run the spark yarn applications on the cluster.

Body:
I am getting below error in driver when running a spark yarn application on spark-1.6.2 cluster:

2017-03-27 18:41:50 SIGTERM handler [INFO ] ApplicationMaster - Final app status: FAILED, exitCode: 16
2017-03-27 18:41:50 SIGTERM handler [ERROR] ApplicationMaster - RECEIVED SIGNAL 15: SIGTERM
2017-03-27 18:41:50 Driver [ERROR] SparkDriver - Failed to start the driver for TestApp
java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.reportInterruptAfterWait(AbstractQueuedSynchronizer.java:2014)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2048)
    at org.apache.spark.streaming.ContextWaiter.waitForStopOrError(ContextWaiter.scala:63)
    at org.apache.spark.streaming.StreamingContext.awaitTermination(StreamingContext.scala:642)
    at org.apache.spark.streaming.api.java.JavaStreamingContext.awaitTermination(JavaStreamingContext.scala:632)
    at com.test.example.SparkDriver.submit(SparkDriver.java:119)
    at com.test.example.SparkDriver.main(SparkDriver.java:94)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)


来源: stackexchange

问:
left join not getting expected data - returns inaccurate result
I am facing issue when trying retrieve some fields from table using left join.

Table 1 has - column reportno, slno, and desc
Table 2 has - Column report no, slno and parameters

Now i would like to retrieve all values from table1 for specific report no and and corresponding  parameters from table2. My expected result is shown below.
that means it should get all row for matching repno from table 1 and also get paramaters by matching repno and slno

/*table2 data*/
repno   slno  parameter
M100001 2     TypeRating
M100001 1     Type&Rating```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>select
qc_item_list.i_rep_no,
qc_item_list.slno,
qc_item_list.ITEM_DESC,
qc_insp.parameters
from qc_item_list
left join qc_insp
on qc_item_list.I_REP_NO = qc_insp.I_REP_NO
WHERE qc_item_list.i_rep_no = 'M100001'
ORDER BY qc_item_list.slno</code>```

答:
SELECT t1.i_rep_no,
       t1.slno,
       t1.ITEM_DESC,
       COALESCE(t2.parameters, 'NA') AS parameter
FROM qc_item_list t1
LEFT JOIN qc_insp t2
    ON t1.slno = t2.slno and t1.i_rep_no = t2.i_rep_no
WHERE t1.i_rep_no = 'M100001'
ORDER BY t1.slno```

added a condition to match repno also

ContentLicense: CC BY-SA 3.0

Body:
I am facing issue when trying retrieve some fields from table using left join.

Table 1 has - column reportno, slno, and desc
Table 2 has - Column report no, slno and parameters

Now i would like to retrieve all values from table1 for specific report no and and corresponding  parameters from table2. My expected result is shown below.
that means it should get all row for matching repno from table 1 and also get paramaters by matching repno and slno

/*table2 data*/
repno   slno  parameter
M100001 2     TypeRating
M100001 1     Type&Rating

select
qc_item_list.i_rep_no,
qc_item_list.slno,
qc_item_list.ITEM_DESC,
qc_insp.parameters
from qc_item_list
left join qc_insp
on qc_item_list.I_REP_NO = qc_insp.I_REP_NO
WHERE qc_item_list.i_rep_no = 'M100001'
ORDER BY qc_item_list.slno

Body:
SELECT t1.i_rep_no,
       t1.slno,
       t1.ITEM_DESC,
       COALESCE(t2.parameters, 'NA') AS parameter
FROM qc_item_list t1
LEFT JOIN qc_insp t2
    ON t1.slno = t2.slno and t1.i_rep_no = t2.i_rep_no
WHERE t1.i_rep_no = 'M100001'
ORDER BY t1.slno

added a condition to match repno also


问:
Delay between speech and voice recognition
I'd like to add a delay between the text to speech and the subsequent voice recognition but don't know enough about wait/sleep statements and the concept of not blocking the main thread.  Could I have suggestions on how to achieve a wait until the text to speech is finished speaking and the voice recognition starting.</p>

```<code>                String myText1 = "Please speak the new speedlimit";
                mTts.speak(myText1, TextToSpeech.QUEUE_FLUSH, null);
                speechSucess = true;
                startVoiceRecognitionActivity();
</code>```

答:
Set an OnUtteranceCompletedListener and call startVoiceRecognitionActivity(); from the listener's callback function:

http://developer.android.com/reference/android/speech/tts/TextToSpeech.html#setOnUtteranceCompletedListener(android.speech.tts.TextToSpeech.OnUtteranceCompletedListener)

ContentLicense: CC BY-SA 2.5

Body:
I'd like to add a delay between the text to speech and the subsequent voice recognition but don't know enough about wait/sleep statements and the concept of not blocking the main thread.  Could I have suggestions on how to achieve a wait until the text to speech is finished speaking and the voice recognition starting.

                String myText1 = "Please speak the new speedlimit";
                mTts.speak(myText1, TextToSpeech.QUEUE_FLUSH, null);
                speechSucess = true;
                startVoiceRecognitionActivity();


问:
How can access random .csv file on my computer for further manipulations?
I am only at the beginning of my python programming way.

```<code>f = csv.reader(open('andr.csv'), delimiter=',')
andr=[]
for row in f:
</code>```

This is for specific .csv file in my comp. I want to INPUT random file

```<code>file=print(input('File to analyze: '))
f = csv.reader(open(file), delimiter=',')
andr=[]
for row in f:
</code>```

This obviously doesn't work. As I've already told, I am just starting to study python and it is probably very easy, but I am stuck here. I appreciate any help.

答:
This is how basic prompts and csv reader work</p>

```<code>import csv

while True:
    filename = input('File to analyze: ')
    try:
    with open(filename, endline='') as fp:
        for row in csv.reader(fp):
            print(row)
        break
    except Exception as e:
        print("Invalid file {} ({}), try again.".format(filename, e))
</code>```

Body:
I am only at the beginning of my python programming way.

f = csv.reader(open('andr.csv'), delimiter=',')
andr=[]
for row in f:

This is for specific .csv file in my comp. I want to INPUT random file

file=print(input('File to analyze: '))
f = csv.reader(open(file), delimiter=',')
andr=[]
for row in f:

This obviously doesn't work. As I've already told, I am just starting to study python and it is probably very easy, but I am stuck here. I appreciate any help.

Body:
This is how basic prompts and csv reader work

import csv

while True:
    filename = input('File to analyze: ')
    try:
    with open(filename, endline='') as fp:
        for row in csv.reader(fp):
            print(row)
        break
    except Exception as e:
        print("Invalid file {} ({}), try again.".format(filename, e))


问:
Azure Logic App - On New Email - Attachments have null bytes

Why aren't the attachments being read correctly?

Trying to use the quick-start template for saving attachments in emails to a SharePoint folder.

Workflow:

On new email (success)

For each container (Attachments is passed in)

Create file (fails)

On new email > Outputs > Attachments

On new mail appears to succeed, but the content of the attachments is set to null ("ContentBytes": null):

```<code>[
  {
    "Id": "AAMkADlhMDBiODNiLWFmOTEtNGZjOS1hMjYxLTY1OTU3MDk4YzZjNABGAAAAAACijX5OkcblRIVMFzOsYgiSBwBFaJ_hCA08Tb5SmdY6ZqCxAAAAADB8AABFaJ_hCA08Tb5SmdY6ZqCxAACD6w2UAAABEgAQAOCw7xb1bG9LstW5SRafEOE=",
    "ContentType": "image/jpeg",
    "Size": 16962,
    "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
    "Name": "image001.jpg",
    "ContentBytes": null
  },
  {
    "Id": "AAMkADlhMDBiODNiLWFmOTEtNGZjOS1hMjYxLTY1OTU3MDk4YzZjNABGAAAAAACijX5OkcblRIVMFzOsYgiSBwBFaJ_hCA08Tb5SmdY6ZqCxAAAAADB8AABFaJ_hCA08Tb5SmdY6ZqCxAACD6w2UAAABEgAQAG7KUOVpzCRJslBYmXAysB4=",
    "ContentType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "Size": 194702,
    "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
    "Name": "Test.docx",
    "ContentBytes": null
  },
  {
    "Id": "AAMkADlhMDBiODNiLWFmOTEtNGZjOS1hMjYxLTY1OTU3MDk4YzZjNABGAAAAAACijX5OkcblRIVMFzOsYgiSBwBFaJ_hCA08Tb5SmdY6ZqCxAAAAADB8AABFaJ_hCA08Tb5SmdY6ZqCxAACD6w2UAAABEgAQAL3JExHdzLJDs0YH1XpZXgU=",
    "ContentType": "image/jpeg",
    "Size": 73353,
    "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
    "Name": "image005.jpg",
    "ContentBytes": null
  },
  {
    "Id": "AAMkADlhMDBiODNiLWFmOTEtNGZjOS1hMjYxLTY1OTU3MDk4YzZjNABGAAAAAACijX5OkcblRIVMFzOsYgiSBwBFaJ_hCA08Tb5SmdY6ZqCxAAAAADB8AABFaJ_hCA08Tb5SmdY6ZqCxAACD6w2UAAABEgAQABUsTq9cXiVCoowGEFnbtHw=",
    "ContentType": "image/jpeg",
    "Size": 3684,
    "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
    "Name": "image003.jpg",
    "ContentBytes": null
  }
]
</code>```

For-each container > Create file

Fails with the following:

InvalidTemplate. Unable to process template language expressions in
  action 'Create_file' inputs at line '1' and column '11': 'The template
  language function 'base64ToBinary' expects its parameter to be a
  string. The provided value is of type 'Null'. Please see
  https://aka.ms/logicexpressions#base64ToBinary for usage details.'.

答: There's an "include attachments " option on the trigger to opt in to include bytes. Make sure that is turned on and it should work. </p>

Body:
Why aren't the attachments being read correctly?

Trying to use the quick-start template for saving attachments in emails to a SharePoint folder.

Workflow:

On new email (success)

For each container (Attachments is passed in)

Create file (fails)

On new email > Outputs > Attachments

On new mail appears to succeed, but the content of the attachments is set to null ("ContentBytes": null):

[
  {
    "Id": "AAMkADlhMDBiODNiLWFmOTEtNGZjOS1hMjYxLTY1OTU3MDk4YzZjNABGAAAAAACijX5OkcblRIVMFzOsYgiSBwBFaJ_hCA08Tb5SmdY6ZqCxAAAAADB8AABFaJ_hCA08Tb5SmdY6ZqCxAACD6w2UAAABEgAQAOCw7xb1bG9LstW5SRafEOE=",
    "ContentType": "image/jpeg",
    "Size": 16962,
    "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
    "Name": "image001.jpg",
    "ContentBytes": null
  },
  {
    "Id": "AAMkADlhMDBiODNiLWFmOTEtNGZjOS1hMjYxLTY1OTU3MDk4YzZjNABGAAAAAACijX5OkcblRIVMFzOsYgiSBwBFaJ_hCA08Tb5SmdY6ZqCxAAAAADB8AABFaJ_hCA08Tb5SmdY6ZqCxAACD6w2UAAABEgAQAG7KUOVpzCRJslBYmXAysB4=",
    "ContentType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "Size": 194702,
    "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
    "Name": "Test.docx",
    "ContentBytes": null
  },
  {
    "Id": "AAMkADlhMDBiODNiLWFmOTEtNGZjOS1hMjYxLTY1OTU3MDk4YzZjNABGAAAAAACijX5OkcblRIVMFzOsYgiSBwBFaJ_hCA08Tb5SmdY6ZqCxAAAAADB8AABFaJ_hCA08Tb5SmdY6ZqCxAACD6w2UAAABEgAQAL3JExHdzLJDs0YH1XpZXgU=",
    "ContentType": "image/jpeg",
    "Size": 73353,
    "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
    "Name": "image005.jpg",
    "ContentBytes": null
  },
  {
    "Id": "AAMkADlhMDBiODNiLWFmOTEtNGZjOS1hMjYxLTY1OTU3MDk4YzZjNABGAAAAAACijX5OkcblRIVMFzOsYgiSBwBFaJ_hCA08Tb5SmdY6ZqCxAAAAADB8AABFaJ_hCA08Tb5SmdY6ZqCxAACD6w2UAAABEgAQABUsTq9cXiVCoowGEFnbtHw=",
    "ContentType": "image/jpeg",
    "Size": 3684,
    "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
    "Name": "image003.jpg",
    "ContentBytes": null
  }
]

For-each container > Create file

Fails with the following:

InvalidTemplate. Unable to process template language expressions in
  action 'Create_file' inputs at line '1' and column '11': 'The template
  language function 'base64ToBinary' expects its parameter to be a
  string. The provided value is of type 'Null'. Please see
  https://aka.ms/logicexpressions#base64ToBinary for usage details.'.


问:
Align image in center without getting space
I want to align the logo at the center in the navigation bar of the page.

This is my code:

```<code><div class="nav">
    <ul>
        <li id="center">
           <a href="home.php"><img src="images/w_logo.gif"></a>
        </li>
    </ul>
</div>
</code>```

I have found this solution online:

```<code>#center img{
    display: block;
    margin: auto;
}
</code>```

But the problem is that by using display:block property I am getting space around the image which is increasing the height of my navigation bar and I am not being able to remove that space.

Help would be appreciated.

答:
#center img{
display: block;
margin: auto;
}
ul{margin:0;}
li{padding:0;list-style:none;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
        <ul>
            <li id="center"><img src="https://dummyimage.com/50x50/000/fff"></li>
        </ul>
    </div></code>```

Demo

Body:
I want to align the logo at the center in the navigation bar of the page.

This is my code:

I have found this solution online:

#center img{
    display: block;
    margin: auto;
}

But the problem is that by using display:block property I am getting space around the image which is increasing the height of my navigation bar and I am not being able to remove that space.

Help would be appreciated.

Body:
#center img{
display: block;
margin: auto;
}
ul{margin:0;}
li{padding:0;list-style:none;}

<div class="nav">
        <ul>
            <li id="center"><a href="home.php"><img src="https://dummyimage.com/50x50/000/fff"></a></li>
        </ul>
    </div>

Demo


问:
Core Data using auto generated Primary Key PK
I have a simple Person entity in Core Data, I noticed that when adding data, each row is auto generated a unique PK called objectID

I wish to retrieve the records using the objectID but I am getting the following error:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'keypath objectID not found in
  entity < NSSQLEntity Person id=2 >'

```<code>func fetchPerson(withID personID: Int,
                 context: NSManagedObjectContext,
                 completion: @escaping ([Person]?) -> Void) {

    let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()

    let predicate = NSPredicate(format: "\(#keyPath(Person.objectID)) == \(personID)")
    fetchRequest.predicate = predicate

    //perform aynchronous operation:
    context.perform {
        do {
            let persons = try fetchRequest.execute()
            //success - return array of persons
            completion(persons)
        } catch {
            //error - return nil
            completion(nil)
        }

    }

}
</code>```

Calling the above :

```<code>//fetch person with specific id:
let personID: Int = 2
fetchPerson(withID: personID, context: persistentContainer.viewContext) { (persons: [Person]?) in
    if persons != nil {

        print("Fetching person with personID: \(personID)")
        for person in persons! {
            print("Person: \(person.objectID) - \(person.firstName!) \(person.lastName!)")
        }

    }
}
</code>```

答: You can fetch with objectID by using the predicate "self == %@", objectID. An objectID is property of a managedObject and its type is NSManagedObjectID not an Int.  In general it is better to create and manage your own objectId. I generally use UUID strings.

Body:
I have a simple Person entity in Core Data, I noticed that when adding data, each row is auto generated a unique PK called objectID

I wish to retrieve the records using the objectID but I am getting the following error:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'keypath objectID not found in
  entity < NSSQLEntity Person id=2 >'

func fetchPerson(withID personID: Int,
                 context: NSManagedObjectContext,
                 completion: @escaping ([Person]?) -> Void) {

    let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()

    let predicate = NSPredicate(format: "\(#keyPath(Person.objectID)) == \(personID)")
    fetchRequest.predicate = predicate

    //perform aynchronous operation:
    context.perform {
        do {
            let persons = try fetchRequest.execute()
            //success - return array of persons
            completion(persons)
        } catch {
            //error - return nil
            completion(nil)
        }

    }

}

Calling the above :

//fetch person with specific id:
let personID: Int = 2
fetchPerson(withID: personID, context: persistentContainer.viewContext) { (persons: [Person]?) in
    if persons != nil {

        print("Fetching person with personID: \(personID)")
        for person in persons! {
            print("Person: \(person.objectID) - \(person.firstName!) \(person.lastName!)")
        }

    }
}


问:
Angular way to capture Id if child being clicked
I'm new to Angular 1.0 and I'm coming from jQuery backgroud.

Let's say I have following HTML :

```<code><div id="filters">
    <div id="filter1">Filter 1</div>
    <div id="filter2">Filter 2</div>
    <div id="filter3">Filter 3</div>
    <div id="filter4">Filter 4</div>
</div>
</code>```

Now I want to have a function which will return id of child element being clicked.
What could be the Angular way to best implement the following jQuery code :

```<code>$('#filters div').on('click', function() {
  alert($(this).attr("id"));
});
</code>```

答:
In you angularJs controller define a function that gets an event and specify ng-click directive on the divs like

```<code><div id="filters">
    <div id="filter1" data-ng-click="ShowId($event)">Filter 1</div>
    <div id="filter2" data-ng-click="ShowId($event)">Filter 2</div>
    <div id="filter3" data-ng-click="ShowId($event)">Filter 3</div>
    <div id="filter4" data-ng-click="ShowId($event)">Filter 4</div>
</div>
</code>```

Controller:

```<code>$scope.ShowId = function(event)
{
   alert(event.target.id);
};
</code>```

Body:
I'm new to Angular 1.0 and I'm coming from jQuery backgroud.

Let's say I have following HTML :

Filter 1

Filter 2

Filter 3

Filter 4

Now I want to have a function which will return id of child element being clicked.
What could be the Angular way to best implement the following jQuery code :

$('#filters div').on('click', function() {
  alert($(this).attr("id"));
});

Body:
In you angularJs controller define a function that gets an event and specify ng-click directive on the divs like

<div id="filters">
    <div id="filter1" data-ng-click="ShowId($event)">Filter 1</div>
    <div id="filter2" data-ng-click="ShowId($event)">Filter 2</div>
    <div id="filter3" data-ng-click="ShowId($event)">Filter 3</div>
    <div id="filter4" data-ng-click="ShowId($event)">Filter 4</div>
</div>

Controller:

$scope.ShowId = function(event)
{
   alert(event.target.id);
};


问:
JSP and Spring Application
In our spring Application in one of the JSP pages, we have a link

```<code><link rel="stylesheet" href="<%=request.getContextPath()%>/css/bootstrap.min.css"></link>
</code>```

When we run the Project in local environment css works but it does not work in different environment

In the other environment CSS URL being

```<code><link rel="stylesheet" href="/myapp/css/jquery-ui.css">
</code>```

when we remove the App name(request.getContextPath()) below this

```<code><link rel="stylesheet" href="/css/jquery-ui.css">
</code>```

The css works in the other environment.

***1. ***In Local System, the Below URL is Working perfectly.******

```<code> <link rel="stylesheet" href="<%request.getContextPath()%>/css/bootstrap.min.css"></link>
</code>```

When we remove the ContexPath() means the CSS didn't work

```<code><link rel="stylesheet" href="/css/bootstrap.min.css"></link>
</code>```

How to handle this issues in local and other environment?

答:
try this</p>

```<code><link type="text/css" href="<%=request.getContextPath() %>/resources/css/main.css" rel="stylesheet"/>
</code>```

Title: JSP and Spring Application

Body:
In our spring Application in one of the JSP pages, we have a link

<link rel="stylesheet" href="<%=request.getContextPath()%>/css/bootstrap.min.css"></link>

When we run the Project in local environment css works but it does not work in different environment

In the other environment CSS URL being

<link rel="stylesheet" href="/myapp/css/jquery-ui.css">

when we remove the App name(request.getContextPath()) below this

<link rel="stylesheet" href="/css/jquery-ui.css">

The css works in the other environment.

***1. ***In Local System, the Below URL is Working perfectly.******

 <link rel="stylesheet" href="<%request.getContextPath()%>/css/bootstrap.min.css"></link>

When we remove the ContexPath() means the CSS didn't work

<link rel="stylesheet" href="/css/bootstrap.min.css"></link>

How to handle this issues in local and other environment?

Body:
try this

<link type="text/css" href="<%=request.getContextPath() %>/resources/css/main.css" rel="stylesheet"/>


问:
$ionicSlideBoxDelegate.enableSlide(false) not working on IOS
I have a slide box and in my controller I placed this to prevent the slide box labels from sliding left and right : </p>

```<code>  $timeout(function() {
    return $ionicSlideBoxDelegate.enableSlide(false);
  }, 1);
</code>```

<p>it works on Android, but not on IOS. Any suggestions? </p>

答:
I'm using this one sliding controller left or right images.

```<code>$ionicModal.fromTemplateUrl('image-modal.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {
    $scope.modal = modal;
  });

  $scope.openModal = function(galryPubId) {
    $ionicSlideBoxDelegate.slide(galryPubId);
    $scope.modal.show();
  };

  $scope.closeModal = function() {
    $scope.modal.hide();
  };

  // Cleanup the modal when we're done with it!
  $scope.$on('$destroy', function() {
    $scope.modal.remove();
  });
  // Execute action on hide modal
  $scope.$on('modal.hide', function() {
    // Execute action
  });
  // Execute action on remove modal
  $scope.$on('modal.removed', function() {
    // Execute action
  });
  $scope.$on('modal.shown', function() {
    console.log('Modal is shown!');
  });

  // Call this functions if you need to manually control the slides
  $scope.next = function() {
    $ionicSlideBoxDelegate.next();
  };

  $scope.previous = function() {
    $ionicSlideBoxDelegate.previous();
  };

  $scope.goToSlide = function(index) {
    $scope.modal.show();
    $ionicSlideBoxDelegate.slide(index);
  }

  // Called each time the slide changes
  $scope.slideChanged = function(index) {
    $scope.slideIndex = index;
  };
</code>```

It's work for both the platform Android / iOS.

Body:
I have a slide box and in my controller I placed this to prevent the slide box labels from sliding left and right :

  $timeout(function() {
    return $ionicSlideBoxDelegate.enableSlide(false);
  }, 1);

it works on Android, but not on IOS. Any suggestions?

Body:
I'm using this one sliding controller left or right images.

$ionicModal.fromTemplateUrl('image-modal.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {
    $scope.modal = modal;
  });

  $scope.openModal = function(galryPubId) {
    $ionicSlideBoxDelegate.slide(galryPubId);
    $scope.modal.show();
  };

  $scope.closeModal = function() {
    $scope.modal.hide();
  };

  // Cleanup the modal when we're done with it!
  $scope.$on('$destroy', function() {
    $scope.modal.remove();
  });
  // Execute action on hide modal
  $scope.$on('modal.hide', function() {
    // Execute action
  });
  // Execute action on remove modal
  $scope.$on('modal.removed', function() {
    // Execute action
  });
  $scope.$on('modal.shown', function() {
    console.log('Modal is shown!');
  });

  // Call this functions if you need to manually control the slides
  $scope.next = function() {
    $ionicSlideBoxDelegate.next();
  };

  $scope.previous = function() {
    $ionicSlideBoxDelegate.previous();
  };

  $scope.goToSlide = function(index) {
    $scope.modal.show();
    $ionicSlideBoxDelegate.slide(index);
  }

  // Called each time the slide changes
  $scope.slideChanged = function(index) {
    $scope.slideIndex = index;
  };

It's work for both the platform Android / iOS.


问:
Imagebutton.setImageURI(uri) doesn't work
now my problem is that:
This is a workaround for Onclcick an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

```<code>private ImageButton mImageSelect;
private static  final int GALLERY_REQUEST =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mImageSelect=(ImageButton) findViewById(R.id.imageselect);
    mImageSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // super.onActivityResult(requestCode, resultCode, data);

    if(requestCode== GALLERY_REQUEST && resultCode==RESULT_OK){
        Uri selectedImageUri=data.getData();
        if (null != selectedImageUri) {

            mImageSelect.setImageURI(selectedImageUri);
            Toast.makeText(PostActivity.this, "Image Selected", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(PostActivity.this,"Image Not Selected",Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

答:
Try</p>

```<code>    mImageSelect.setImageURI(Uri.parse(data.getData());
</code>```

Body:
now my problem is that:
This is a workaround for Onclcick an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

private ImageButton mImageSelect;
private static  final int GALLERY_REQUEST =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mImageSelect=(ImageButton) findViewById(R.id.imageselect);
    mImageSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // super.onActivityResult(requestCode, resultCode, data);

    if(requestCode== GALLERY_REQUEST && resultCode==RESULT_OK){
        Uri selectedImageUri=data.getData();
        if (null != selectedImageUri) {

            mImageSelect.setImageURI(selectedImageUri);
            Toast.makeText(PostActivity.this, "Image Selected", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(PostActivity.this,"Image Not Selected",Toast.LENGTH_SHORT).show();
        }
    }
}

Body:
Try

    mImageSelect.setImageURI(Uri.parse(data.getData());


问:
Java android ContextCompat don't have a method checkSelfPermission
Hi I have an old project in eclipse and I when I try checkSelfPermission like this :

```<code> ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
</code>```

I don't have a method checkSelfPermission on ContextCompat

答:
Replace your code with:

ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION);

and replace the import line

import android.support.v4.app.ContextCompat

with

import android.support.v4.app.ActivityCompat

Body:
Hi I have an old project in eclipse and I when I try checkSelfPermission like this :

 ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);

I don't have a method checkSelfPermission on ContextCompat


问:
Selenium WebDriver typing very slow in text field on IE browser
I'm running one of my scripts on IE 11 browser with Selenium 2.43.1
when the script types in text field using following:

```<code>element.sendKeys("string");
</code>```

In IE browser, I can see that one character of string is typed in text field and it waits for 1-2 seconds before typing next character. Means for typing one character it's taking 1-2 seconds.

Why is typing so slow with IE?

Is there any alternate way to speed up typing?

答: You can change to 32 bit version,it will be speed compare to 64 bit.</p>

Body:
I'm running one of my scripts on IE 11 browser with Selenium 2.43.1
when the script types in text field using following:

element.sendKeys("string");

In IE browser, I can see that one character of string is typed in text field and it waits for 1-2 seconds before typing next character. Means for typing one character it's taking 1-2 seconds.

Why is typing so slow with IE?

Is there any alternate way to speed up typing?


问:
Call MVC web API controller method from client
I am trying to consume/call an MVC Web API controller method, which will be used to upload a file. I am struggling to call it from my MVC controller.

Here's my code for the API Controller

```<code>public class ImportController : ApiController
{
    [HttpPost]
    public bool PutImportFile(byte[] fileToBeImported, string nameOfTheFileToBeImported)
    {
        // I am doing file saving stuff here
    }
}
</code>```

I have tested the file saving part by changing the method to HttpGet and its working when I called it directly from the browser. I removed the parameters for that.

However, I am not able to figure out how to call it from a client.

I have tried below.

```<code>public class ImportFileModel
{
    public byte[] FileToBeImported { get; set; }

    public string NameOfTheFileToBeImported { get; set; }
}
</code>```

The below code will accept a file from the browser uploaded by user and post it to the API controller to save the file.

```<code>[HttpPost]
public async Task<JsonResult> Upload()
{
    byte[] file;
    string fileName = string.Empty;

    if (Request.Files.Count > 0)
    {
        try
        {
            fileName = Request.Files[0].FileName;

            using (MemoryStream ms = new MemoryStream())
            {
                Request.Files[0].InputStream.CopyTo(ms);
                file = ms.ToArray();
            }

            //To do: get url from configuration
            string url = "http://localhost:(port)/api/Import/PutImportFile";

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/bson"));

                ImportFileModel request = new ImportFileModel
                {
                    FileToBeImported = file,
                    NameOfTheFileToBeImported = fileName
                };

                MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                var result = await client.PostAsync(url, request, bsonFormatter);

                HttpResponseMessage response = result.EnsureSuccessStatusCode();
            }
        }
        catch (Exception ex)
        {
            // exception handling here
        }
    }

    return Json(true, JsonRequestBehavior.AllowGet);
}
</code>```

It ends up in an exception at the last line.

```<code>HttpResponseMessage response = result.EnsureSuccessStatusCode();
</code>```

Throwing 404 not found error.

I have also tried the same from a console application using HttpWebRequest. It also throws the same error.

答:
Your Web API method PutImportFile is setup to receive two values, not a single model; hence, your HttpClient call is not recognized (no matching route found). Change your Web API method to receive a model:

```<code>public class ImportController : ApiController
{
    [HttpPost]
    public bool PutImportFile(ImportFileModel fileInfo)
    {
        //Your code to save the file...
    }
}
</code>```

Body:
I am trying to consume/call an MVC Web API controller method, which will be used to upload a file. I am struggling to call it from my MVC controller.

Here's my code for the API Controller

public class ImportController : ApiController
{
    [HttpPost]
    public bool PutImportFile(byte[] fileToBeImported, string nameOfTheFileToBeImported)
    {
        // I am doing file saving stuff here
    }
}

I have tested the file saving part by changing the method to HttpGet and its working when I called it directly from the browser. I removed the parameters for that.

However, I am not able to figure out how to call it from a client.

I have tried below.

public class ImportFileModel
{
    public byte[] FileToBeImported { get; set; }

    public string NameOfTheFileToBeImported { get; set; }
}

The below code will accept a file from the browser uploaded by user and post it to the API controller to save the file.

[HttpPost]
public async Task<JsonResult> Upload()
{
    byte[] file;
    string fileName = string.Empty;

    if (Request.Files.Count > 0)
    {
        try
        {
            fileName = Request.Files[0].FileName;

            using (MemoryStream ms = new MemoryStream())
            {
                Request.Files[0].InputStream.CopyTo(ms);
                file = ms.ToArray();
            }

            //To do: get url from configuration
            string url = "http://localhost:(port)/api/Import/PutImportFile";

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/bson"));

                ImportFileModel request = new ImportFileModel
                {
                    FileToBeImported = file,
                    NameOfTheFileToBeImported = fileName
                };

                MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
                var result = await client.PostAsync(url, request, bsonFormatter);

                HttpResponseMessage response = result.EnsureSuccessStatusCode();
            }
        }
        catch (Exception ex)
        {
            // exception handling here
        }
    }

    return Json(true, JsonRequestBehavior.AllowGet);
}

It ends up in an exception at the last line.

HttpResponseMessage response = result.EnsureSuccessStatusCode();

Throwing 404 not found error.

I have also tried the same from a console application using HttpWebRequest. It also throws the same error.

Body:
Your Web API method PutImportFile is setup to receive two values, not a single model; hence, your HttpClient call is not recognized (no matching route found). Change your Web API method to receive a model:

public class ImportController : ApiController
{
    [HttpPost]
    public bool PutImportFile(ImportFileModel fileInfo)
    {
        //Your code to save the file...
    }
}


问:
Enumerate or list all variables in a program of [your favorite language here]
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:

```
#!/usr/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a",
        "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue
```

which will output something like:

```
__builtins__ is <type 'str'> and is equal to  <module '__builtin__' (built-in)>
__doc__ is <type 'str'> and is equal to  None
__file__ is <type 'str'> and is equal to  ./foo.py
__name__ is <type 'str'> and is equal to  __main__
foo1 is <type 'str'> and is equal to  Hello world
foo2 is <type 'str'> and is equal to  bar
foo3 is <type 'str'> and is equal to  {'1': 'a', '2': 'b'}
foo4 is <type 'str'> and is equal to  1+1
```

I have so far found a partial way in PHP (courtesy of link text) but it only lists all variables and their types, not the contents:

```
<?php
// create a few variables
$bar = 'foo';
$foo ='bar';
// create a new array object
$arrayObj = new ArrayObject(get_defined_vars());
// loop over the array object and echo variables and values
for($iterator = $arrayObj->getIterator(); $iterator->valid(); $iterator->next())
        {
        echo $iterator->key() . ' => ' . $iterator->current() . '<br />';
        }
?>
```

So I put it to you: how do you list all variables and their contents in your favorite language?

Edit by VonC: I propose this question follows the spirit of a little "code-challenge".

If you do not agree, just edit and remove the tag and the link.

答:
This is what it would look like in Ruby:

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

foo1 = 'Hello world'
foo2 = 'bar'
foo3 = { '1' => 'a', '2' => 'b' }
foo4 = '1+1'

b = binding
local_variables.each do |var|
  puts "#{var} is #{var.class} and is equal to #{b.local_variable_get(var).inspect}"
end
</code>```

which will output

```foo1 is String and is equal to "Hello world"
foo2 is String and is equal to "bar"
foo3 is String and is equal to {"1"=>"a", "2"=>"b"}
foo4 is String and is equal to "1+1"```

However, didn't you mean to output the type of object the variable references instead of the type used to represent the variable identifier? IOW, the type of foo3 should be Hash (or dict) instead of String, right? In that case, the code would be

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

foo1 = 'Hello world'
foo2 = 'bar'
foo3 = { '1' => 'a', '2' => 'b' }
foo4 = '1+1'

b = binding
local_variables.each do |var|
  val = b.local_variable_get(var)
  puts "#{var} is #{val.class} and is equal to #{val.inspect}"
end
</code>```

and the result is

```foo1 is String and is equal to "Hello world"
foo2 is String and is equal to "bar"
foo3 is Hash and is equal to {"1"=>"a", "2"=>"b"}
foo4 is String and is equal to "1+1"```

OwnerDisplayName: Kurt

Body:
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:

#!/usr/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a",
        "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue

which will output something like:

__builtins__ is <type 'str'> and is equal to  <module '__builtin__' (built-in)>
__doc__ is <type 'str'> and is equal to  None
__file__ is <type 'str'> and is equal to  ./foo.py
__name__ is <type 'str'> and is equal to  __main__
foo1 is <type 'str'> and is equal to  Hello world
foo2 is <type 'str'> and is equal to  bar
foo3 is <type 'str'> and is equal to  {'1': 'a', '2': 'b'}
foo4 is <type 'str'> and is equal to  1+1

I have so far found a partial way in PHP (courtesy of link text) but it only lists all variables and their types, not the contents:

<?php
// create a few variables
$bar = 'foo';
$foo ='bar';
// create a new array object
$arrayObj = new ArrayObject(get_defined_vars());
// loop over the array object and echo variables and values
for($iterator = $arrayObj->getIterator(); $iterator->valid(); $iterator->next())
        {
        echo $iterator->key() . ' => ' . $iterator->current() . '
';
        }
?>

So I put it to you: how do you list all variables and their contents in your favorite language?

Edit by VonC: I propose this question follows the spirit of a little "code-challenge".

If you do not agree, just edit and remove the tag and the link.

LastEditorDisplayName: VonC

Body:
This is what it would look like in Ruby:

#!/usr/bin/env ruby

foo1 = 'Hello world'
foo2 = 'bar'
foo3 = { '1' => 'a', '2' => 'b' }
foo4 = '1+1'

b = binding
local_variables.each do |var|
  puts "#{var} is #{var.class} and is equal to #{b.local_variable_get(var).inspect}"
end

which will output

foo1 is String and is equal to "Hello world"
foo2 is String and is equal to "bar"
foo3 is String and is equal to {"1"=>"a", "2"=>"b"}
foo4 is String and is equal to "1+1"

However, didn't you mean to output the type of object the variable references instead of the type used to represent the variable identifier? IOW, the type of foo3 should be Hash (or dict) instead of String, right? In that case, the code would be

#!/usr/bin/env ruby

foo1 = 'Hello world'
foo2 = 'bar'
foo3 = { '1' => 'a', '2' => 'b' }
foo4 = '1+1'

b = binding
local_variables.each do |var|
  val = b.local_variable_get(var)
  puts "#{var} is #{val.class} and is equal to #{val.inspect}"
end

and the result is

foo1 is String and is equal to "Hello world"
foo2 is String and is equal to "bar"
foo3 is Hash and is equal to {"1"=>"a", "2"=>"b"}
foo4 is String and is equal to "1+1"

OwnerDisplayName: Jörg W Mittag


问:
Safari browser - Mac vs Windows vs iOS
Can anyone let me know what is the difference between testing a Safari 5 in Windows vs Mac? Are there significant changes in how the page is rendered between windows vs Mac for the same version of Safari? If I test a page in Windows Safari, can I expect the page works exactly same in Mac Safari as long as Safari version matches?

Thanks

答: i notice few thing in windows safari and mac safari,when we choose an image in windows safari then its not display as preview but in mac safari its display as preview before upload.so File reader api is not supporting blog type.</p>

Title: Safari browser - Mac vs Windows vs iOS


问:
Changing background colour of specific select2 through javascript
In a web form, I'm using two select2 control at two panel each.

I wish to change only one of the select2's background colour when it hit certain condition through javascript else it will remain its original colour.

How can I accomplish that?

I am at the stage where the css code below I found is able to modify the select2 to the result I want.

```<code>       .select2-container .select2-selection{
        background: yellow;
        }
</code>```

Any help is much appreciated.

Edited:

Adding some part of my code:

CSS

```<code>    .select2-container {
        position: relative;
        z-index: 2;
        float: left;
        margin-bottom: 0;
        display: table;
        table-layout: fixed;
        font-size: smaller;
    }
</code>```

Markup

```<code><div class="container-fluid">
    <div class="col-md-7">
        <table>
           <tr>
                 <td>
                     <select id="ddl_Select2ONE" runat="server" class="form-control select"></select>
                 </td>
           </tr>
        </table>
    </div>
    <div class="col-md-5">
        <table>
           <tr>
                 <td>
                     <select id="ddl_Select2TWO" runat="server" class="form-control select"></select>
                 </td>
           </tr>
        </table>
    </div>
</div>
</code>```

Javascript

```<code>pageLoad(){
  configureSelect2()
}

configureSelect2(){
    if(hf_value.value == "1"){
        //Change only ddl_Select2ONE to yellow background
    }
    else{
        //Change only ddl_Select2ONE to original background
    }
}
</code>```

Then I will perform some checking on javascript's pageload when it check a hidden field value for conditional enable.

答:
Try this

function declaration syntax was wrong.

use with classList function

```<code>//add in your js

        function pageLoad() {
          configureSelect2()
        }

        function configureSelect2() {
          if (hf_value.value == "1") {
        document.getElementById("ddl_Select2ONE").classList.add("yellow");
          } else {
           document.getElementById("ddl_Select2ONE").classList.remove("yellow");
          }
        }

 //add in your css
        .yellow{
        background-color:yellow !important;
        }
</code>```

Body:
In a web form, I'm using two select2 control at two panel each.

I wish to change only one of the select2's background colour when it hit certain condition through javascript else it will remain its original colour.

How can I accomplish that?

I am at the stage where the css code below I found is able to modify the select2 to the result I want.

       .select2-container .select2-selection{
        background: yellow;
        }

Any help is much appreciated.

Edited:

Adding some part of my code:

CSS

    .select2-container {
        position: relative;
        z-index: 2;
        float: left;
        margin-bottom: 0;
        display: table;
        table-layout: fixed;
        font-size: smaller;
    }

Markup

                     <select id="ddl_Select2ONE" runat="server" class="form-control select"></select>

                     <select id="ddl_Select2TWO" runat="server" class="form-control select"></select>

Javascript

pageLoad(){
  configureSelect2()
}

configureSelect2(){
    if(hf_value.value == "1"){
        //Change only ddl_Select2ONE to yellow background
    }
    else{
        //Change only ddl_Select2ONE to original background
    }
}

Then I will perform some checking on javascript's pageload when it check a hidden field value for conditional enable.

Body:
Try this

function declaration syntax was wrong.

use with classList function

//add in your js

        function pageLoad() {
          configureSelect2()
        }

        function configureSelect2() {
          if (hf_value.value == "1") {
        document.getElementById("ddl_Select2ONE").classList.add("yellow");
          } else {
           document.getElementById("ddl_Select2ONE").classList.remove("yellow");
          }
        }

 //add in your css
        .yellow{
        background-color:yellow !important;
        }


问:
How can I use session in a library in CodeIgniter?
I want to check if user is logged in CodeIgniter by using my library in the controller's constructor.

This is my library:

```<code>class Administrator_libs {

    public function validate_authen(){
        if( $this->session->userdata('user_authen') ){
            redirect(base_url().'admin/login/');
        }
    }
}
</code>```

And this is my controller:

```<code>class Administrator extends CI_Controller {

    public function __construct(){
        parent::__construct();
        $this->load->library('administrator_libs');
        $this->administrator_libs->validate_authen();
        $this->load->model('mod_menu');
    }
}
</code>```

But I get this error message:

```<code>Undefined property: Administrator_libs::$session
</code>```

How can I use session in a library in CodeIgniter?

答:
You should simply go to application/autoload.php and add your autoload package which should look like somewhat like this : $autoload['packages'] = array('database','form_validation','session','email');

you can see there is session package that i added in my packages. Now coming to your constructor you should load this package by adding this : $this->load->library("session");

Body:
I want to check if user is logged in CodeIgniter by using my library in the controller's constructor.

This is my library:

class Administrator_libs {

    public function validate_authen(){
        if( $this->session->userdata('user_authen') ){
            redirect(base_url().'admin/login/');
        }
    }
}

And this is my controller:

class Administrator extends CI_Controller {

    public function __construct(){
        parent::__construct();
        $this->load->library('administrator_libs');
        $this->administrator_libs->validate_authen();
        $this->load->model('mod_menu');
    }
}

But I get this error message:

Undefined property: Administrator_libs::$session

How can I use session in a library in CodeIgniter?


问:
drawing cache returns the same Image
i have problem with frame layout drawing cache.
i capture the video from camera and display it in frame layout.
i want to read this image(s) and send it to another client with TCP or UDP.
now the problem is the cache dosent update and i have the same image (complete black image) always
here is my code:

```<code>selfImage.setDrawingCacheEnabled(true);
selfImage.buildDrawingCache();
mainImage = selfImage.getDrawingCache();
Bitmap bmp = mainImage.copy(Bitmap.Config.ARGB_8888,false);
streamImage.reset();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, streamImage);
Bitmap temp = bmp;
runOnUiThread(new uiInterface(12, temp));
sendVideo(streamImage);
selfImage.destroyDrawingCache();
mainImage.recycle();
selfImage.setDrawingCacheEnabled(false);
</code>```

self image is my frame layout!
please help me.
thanks

答:
I used this code. It works in my case.

setDrawingCacheEnabled(true);
destroyDrawingCache();
return getDrawingCache();

Title: drawing cache returns the same Image

Body:
i have problem with frame layout drawing cache.
i capture the video from camera and display it in frame layout.
i want to read this image(s) and send it to another client with TCP or UDP.
now the problem is the cache dosent update and i have the same image (complete black image) always
here is my code:

selfImage.setDrawingCacheEnabled(true);
selfImage.buildDrawingCache();
mainImage = selfImage.getDrawingCache();
Bitmap bmp = mainImage.copy(Bitmap.Config.ARGB_8888,false);
streamImage.reset();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, streamImage);
Bitmap temp = bmp;
runOnUiThread(new uiInterface(12, temp));
sendVideo(streamImage);
selfImage.destroyDrawingCache();
mainImage.recycle();
selfImage.setDrawingCacheEnabled(false);

self image is my frame layout!
please help me.
thanks


答:
Easiest way to do is create an array and loop it through the DOM using ng-repeat then you can pass the object as parameter to click function and get the id

```<code><div id="filters">
    <div ng-click="check(item)" ng-repeat="item in arr" id="{{item.id}}">{{item.name}}</div>
</div>
</code>```

sample array

```<code>[{"name":"Filter 1","id":"filter1"},{"name":"Filter 2","id":"filter2"},{"name":"Filter 3","id":"filter3"},{"name":"Filter 4","id":"filter4"}]
</code>```

if you don't want to use the ng repeat then i suggest pass the $event.target as the parameter to the click event

```<code><div id="filters">
    <div id="filter1" ng-click="getID($event.target)">Filter 1</div>
    <div id="filter2" ng-click="getID($event.target)">Filter 2</div>
    <div id="filter3" ng-click="getID($event.target)">Filter 3</div>
    <div id="filter4" ng-click="getID($event.target)">Filter 4</div>
</div>
</code>```

The function

```<code>$scope.getID = function(item){
   console.log(item.id)
};
</code>```

Demo

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.arr = [{"name":"Filter 1","id":"filter1"},{"name":"Filter 2","id":"filter2"},{"name":"Filter 3","id":"filter3"},{"name":"Filter 4","id":"filter4"}]

$scope.check = function(item){
    console.log(item.id)
}

$scope.getID = function(item)
{
    console.log(item.id)
};
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">

<p> using ng repeat </p>
 <div id="filters">
    <div ng-click="check(item)" ng-repeat="item in arr" id="{{item.id}}">{{item.name}}</div>
</div>
<br>

<p> using $event </p>
<div id="filters">
    <div id="filter1" ng-click="getID($event.target)">Filter 1</div>
    <div id="filter2" ng-click="getID($event.target)">Filter 2</div>
    <div id="filter3" ng-click="getID($event.target)">Filter 3</div>
    <div id="filter4" ng-click="getID($event.target)">Filter 4</div>
</div>

</div></code>```

Title: Angular way to capture Id if child being clicked

Body:
I'm new to Angular 1.0 and I'm coming from jQuery backgroud.

Let's say I have following HTML :

Filter 1

Filter 2

Filter 3

Filter 4

Now I want to have a function which will return id of child element being clicked.
What could be the Angular way to best implement the following jQuery code :

$('#filters div').on('click', function() {
  alert($(this).attr("id"));
});

Body:
Easiest way to do is create an array and loop it through the DOM using ng-repeat then you can pass the object as parameter to click function and get the id

<div id="filters">
    <div ng-click="check(item)" ng-repeat="item in arr" id="{{item.id}}">{{item.name}}</div>
</div>

sample array

[{"name":"Filter 1","id":"filter1"},{"name":"Filter 2","id":"filter2"},{"name":"Filter 3","id":"filter3"},{"name":"Filter 4","id":"filter4"}]

if you don't want to use the ng repeat then i suggest pass the $event.target as the parameter to the click event

<div id="filters">
    <div id="filter1" ng-click="getID($event.target)">Filter 1</div>
    <div id="filter2" ng-click="getID($event.target)">Filter 2</div>
    <div id="filter3" ng-click="getID($event.target)">Filter 3</div>
    <div id="filter4" ng-click="getID($event.target)">Filter 4</div>
</div>

The function

$scope.getID = function(item){
   console.log(item.id)
};

Demo

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.arr = [{"name":"Filter 1","id":"filter1"},{"name":"Filter 2","id":"filter2"},{"name":"Filter 3","id":"filter3"},{"name":"Filter 4","id":"filter4"}]

$scope.check = function(item){
    console.log(item.id)
}

$scope.getID = function(item)
{
    console.log(item.id)
};
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">

<p> using ng repeat </p>
 <div id="filters">
    <div ng-click="check(item)" ng-repeat="item in arr" id="{{item.id}}">{{item.name}}</div>
</div>
<br>

<p> using $event </p>
<div id="filters">
    <div id="filter1" ng-click="getID($event.target)">Filter 1</div>
    <div id="filter2" ng-click="getID($event.target)">Filter 2</div>
    <div id="filter3" ng-click="getID($event.target)">Filter 3</div>
    <div id="filter4" ng-click="getID($event.target)">Filter 4</div>
</div>

</div>


问:
WSO2 Identity Server dashboard widgets are empty
I am trying to install the WSO2 Identity Server and run into the problem which I cannot resolve myself. Unfortunately Google search does not help at all. So the only hope is on the community here.

My setup: standalone WSO2IS behind apache2 reverse proxy. Software version 5.3.0; Java version "1.8.0_121"; OS: Debian 9.0 (kernel 4.9.0-1-amd64)

There are no problems with logging into the user dashboard, but trying to access the widgets gives empty pages. The behavior is exactly the same as reported by https://wso2.org/jira/browse/IDENTITY-4141. It is marked as fixed, but looks like the problem still exists. Or I am doing something wrong.

Could anyone point me where to dig or how to fix this issue?

Thanks.

答:
I had the same problem on the same config however on Debian 8 instead of 9.

My dashboard is now working well behind an apache reverse proxy. I followed the wso2 identity server configuration as described in Isura's Blog without the Nginx config.

In catalina-server.xml I set clientAuth="false" instead of "want", since this produced certificate error. It is behind the proxy, thus I don't see any big security issues.

The apache proxy with the mod_proxy_wstunnel installed has the following config:

```<code>SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
ProxyPreserveHost On

RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*)           wss://identity.local.domain:9443/$1 [P,L]

<Location />
       ProxyPass "https://identity.local.domain:9443/"
       ProxyPassReverse "https://identity.local.domain:9443/"
</Location>
</code>```

Body:
I had the same problem on the same config however on Debian 8 instead of 9.

My dashboard is now working well behind an apache reverse proxy. I followed the wso2 identity server configuration as described in Isura's Blog without the Nginx config.

In catalina-server.xml I set clientAuth="false" instead of "want", since this produced certificate error. It is behind the proxy, thus I don't see any big security issues.

The apache proxy with the mod_proxy_wstunnel installed has the following config:

SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
ProxyPreserveHost On

RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*)           wss://identity.local.domain:9443/$1 [P,L]

<Location />
       ProxyPass "https://identity.local.domain:9443/"
       ProxyPassReverse "https://identity.local.domain:9443/"
</Location>


问:
How to copy EXACT value from UltraGrid cell to Excel
I'm using Infragistics's UltraGrid widget to create Excel-like grid. I am trying to copy value from cell and paste it to Excel. That works fine, except for one minor issue: it copies value that is shown in the cell (Text property), instead of real value contained in the cell (Value property). Is there an option to copy real value, instead of shown value?

I've tried using

```<code>PerformAction(UltraGridAction.Copy, false, false);
</code>```

and looking for some method or way to copy real values, but haven't found none. I've also tried to implement my own copy function, but this creates CSV data, and doesn't copy actual cells.

```<code>void OnExportToClipboardSelectedRows(object sender, EventArgs e)
    {
        List<UltraGridRow> rows = this.Grid.GetAllSelectedRows().ToList();
        Console.WriteLine(rows[0].Cells.Count);

        List<string> newRows = new List<string>();
        if (rows.Count > 0)
        {
            int minRowIndex = -1;
            int maxRowIndex = -1;

            foreach (var row in rows)
            {
                if (row.Index < minRowIndex || minRowIndex == -1)
                    minRowIndex = row.Index;
                if (row.Index > maxRowIndex || maxRowIndex == -1)
                    maxRowIndex = row.Index;
            }

            List<int> selectedCols = new List<int>();
            foreach (var cell in this.Grid.Selected.Cells)
            {
                if (!selectedCols.Contains(cell.Column.Index))
                    selectedCols.Add(cell.Column.Index);
            }

            for (int i = minRowIndex; i <= maxRowIndex; i++)
            {
                List<string> cells = new List<string>();
                foreach (int j in selectedCols)
                {
                    cells.Add(this.Grid.Rows[i].Cells[j].Value.ToString());
                }
                newRows.Add(String.Join("\t", cells));
            }
            Clipboard.SetText(String.Join("\n", newRows));
        }
        else
        {
            MessageBox.Show("No selected rows found.");
        }
    }
</code>```

答:
After exhaustive trial/error attempts I finally come to working solution:

```<code>var selectedCells = this.Grid.Selected.Cells;

// Loop through selected cells and put them in "edit mode" (actually, show plain text)
foreach (var cell in selectedCells)
{
    Console.WriteLine(cell.CellDisplayStyle);
    cell.CellDisplayStyle = CellDisplayStyle.PlainText;
}

// Execute copy command
this.Grid.PerformAction(UltraGridAction.Copy, false, false);

// Loop through selected cells and bring them back to original state
foreach (var cell in selectedCells)
{
    Console.WriteLine(cell.CellDisplayStyle);
    cell.CellDisplayStyle = CellDisplayStyle.Default;
}
</code>```

When CellDisplayStyle is set to PlainText, cell displays actual value, rather then formatted value. In that state, perform Copy and return cells to original state.

Body:
I'm using Infragistics's UltraGrid widget to create Excel-like grid. I am trying to copy value from cell and paste it to Excel. That works fine, except for one minor issue: it copies value that is shown in the cell (Text property), instead of real value contained in the cell (Value property). Is there an option to copy real value, instead of shown value?

I've tried using

PerformAction(UltraGridAction.Copy, false, false);

and looking for some method or way to copy real values, but haven't found none. I've also tried to implement my own copy function, but this creates CSV data, and doesn't copy actual cells.

void OnExportToClipboardSelectedRows(object sender, EventArgs e)
    {
        List<UltraGridRow> rows = this.Grid.GetAllSelectedRows().ToList();
        Console.WriteLine(rows[0].Cells.Count);

        List<string> newRows = new List<string>();
        if (rows.Count > 0)
        {
            int minRowIndex = -1;
            int maxRowIndex = -1;

            foreach (var row in rows)
            {
                if (row.Index < minRowIndex || minRowIndex == -1)
                    minRowIndex = row.Index;
                if (row.Index > maxRowIndex || maxRowIndex == -1)
                    maxRowIndex = row.Index;
            }

            List<int> selectedCols = new List<int>();
            foreach (var cell in this.Grid.Selected.Cells)
            {
                if (!selectedCols.Contains(cell.Column.Index))
                    selectedCols.Add(cell.Column.Index);
            }

            for (int i = minRowIndex; i <= maxRowIndex; i++)
            {
                List<string> cells = new List<string>();
                foreach (int j in selectedCols)
                {
                    cells.Add(this.Grid.Rows[i].Cells[j].Value.ToString());
                }
                newRows.Add(String.Join("\t", cells));
            }
            Clipboard.SetText(String.Join("\n", newRows));
        }
        else
        {
            MessageBox.Show("No selected rows found.");
        }
    }

Body:
After exhaustive trial/error attempts I finally come to working solution:

var selectedCells = this.Grid.Selected.Cells;

// Loop through selected cells and put them in "edit mode" (actually, show plain text)
foreach (var cell in selectedCells)
{
    Console.WriteLine(cell.CellDisplayStyle);
    cell.CellDisplayStyle = CellDisplayStyle.PlainText;
}

// Execute copy command
this.Grid.PerformAction(UltraGridAction.Copy, false, false);

// Loop through selected cells and bring them back to original state
foreach (var cell in selectedCells)
{
    Console.WriteLine(cell.CellDisplayStyle);
    cell.CellDisplayStyle = CellDisplayStyle.Default;
}

When CellDisplayStyle is set to PlainText, cell displays actual value, rather then formatted value. In that state, perform Copy and return cells to original state.


问:
How to fade part of an image
I have a kind of simple donut chart gradually colored. I want this donut be faded depending on a value. For example if the value is 35 then 35 % of my donut would be not faded and 65 % would be faded. I don't want any animation.

This is an example of what I want to achieve :

The code for the donut without the masking feature :

```<code><ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/donut"
        android:layout_alignTop="@+id/imageView"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"/>
</code>```

答:
I don't know android designing but some web design logic may help.
Could you create a non-transparent panel over the image and give it the exact width and height of the image. So when you wish to display 20% of the image, you just giv to the panel 80% and align it properly.

Best regards.

Title: How to fade part of an image

Body:
I have a kind of simple donut chart gradually colored. I want this donut be faded depending on a value. For example if the value is 35 then 35 % of my donut would be not faded and 65 % would be faded. I don't want any animation.

This is an example of what I want to achieve :

The code for the donut without the masking feature :

<ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/donut"
        android:layout_alignTop="@+id/imageView"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"/>


问:
How to align the title in the middle?
I'm working with codepen.io and I am creating a paragraph.
The graph has a title.

The problem is that I want the title center-aligned.It should automatically set the title in the middle, not about editing the value of "x". I can't use CSS to do this, and I believe javascript would do the job.

Here are the one functions I am using to draw the title and the link to my project goes bellow.

```<code>var text = document.createElementNS(svgNS,"text");
    text.setAttributeNS(null, 'x', 100);
    text.setAttributeNS(null, 'y', 15);
    text.textContent = (titel);
document.getElementById("bargraph").appendChild(text);
</code>```

Full code:

codepen.io/Cleanwater/pen/LWQyJm?editors=0010

答:
```<code>var text = document.createElementNS(svgNS,"text");
    text.setAttributeNS(null, 'y', 15);
    text.textContent = (titel);
document.getElementById("bargraph").appendChild(text);
    text.setAttributeNS(null, 'x', 300 / 2 - text.getBBox().width /2);
</code>```

Title: How to align the title in the middle?

Body:
I'm working with codepen.io and I am creating a paragraph.
The graph has a title.

The problem is that I want the title center-aligned.It should automatically set the title in the middle, not about editing the value of "x". I can't use CSS to do this, and I believe javascript would do the job.

Here are the one functions I am using to draw the title and the link to my project goes bellow.

var text = document.createElementNS(svgNS,"text");
    text.setAttributeNS(null, 'x', 100);
    text.setAttributeNS(null, 'y', 15);
    text.textContent = (titel);
document.getElementById("bargraph").appendChild(text);

Full code:

codepen.io/Cleanwater/pen/LWQyJm?editors=0010


问:
[UWP]The storyboard contained in the DataTemplate is not working properly
Clicking on any item will only work on the storyboard of the first item.

You can download the source from the address below.

http://util.aquerytool.com/Download?fileName=ItemStoryboardApp.zip

Thank you for your reply.

```<code><UserControl
    x:Class="ItemStoryboardApp.View.ItemListMVVMLightView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ItemStoryboardApp.View"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:core="using:Microsoft.Xaml.Interactions.Core"
    xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
    xmlns:media="using:Microsoft.Xaml.Interactions.Media"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid x:Name="PART_RootPanel">

        <ItemsControl ItemsSource="{Binding ItemList}" Padding="0,0,0,0">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Foreground="White" Margin="0,0,5,0" Padding="0,0,0,0" Height="40" Command="{Binding DataContext.SelectedItemCommand, ElementName=PART_RootPanel}" CommandParameter="{Binding}" VerticalContentAlignment="Stretch" >
                        <Button.Content>
                            <Grid x:Name="PART_ContinuousDefectPanel" RenderTransformOrigin="0.5, 0.5">
                                <Grid.Resources>
                                    <Storyboard x:Name="SB_ChangedCount">
                                        <DoubleAnimation Storyboard.TargetName="PART_ContinuousDefectPanel" Duration="0:0:0.25" To="1.2" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)" AutoReverse="True" />
                                        <DoubleAnimation Storyboard.TargetName="PART_ContinuousDefectPanel" Duration="0:0:0.25" To="1.2" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)" AutoReverse="True" />
                                    </Storyboard>
                                </Grid.Resources>

                                <Grid.RenderTransform>
                                    <ScaleTransform x:Name="ImageScale" ScaleX="1" ScaleY="1" />
                                </Grid.RenderTransform>

                                <interactivity:Interaction.Behaviors>
                                    <core:DataTriggerBehavior Binding="{Binding IsSelected}" Value="True"  ComparisonCondition="Equal">
                                        <media:ControlStoryboardAction Storyboard="{StaticResource SB_ChangedCount}" />
                                    </core:DataTriggerBehavior>
                                </interactivity:Interaction.Behaviors>

                                <Rectangle Fill="Orange" RadiusX="10" RadiusY="10"/>
                                <StackPanel Orientation="Horizontal" Margin="10,0,10,0" VerticalAlignment="Center">
                                    <TextBlock Text="{Binding ItemName}" />
                                </StackPanel>

                            </Grid>
                        </Button.Content>
                    </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

    </Grid>

</UserControl>

public class ItemListMVVMLightViewModel : ViewModelBase
{
    public ObservableCollection<ItemModel> ItemList
    {
        get { return _itemList; }
        set { _itemList = value; RaisePropertyChanged("ItemList"); }
    }
    ObservableCollection<ItemModel> _itemList = new ObservableCollection<ItemModel>();

    public ICommand SelectedItemCommand { get; private set; }

    public ItemListMVVMLightViewModel()
    {
        InitData();
        InitCommand();
    }

    void InitCommand()
    {
        SelectedItemCommand = new RelayCommand<object>((param) => OnSelectedItemCommand(param));
    }

    void InitData()
    {
        for (int i = 0; i < 10; i++)
        {
            ItemList.Add(new ItemModel() { ItemName = "Name" + i.ToString() });
        }
    }

    void OnSelectedItemCommand(object param)
    {
        if (param == null || (param is ItemModel) == false)
        {
            return;
        }

        foreach (ItemModel i in ItemList)
        {
            i.IsSelected = false;
        }

        ItemModel item = param as ItemModel;
        item.IsSelected = true;
    }

}
</code>```

答:
According to Storyboard class,

TargetNameProperty is used to reference another element by its name.For most animation targeting scenarios you won't need to worry about the influence of XAML namescopes, but you might encounter XAML name resolution issues if you're trying to target template parts, or objects that were created using Load(String) and subsequently added to the object tree. For more info, see XAML namescopes.

Since you're using a storyboard inside a datatemplate, you may encounter XAML name resolution issue. The storyboard always target the first item may lead this issue.

In your code snippet you are using a DataTrigger for trigger the storyboard.   However, it may be a legacy syntax from WPF and early versions of Silverlight prior to VisualStateManager support.  I recommend you to storyboard animations for visual states. The following code may achieve the same result as you want you may reference.  I think you want to animate one item once it selected. I custom the button style to add your animation to the VisualStateManager.

```<code><ItemsControl Padding="0,0,0,0" ItemsSource="{Binding ItemList}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button
                    Height="40"
                    Margin="0,0,5,0"
                    Padding="0,0,0,0"
                    VerticalContentAlignment="Stretch"
                    Foreground="White"
                    Command="{Binding DataContext.SelectedItemCommand, ElementName=PART_RootPanel}"
                    CommandParameter="{Binding}">
                    <Button.Style>
                        <Style TargetType="Button">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="Button">
                                        <Grid x:Name="RootGrid" Background="{TemplateBinding Background}">
                                            <Grid.RenderTransform>
                                                <ScaleTransform
                                                    x:Name="ImageScale"
                                                    ScaleX="1"
                                                    ScaleY="1" />
                                            </Grid.RenderTransform>
                                            <Rectangle
                                                Fill="Orange"
                                                RadiusX="10"
                                                RadiusY="10" />
                                            <StackPanel
                                                Margin="10,0,10,0"
                                                VerticalAlignment="Center"
                                                Orientation="Horizontal">
                                                <TextBlock Text="{Binding ItemName}" />
                                            </StackPanel>
                                            <VisualStateManager.VisualStateGroups>
                                                <VisualStateGroup x:Name="CommonStates">
                                                    <VisualState x:Name="Pressed">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseMediumLowBrush}" />
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <PointerDownThemeAnimation Storyboard.TargetName="RootGrid" />
                                                            <DoubleAnimation
                                                                AutoReverse="True"
                                                                Duration="0:0:0.25"
                                                                Storyboard.TargetName="RootGrid"
                                                                Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"
                                                                To="1.2" />
                                                            <DoubleAnimation
                                                                AutoReverse="True"
                                                                Duration="0:0:0.25"
                                                                Storyboard.TargetName="RootGrid"
                                                                Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)"
                                                                To="1.2" />
                                                        </Storyboard>
                                                    </VisualState>
                                                </VisualStateGroup>
                                            </VisualStateManager.VisualStateGroups>
                                        </Grid>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Button.Style>
                </Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</code>```

Body:
Clicking on any item will only work on the storyboard of the first item.

You can download the source from the address below.

http://util.aquerytool.com/Download?fileName=ItemStoryboardApp.zip

Thank you for your reply.

<UserControl
    x:Class="ItemStoryboardApp.View.ItemListMVVMLightView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ItemStoryboardApp.View"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:core="using:Microsoft.Xaml.Interactions.Core"
    xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
    xmlns:media="using:Microsoft.Xaml.Interactions.Media"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid x:Name="PART_RootPanel">

        <ItemsControl ItemsSource="{Binding ItemList}" Padding="0,0,0,0">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Foreground="White" Margin="0,0,5,0" Padding="0,0,0,0" Height="40" Command="{Binding DataContext.SelectedItemCommand, ElementName=PART_RootPanel}" CommandParameter="{Binding}" VerticalContentAlignment="Stretch" >
                        <Button.Content>
                            <Grid x:Name="PART_ContinuousDefectPanel" RenderTransformOrigin="0.5, 0.5">
                                <Grid.Resources>
                                    <Storyboard x:Name="SB_ChangedCount">
                                        <DoubleAnimation Storyboard.TargetName="PART_ContinuousDefectPanel" Duration="0:0:0.25" To="1.2" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)" AutoReverse="True" />
                                        <DoubleAnimation Storyboard.TargetName="PART_ContinuousDefectPanel" Duration="0:0:0.25" To="1.2" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)" AutoReverse="True" />
                                    </Storyboard>
                                </Grid.Resources>

                                <Grid.RenderTransform>
                                    <ScaleTransform x:Name="ImageScale" ScaleX="1" ScaleY="1" />
                                </Grid.RenderTransform>

                                <interactivity:Interaction.Behaviors>
                                    <core:DataTriggerBehavior Binding="{Binding IsSelected}" Value="True"  ComparisonCondition="Equal">
                                        <media:ControlStoryboardAction Storyboard="{StaticResource SB_ChangedCount}" />
                                    </core:DataTriggerBehavior>
                                </interactivity:Interaction.Behaviors>

                                <Rectangle Fill="Orange" RadiusX="10" RadiusY="10"/>
                                <StackPanel Orientation="Horizontal" Margin="10,0,10,0" VerticalAlignment="Center">
                                    <TextBlock Text="{Binding ItemName}" />
                                </StackPanel>

                            </Grid>
                        </Button.Content>
                    </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

    </Grid>

</UserControl>

public class ItemListMVVMLightViewModel : ViewModelBase
{
    public ObservableCollection<ItemModel> ItemList
    {
        get { return _itemList; }
        set { _itemList = value; RaisePropertyChanged("ItemList"); }
    }
    ObservableCollection<ItemModel> _itemList = new ObservableCollection<ItemModel>();

    public ICommand SelectedItemCommand { get; private set; }

    public ItemListMVVMLightViewModel()
    {
        InitData();
        InitCommand();
    }

    void InitCommand()
    {
        SelectedItemCommand = new RelayCommand<object>((param) => OnSelectedItemCommand(param));
    }

    void InitData()
    {
        for (int i = 0; i < 10; i++)
        {
            ItemList.Add(new ItemModel() { ItemName = "Name" + i.ToString() });
        }
    }

    void OnSelectedItemCommand(object param)
    {
        if (param == null || (param is ItemModel) == false)
        {
            return;
        }

        foreach (ItemModel i in ItemList)
        {
            i.IsSelected = false;
        }

        ItemModel item = param as ItemModel;
        item.IsSelected = true;
    }

}

Body:
According to Storyboard class,

TargetNameProperty is used to reference another element by its name.For most animation targeting scenarios you won't need to worry about the influence of XAML namescopes, but you might encounter XAML name resolution issues if you're trying to target template parts, or objects that were created using Load(String) and subsequently added to the object tree. For more info, see XAML namescopes.

Since you're using a storyboard inside a datatemplate, you may encounter XAML name resolution issue. The storyboard always target the first item may lead this issue.

In your code snippet you are using a DataTrigger for trigger the storyboard.   However, it may be a legacy syntax from WPF and early versions of Silverlight prior to VisualStateManager support.  I recommend you to storyboard animations for visual states. The following code may achieve the same result as you want you may reference.  I think you want to animate one item once it selected. I custom the button style to add your animation to the VisualStateManager.

<ItemsControl Padding="0,0,0,0" ItemsSource="{Binding ItemList}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button
                    Height="40"
                    Margin="0,0,5,0"
                    Padding="0,0,0,0"
                    VerticalContentAlignment="Stretch"
                    Foreground="White"
                    Command="{Binding DataContext.SelectedItemCommand, ElementName=PART_RootPanel}"
                    CommandParameter="{Binding}">
                    <Button.Style>
                        <Style TargetType="Button">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="Button">
                                        <Grid x:Name="RootGrid" Background="{TemplateBinding Background}">
                                            <Grid.RenderTransform>
                                                <ScaleTransform
                                                    x:Name="ImageScale"
                                                    ScaleX="1"
                                                    ScaleY="1" />
                                            </Grid.RenderTransform>
                                            <Rectangle
                                                Fill="Orange"
                                                RadiusX="10"
                                                RadiusY="10" />
                                            <StackPanel
                                                Margin="10,0,10,0"
                                                VerticalAlignment="Center"
                                                Orientation="Horizontal">
                                                <TextBlock Text="{Binding ItemName}" />
                                            </StackPanel>
                                            <VisualStateManager.VisualStateGroups>
                                                <VisualStateGroup x:Name="CommonStates">
                                                    <VisualState x:Name="Pressed">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseMediumLowBrush}" />
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <PointerDownThemeAnimation Storyboard.TargetName="RootGrid" />
                                                            <DoubleAnimation
                                                                AutoReverse="True"
                                                                Duration="0:0:0.25"
                                                                Storyboard.TargetName="RootGrid"
                                                                Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"
                                                                To="1.2" />
                                                            <DoubleAnimation
                                                                AutoReverse="True"
                                                                Duration="0:0:0.25"
                                                                Storyboard.TargetName="RootGrid"
                                                                Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)"
                                                                To="1.2" />
                                                        </Storyboard>
                                                    </VisualState>
                                                </VisualStateGroup>
                                            </VisualStateManager.VisualStateGroups>
                                        </Grid>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Button.Style>
                </Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>


问:
Index was outside the bounds of the array
At the line `If aryTemp(1) < aryTemp2(1) Then the

Index was outside the bounds of the
  array.

error appears. Can't identify why would it be outside array's bounds.
Basically trying to compare Last Names to sort the records and place em back into list box.

A student record looks like this:
FirstName[space]LastName[space]Major[space]Telephone[space]Email[space]GPA

Example: Johny Cake E201 6666666666 me@me.com 1.0

```<code> Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
        ''#load all students into array
        Dim arySort(numberOfRecords) As String
        Dim aryTemp(6) As String
        Dim aryTemp2(6) As String
        For i = 0 To numberOfRecords - 1
            arySort(i) = lstListBox.Items(i)
        Next
        Dim temp As String ''#holds temporary record
        Dim k As Integer
        For i = 0 To arySort.Length - 2
            aryTemp = Split(arySort(i), " ")
            For k = i + 1 To arySort.Length - 1
                aryTemp2 = Split(arySort(k), " ")
                If aryTemp(1) < aryTemp2(1) Then ''# index of 1 refers to last name of a split string
                    temp = arySort(k)
                    arySort(k) = arySort(i)
                    arySort(i) = temp
                End If
            Next
        Next
        lstListBox.Items.Clear()
        numberOfRecords = 0
        isLoaded = False
        For i = 0 To arySort.Length - 1
            lstListBox.Items.Add(arySort(i))
            numberOfRecords += 1
        Next
        currentRecord = 0
        isLoaded = True
    End Sub
</code>```

答:
Arrays in VB.NET are zero-based, so your code is declaring one too many items for each array.  As written, arySort will contain one item for each record in your ListBox, plus one extra, empty item.  That will cause one of your aryTemp2 = Split(arySort(k), " ") calls to split on Nothing, which will leave you without any enough items in the aryTemp2 array to do the comparison with aryTemp.

Corrected code:

```<code>Dim arySort(numberOfRecords - 1) As String
Dim aryTemp(5) As String
Dim aryTemp2(5) As String
</code>```

Body:
At the line `If aryTemp(1) < aryTemp2(1) Then the

Index was outside the bounds of the
  array.

error appears. Can't identify why would it be outside array's bounds.
Basically trying to compare Last Names to sort the records and place em back into list box.

A student record looks like this:
FirstName[space]LastName[space]Major[space]Telephone[space]Email[space]GPA

Example: Johny Cake E201 6666666666 me@me.com 1.0

 Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
        ''#load all students into array
        Dim arySort(numberOfRecords) As String
        Dim aryTemp(6) As String
        Dim aryTemp2(6) As String
        For i = 0 To numberOfRecords - 1
            arySort(i) = lstListBox.Items(i)
        Next
        Dim temp As String ''#holds temporary record
        Dim k As Integer
        For i = 0 To arySort.Length - 2
            aryTemp = Split(arySort(i), " ")
            For k = i + 1 To arySort.Length - 1
                aryTemp2 = Split(arySort(k), " ")
                If aryTemp(1) < aryTemp2(1) Then ''# index of 1 refers to last name of a split string
                    temp = arySort(k)
                    arySort(k) = arySort(i)
                    arySort(i) = temp
                End If
            Next
        Next
        lstListBox.Items.Clear()
        numberOfRecords = 0
        isLoaded = False
        For i = 0 To arySort.Length - 1
            lstListBox.Items.Add(arySort(i))
            numberOfRecords += 1
        Next
        currentRecord = 0
        isLoaded = True
    End Sub

Body:
Arrays in VB.NET are zero-based, so your code is declaring one too many items for each array.  As written, arySort will contain one item for each record in your ListBox, plus one extra, empty item.  That will cause one of your aryTemp2 = Split(arySort(k), " ") calls to split on Nothing, which will leave you without any enough items in the aryTemp2 array to do the comparison with aryTemp.

Corrected code:

Dim arySort(numberOfRecords - 1) As String
Dim aryTemp(5) As String
Dim aryTemp2(5) As String


问:
Regarding RSU address in message
I added the following lines in onData method of my TracIDemoRSU11p.cc file:

```<code>void TraCIDemoRSU11p::onData(WaveShortMessage* wsm) {
    findHost()->getDisplayString().updateWith("r=16,green");

    annotations->scheduleErase(1, annotations->drawLine(wsm->getSenderPos(), mobi->getCurrentPosition(), "blue"));
    static int count=0;
    count++;
    if(count>100)
    {
        wsm->setCount(count);
        sendMessage(wsm->getWsmData());
    }
}
</code>```

What I want is to get the vehicle's address which has sent the data as well.
Also, is there any problem in using the static variables in the method?

I have defined a count variable in wsm message and I want to send the count value along with the vehicleId in the message.

答:
Amending the message definition to include a vehicle id is allowed. So is using static variables in C++. I don't think it is a good idea though.

The static variable will be shared among all instances of that class (that is, across nodes and - possibly - simulation runs). I would recommend using a regular member variable of some class.

Title: Regarding RSU address in message

Body:
I added the following lines in onData method of my TracIDemoRSU11p.cc file:

void TraCIDemoRSU11p::onData(WaveShortMessage* wsm) {
    findHost()->getDisplayString().updateWith("r=16,green");

    annotations->scheduleErase(1, annotations->drawLine(wsm->getSenderPos(), mobi->getCurrentPosition(), "blue"));
    static int count=0;
    count++;
    if(count>100)
    {
        wsm->setCount(count);
        sendMessage(wsm->getWsmData());
    }
}

What I want is to get the vehicle's address which has sent the data as well.
Also, is there any problem in using the static variables in the method?

I have defined a count variable in wsm message and I want to send the count value along with the vehicleId in the message.


问:
Overloaded Equals method and putVal method in HashMap
I have two methods in my Emp class

```<code>class Emp
{
  String empId;
  public boolean equals(Emp e){..}
  public boolean equals(Object o){..}
  public int hashCode(){
  return empId.hashCode();
 }
}
</code>```

Now if a am trying to add Emp objects to a HashSet<Emp>.

If i look at the code of HashMap's putVal method which is used to compare and put values to the set. The code never casts your passed object to java.lang.Object.So every time the equals(Emp) version should get called.

But every time equals(Object o) gets called.I want to know when is this Emp converted to java.lang.Object so that everyTime the equals(Object o) gets called.

Below is the putval snippet i am using:

```<code> final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                        boolean evict) {
   Node<K,V>[] tab; Node<K,V> p; int n, i;
   if ((tab = table) == null || (n = tab.length) == 0)
     n = (tab = resize()).length;
   if ((p = tab[i = (n - 1) & hash]) == null)
     tab[i] = newNode(hash, key, value, null);
   else {
     Node<K,V> e; K k;
     if (p.hash == hash &&
          ((k = p.key) == key || (key != null && key.equals(k))))
       e = p;
     else if (p instanceof TreeNode)
       e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                     ....
    }
</code>```

答: The compiler erases the generic type parameters, so K and V become Object when the code is compiled. Therefore key.equals(k) executes equals(Object o).

Body:
I have two methods in my Emp class

class Emp
{
  String empId;
  public boolean equals(Emp e){..}
  public boolean equals(Object o){..}
  public int hashCode(){
  return empId.hashCode();
 }
}

Now if a am trying to add Emp objects to a HashSet<Emp>.

If i look at the code of HashMap's putVal method which is used to compare and put values to the set. The code never casts your passed object to java.lang.Object.So every time the equals(Emp) version should get called.

But every time equals(Object o) gets called.I want to know when is this Emp converted to java.lang.Object so that everyTime the equals(Object o) gets called.

Below is the putval snippet i am using:

 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                        boolean evict) {
   Node<K,V>[] tab; Node<K,V> p; int n, i;
   if ((tab = table) == null || (n = tab.length) == 0)
     n = (tab = resize()).length;
   if ((p = tab[i = (n - 1) & hash]) == null)
     tab[i] = newNode(hash, key, value, null);
   else {
     Node<K,V> e; K k;
     if (p.hash == hash &&
          ((k = p.key) == key || (key != null && key.equals(k))))
       e = p;
     else if (p instanceof TreeNode)
       e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                     ....
    }


问:
Embed PDF Viewer with annotation like highlight, scribble, add note using PHP
I have a website build on CakePHP framework. I have already integrated Dompdf library for generating PDF from HTML.

And now for viewing the PDF files, I need a pdf reader that will be embedded into the website with limited capabilities so that the files cannot be printed or shared. Ideally, this would be the layout of the reader. The top would show the title of the document and people can highlight, scribble, add note to the document.

答:
Please try out PdfJs

It suits your needs the most and it has good documentation so you could get started quickly