问:
How can I make my icon
s show up next to each other, rather than underneath each other?
I have this

```<code><a href="#"><div class="iconFriends"></div></a>
<a href="#"><div class="iconFavorite"></div></a>
<a href="#"><div class="iconPM"></div></a>
<a href="#"><div class="iconShield"></div></a>
</code>```

and the css for the icons class looks all similiar to this:

```<code>.iconFriends{
background: url(../images/icons/friends_16x16.png) no-repeat;
width: 16px;
height: 16px;
border: none;
}
</code>```

Now the results is that there is like a
 when I do this. But if i remove the div and make a normal  It shows fine. How can i fix this?

答: try giving them all a float:left

Title: How can I make my icon <div>s show up next to each other, rather than underneath each other?

Body:
I have this

and the css for the icons class looks all similiar to this:

.iconFriends{
background: url(../images/icons/friends_16x16.png) no-repeat;
width: 16px;
height: 16px;
border: none;
}

Now the results is that there is like a
 when I do this. But if i remove the div and make a normal  It shows fine. How can i fix this?

Body: try giving them all a float:left


来源: stackexchange

问:
Unable to display dropdown and popover AngularJS
I am new to this, can you help me figure out why my dropdown is not displaying properly and also the popover of the second value of dropdown is not working properly?
I am a bit confuse since it is my first time trying this.
Here is my code

```<code><ul class="nav site-nav">
<li class=flyout>
    <a href=#>Menu</a>

<!-- Flyout -->
<ul class="flyout-content nav stacked">
  <li>
    <div ng-app>
      <div ng-controller="popoverCtrl">
        <a href="#" ng-mouseover="showPopover=true;" ng-mouseleave="showPopover=false;">Real Account <div class="popover" ng-show="showPopover"><span>{{ popover.title }}</span>{{ popover.message }}</div></a>
      </div>
    </div>
  </li>
  <li>
    <div ng-app>
      <div ng-controller="popoverCtrl2">
        <a href="#" ng-mouseover="showPopover2=true;" ng-mouseleave="showPopover2=false;">Practice Account <div class="popover2" ng-show="showPopover2"><span>{{ popover2.title }}</span>{{ popover2.message }}</div></a>
      </div>
    </div>
  </li>

</ul>
</code>```

and my JS

```<code>function popoverCtrl($scope) {

  $scope.showPopover = false;

  $scope.popover = {
    title: 'Title',
    message: 'Message'
  };

}

function popoverCtrl2($scope2) {

  $scope2.showPopover2 = false;

  $scope2.popover2 = {
    title: 'Test',
    message: 'Sample'
  };
}
</code>```

Here is what I have done so far http://jsfiddle.net/fn1aj1e6/

答:
You need to correct below things in your code :

define only 1 ng-app, to the root most HTML element.(in your code
 tag but ideally  tag)

Remove $scope2 from second controller., it should be only $scope.

Working fiddle

ContentLicense: CC BY-SA 3.0

Body:
I am new to this, can you help me figure out why my dropdown is not displaying properly and also the popover of the second value of dropdown is not working properly?
I am a bit confuse since it is my first time trying this.
Here is my code

    Menu

        Real Account
{{ popover.title }}{{ popover.message }}

        Practice Account
{{ popover2.title }}{{ popover2.message }}

and my JS

function popoverCtrl($scope) {

  $scope.showPopover = false;

  $scope.popover = {
    title: 'Title',
    message: 'Message'
  };

}

function popoverCtrl2($scope2) {

  $scope2.showPopover2 = false;

  $scope2.popover2 = {
    title: 'Test',
    message: 'Sample'
  };
}

Here is what I have done so far http://jsfiddle.net/fn1aj1e6/

Body:
You need to correct below things in your code :

define only 1 ng-app, to the root most HTML element.(in your code <ul> tag but ideally <html> tag)

Remove $scope2 from second controller., it should be only $scope.

Working fiddle


问:
How to add and substract 15 minutes from date sql
I have a query to search records depending on latitude longitude and the date.

The query works fine for the same date, but I want to get records which are 15 minutes before the date and 15 minutes after the date.

Working query is this:

```<code>SELECT
   *
FROM post
WHERE st_lati LIKE '19.878454%' AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%' AND ed_longi LIKE '73.791389%'
AND pt_date LIKE '2017-05-30 06:30%'
</code>```

I tried to minus 15 minutes using dateadd function but its giving errors.

my attempt

```<code>SELECT
 *
FROM post
WHERE pt_date DATEADD(minute, -15 * @h - @m, pt_date)
AND st_lati LIKE '19.878454%'
AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%'
AND ed_longi LIKE '73.791389%'
</code>```

I want to get records where pt_date before 15 minutes and after 15 minutes.

答:
Try this:</p>

```<code>SELECT
*
FROM post
WHERE st_lati LIKE '19.878454%'
  AND st_longi LIKE '73.836708%'
  AND ed_lati LIKE '20.012709%'
  AND ed_longi LIKE '73.791389%'
  AND pt_date BETWEEN '2017-05-30 06:30:00' - INTERVAL 15 MINUTE AND
  '2017-05-30 06:30:00' + INTERVAL 15 MINUTE
</code>```

Body:
I have a query to search records depending on latitude longitude and the date.

The query works fine for the same date, but I want to get records which are 15 minutes before the date and 15 minutes after the date.

Working query is this:

SELECT
   *
FROM post
WHERE st_lati LIKE '19.878454%' AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%' AND ed_longi LIKE '73.791389%'
AND pt_date LIKE '2017-05-30 06:30%'

I tried to minus 15 minutes using dateadd function but its giving errors.

my attempt

SELECT
 *
FROM post
WHERE pt_date DATEADD(minute, -15 * @h - @m, pt_date)
AND st_lati LIKE '19.878454%'
AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%'
AND ed_longi LIKE '73.791389%'

I want to get records where pt_date before 15 minutes and after 15 minutes.

Body:
Try this:

SELECT
*
FROM post
WHERE st_lati LIKE '19.878454%'
  AND st_longi LIKE '73.836708%'
  AND ed_lati LIKE '20.012709%'
  AND ed_longi LIKE '73.791389%'
  AND pt_date BETWEEN '2017-05-30 06:30:00' - INTERVAL 15 MINUTE AND
  '2017-05-30 06:30:00' + INTERVAL 15 MINUTE


问:
Convert .csv file into .dbf using Python?
How can I convert a .csv file into .dbf file using a python script? I found this piece of code online but I'm not certain how reliable it is. Are there any modules out there that have this functionality?</p>

答:
Use the csv library to read your data from the csv file.  The third-party dbf  library can write a dbf file for you.

Edit:  Originally, I listed dbfpy, but the library above seems to be more actively updated.

ContentLicense: CC BY-SA 2.5


问:
Creating a struct and a class with the same name
Summary: What happens if you declare a struct and a class with the same name.

Details:

I'm reviewing some code and I saw a warning like this:

```<code>warning: struct 'foo' was previously declared as a class
</code>```

When compiling with clang there were also a couple of places where clang added notes saying:

```<code>foo.h:29:1: note: did you mean struct here?
class foo;
^~~~~
struct
</code>```

Obviously this is not a good coding practice to have a struct and a class with the same name.  It looks like what happened is the developer was writing his own class and used a name that was already in use in another file that he was including and he did not notice that.

However, my question is will the compiler be able to tell the difference between the variables that were declared as class foo and the ones that were struct foo?

Edit:

Actually what was happening was that the developer was using the class foo in a class bar that he had created.  I think that in the meantime the place where the class foo was declared had been changed to a struct bar.  So that was why the code was compiling.  So I guess the answer to my question is that struct and class are interchangeable when declaring objects.  Still I guess it's a good idea to use them consistently.

答:
I would take @Alex Chamberlain and @James Kanze's comments as an answer:

There is nothing wrong with the code because declaration != definition: You can declare a type as a class, struct or union and then use a different one for the definition. Multiple definitions shouldn't compile; multiple declarations however is just fine.

The real problem: When you forward declare, you do NOT want to care whether it was a struct, class or union: In that context, that is an irrelevant implementation detail, that could even change later. So this warning is an artificial code smell. Still, you have to choose, and considering that class foo; has come to be the way to forward declare, I would go as far as to say the code is perfect.

The author didn't forget to update the forward declaration; he isn't supposed to (whether he changed the implementation or not, he probably didn't).

Body:
Summary: What happens if you declare a struct and a class with the same name.

Details:

I'm reviewing some code and I saw a warning like this:

warning: struct 'foo' was previously declared as a class

When compiling with clang there were also a couple of places where clang added notes saying:

foo.h:29:1: note: did you mean struct here?
class foo;
^~~~~
struct

Obviously this is not a good coding practice to have a struct and a class with the same name.  It looks like what happened is the developer was writing his own class and used a name that was already in use in another file that he was including and he did not notice that.

However, my question is will the compiler be able to tell the difference between the variables that were declared as class foo and the ones that were struct foo?

Edit:

Actually what was happening was that the developer was using the class foo in a class bar that he had created.  I think that in the meantime the place where the class foo was declared had been changed to a struct bar.  So that was why the code was compiling.  So I guess the answer to my question is that struct and class are interchangeable when declaring objects.  Still I guess it's a good idea to use them consistently.


问:
Where can i read this log that ActivityManager: Killing 2225:com.android.email/u0a39 (adj 900): remove task
I'm searching where can I read this log.

```<code>03-29 02:47:31.249   774   795 I ActivityManager: Displayed com.android.email/.activity.setup.AccountSetupFinal: +120ms
03-29 02:47:34.014   774  1200 I ActivityManager: START u0 {flg=0x10804000 cmp=com.android.systemui/.recents.RecentsActivity} from uid 10023 on display 0
03-29 02:47:35.488   774   785 I ActivityManager: Killing 2225:com.android.email/u0a39 (adj 900): remove task
</code>```

This log shows in ActivityManager but I can't find the source in ActivityManager.java in AOSP full source.

So would you tell me where is the log source file?

答:
This logs are printed by the files under "frameworks/base/services/core/java/com/android/server/am/" .
For eg , the last line in your logs is printed by ProcessRecord.java

```<code>Slog.i(TAG, "Killing " + toShortString() + " (adj " + setAdj + "): " + reason);
</code>```

where TAG is defined as :

```<code>private static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessRecord" : TAG_AM;
</code>```

Body:
I'm searching where can I read this log.

03-29 02:47:31.249   774   795 I ActivityManager: Displayed com.android.email/.activity.setup.AccountSetupFinal: +120ms
03-29 02:47:34.014   774  1200 I ActivityManager: START u0 {flg=0x10804000 cmp=com.android.systemui/.recents.RecentsActivity} from uid 10023 on display 0
03-29 02:47:35.488   774   785 I ActivityManager: Killing 2225:com.android.email/u0a39 (adj 900): remove task

This log shows in ActivityManager but I can't find the source in ActivityManager.java in AOSP full source.

So would you tell me where is the log source file?

Body:
This logs are printed by the files under "frameworks/base/services/core/java/com/android/server/am/" .
For eg , the last line in your logs is printed by ProcessRecord.java

Slog.i(TAG, "Killing " + toShortString() + " (adj " + setAdj + "): " + reason);

where TAG is defined as :

private static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessRecord" : TAG_AM;


问:
TYPO3 v6.2.x Tutorials for beginners
I  decided to learning TYPO3 v6.2.x CMS,I installed CMS on local server  but I can't create some basic  template, after long searching in google and here on stackoverflow, I can't find  any useful tutorials or books for beginners.

I need only tutorials  where explained how to create basic template  with TYPO3 CMS v6.x.x or maybe in "github" is some basic start kit with basic template?.

I hope some kind  people suggest me  how  and where to start.
Please don't be lazy, it`s very important for me :).

答:
All Fluid tutorials should work. The official tutorial from typo3.org is
https://wiki.typo3.org/T3Doc/Fluidtemplate_by_example

There is also a "Bootstrap Kickstart Package". You can find it in the Extension Manager under "get preconfigured distribution". Or in the repository: https://typo3.org/extensions/repository/view/bsdist

But why do you want to start learning with an old Version? End of maintenance of v6.2 was in April. Better start with the new LTS version 8.7.1

Title: TYPO3 v6.2.x Tutorials for beginners


问:
Show Tutorial View on first time only
I'm trying to create an tutorial screen that displays only during the first opening of an app. i know i should use user defaults but how and where ? in method viewDidLoad or on app delegate class ? </p>

答:
Store the status whether the Tutorial View is displayed or not in NSUserDefaults.

If you want to decide at startup to show or not show the Tutorial View you should do it in App Delegate didFinishLaunchingWithOptions

```<code>if(![[NSUserDefaults standardUserDefaults] boolForKey:@"shouldShowTutorial"])

//show tutorial

}
else{

//don't show tutorial

}
</code>```

On the first time when the Tutorial View has been displayed set a flag in NSUserDefaults.

```<code>[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"shouldShowTutorial"];
</code>```

Title: Show Tutorial View on first time only

Body:
Store the status whether the Tutorial View is displayed or not in NSUserDefaults.

If you want to decide at startup to show or not show the Tutorial View you should do it in App Delegate didFinishLaunchingWithOptions

if(![[NSUserDefaults standardUserDefaults] boolForKey:@"shouldShowTutorial"])

//show tutorial

}
else{

//don't show tutorial

}

On the first time when the Tutorial View has been displayed set a flag in NSUserDefaults.

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"shouldShowTutorial"];


问:
How to fetch list of tables in database using HibernateDaoSupport?
Here I have added my code. Issue occurs in try block while I am trying fetch list of tables.

Database is MySql

Exception is  : java.lang.IllegalArgumentException: node to traverse cannot be null!

```<code>public class DBOptimizationDAO extends HibernateDaoSupport {

private static final Log log  = LogFactory.getLog(DBOptimizationDAO.class);

public void optimizeAdapter(String year)
{
    List<com.ecw.adapterservice.beans.TransactionInbound> transactionInboundList = null;
    StringBuilder queries = new StringBuilder();
    try {
        transactionInboundList = (List<com.ecw.adapterservice.beans.TransactionInbound>)super.getHibernateTemplate().find("from TransactionInbound where inboundTimestamp < '" + year+ "-01-01'order by 1 desc limit 2");

        //  Check if archive table exist or not
        List<Object> inboundObj = getHibernateTemplate().find("SHOW TABLES LIKE transaction_outbound");
        List<Object> outboundObj = getHibernateTemplate().find("SHOW TABLES LIKE 'transaction_outbound_archive'");
</code>```

答:
The HibernateTemplate::find expects a HQL query in the string parameter and you are passing a native statement. You can do native stuff (queries, statements, etc) using the Session object returned by HibernateTemplate::getSession. To pass a native select query you then have Session::createSQLQuery

BUT do you really want to rely on database specific code to do this? There is a more elegant way to do it by using DatabaseMetaData::getTables. See this answer. And you can get an instance of DatabaseMetaData from a callback method of your HibernateTemplate.

Try this:

```<code>        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        if(!session instaceof SessionImpl){
                    //handle this, maybe throw an exception
                }
        else {
            Connection con = (SessionImpl)session.connection();
            ...
        }
</code>```

Body:
Here I have added my code. Issue occurs in try block while I am trying fetch list of tables.

Database is MySql

Exception is  : java.lang.IllegalArgumentException: node to traverse cannot be null!

public class DBOptimizationDAO extends HibernateDaoSupport {

private static final Log log  = LogFactory.getLog(DBOptimizationDAO.class);

public void optimizeAdapter(String year)
{
    List<com.ecw.adapterservice.beans.TransactionInbound> transactionInboundList = null;
    StringBuilder queries = new StringBuilder();
    try {
        transactionInboundList = (List<com.ecw.adapterservice.beans.TransactionInbound>)super.getHibernateTemplate().find("from TransactionInbound where inboundTimestamp < '" + year+ "-01-01'order by 1 desc limit 2");

        //  Check if archive table exist or not
        List<Object> inboundObj = getHibernateTemplate().find("SHOW TABLES LIKE transaction_outbound");
        List<Object> outboundObj = getHibernateTemplate().find("SHOW TABLES LIKE 'transaction_outbound_archive'");

Body:
The HibernateTemplate::find expects a HQL query in the string parameter and you are passing a native statement. You can do native stuff (queries, statements, etc) using the Session object returned by HibernateTemplate::getSession. To pass a native select query you then have Session::createSQLQuery

BUT do you really want to rely on database specific code to do this? There is a more elegant way to do it by using DatabaseMetaData::getTables. See this answer. And you can get an instance of DatabaseMetaData from a callback method of your HibernateTemplate.

Try this:

        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        if(!session instaceof SessionImpl){
                    //handle this, maybe throw an exception
                }
        else {
            Connection con = (SessionImpl)session.connection();
            ...
        }


问:
How to append text to array value JavaScript
I have two javascript array like this.

```<code>var category = ['Jacket'];
var subcategory = ['Woman', 'Men', 'Kids'];
</code>```

and i want combining array value like this

```<code>var finalCategory = ['Jacket Woman', 'Jacket Men', 'Jacket Kids'];
</code>```

if category more than one, final result

```<code>var category = ['Jacket', 'Bags'];
var subcategory = ['Woman', 'Men', 'Kids'];
var finalCategory = ['Jacket Woman', 'Jacket Men', 'Jacket Kids', 'Bags Woman', 'Bags Men', 'Bags Kids'];
</code>```

Please help, thank you.

答:
You could create the cartesian product with nested loops as result.

var category = ['Jacket', 'Bags'],
    subcategory = ['Woman', 'Men', 'Kids'],
    result = category.reduce(function (r, a) {         // use an accumulator and item
        return r.concat(subcategory.map(function (b) { // concat result of mapped subs
            return [a, b].join(' ');                   // build string with given items
        }));
    }, []);                                            // take array as accumulator

console.log(result);```
</div>
</div>
</p>

<p>ES6</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>var category = ['Jacket', 'Bags'],
    subcategory = ['Woman', 'Men', 'Kids'],
    result = category.reduce((r, a) => r.concat(subcategory.map(b => [a, b].join(' '))), []);

console.log(result);</code>```

Body:
I have two javascript array like this.

var category = ['Jacket'];
var subcategory = ['Woman', 'Men', 'Kids'];

and i want combining array value like this

var finalCategory = ['Jacket Woman', 'Jacket Men', 'Jacket Kids'];

if category more than one, final result

var category = ['Jacket', 'Bags'];
var subcategory = ['Woman', 'Men', 'Kids'];
var finalCategory = ['Jacket Woman', 'Jacket Men', 'Jacket Kids', 'Bags Woman', 'Bags Men', 'Bags Kids'];

Please help, thank you.

Body:
You could create the cartesian product with nested loops as result.

var category = ['Jacket', 'Bags'],
    subcategory = ['Woman', 'Men', 'Kids'],
    result = category.reduce(function (r, a) {         // use an accumulator and item
        return r.concat(subcategory.map(function (b) { // concat result of mapped subs
            return [a, b].join(' ');                   // build string with given items
        }));
    }, []);                                            // take array as accumulator

console.log(result);

ES6

var category = ['Jacket', 'Bags'],
    subcategory = ['Woman', 'Men', 'Kids'],
    result = category.reduce((r, a) => r.concat(subcategory.map(b => [a, b].join(' '))), []);

console.log(result);


答:
You can use</p>

```<code>var category = ['Jacket', 'Bags'];
var subcategory = ['Woman', 'Men', 'Kids'];
var combos = [];
category.forEach(function(a){
    subcategory.forEach(function(b){
        combos.push(a + ' ' + b);
    });
});
</code>```

Title: How to append text to array value JavaScript

Body:
You can use

var category = ['Jacket', 'Bags'];
var subcategory = ['Woman', 'Men', 'Kids'];
var combos = [];
category.forEach(function(a){
    subcategory.forEach(function(b){
        combos.push(a + ' ' + b);
    });
});


问:
Python Tabs Fake or Real
Many tutorial suggest users to use tab with width of 4 while 4 is made using spaces not real tab character. Using real tab also it works so why do people suggest to use spaces of 4 rather than real tab ? I'm a python beginner confused ????

[UPDATE]
Thanks! I am now switching to spaces of 4.

Added following to my .vimrc
"Python

```<code>au BufRead,BufNewFile *.py,*pyw set shiftwidth=4
au BufRead,BufNewFile *.py,*.pyw set expandtab
fu Select_c_style()
    if search('^\t', 'n', 150)
        set shiftwidth=8
        set noexpandtab
    el
        set shiftwidth=4
        set expandtab
    en
endf
</code>```

For other case:

```<code>set noexpandtab                " tabs are tabs, not spaces
</code>```

答: The Python compiler considers the tab character to be equivalent to indentation of 8 spaces. You can use tabs if you like but mixing tabs and spaces will lead to tricky-to-debug errors, which is why sticking with spaces is recommended.</p>

Title: Python Tabs Fake or Real

Body:
Many tutorial suggest users to use tab with width of 4 while 4 is made using spaces not real tab character. Using real tab also it works so why do people suggest to use spaces of 4 rather than real tab ? I'm a python beginner confused ????

[UPDATE]
Thanks! I am now switching to spaces of 4.

Added following to my .vimrc
"Python

au BufRead,BufNewFile *.py,*pyw set shiftwidth=4
au BufRead,BufNewFile *.py,*.pyw set expandtab
fu Select_c_style()
    if search('^\t', 'n', 150)
        set shiftwidth=8
        set noexpandtab
    el
        set shiftwidth=4
        set expandtab
    en
endf

For other case:

set noexpandtab                " tabs are tabs, not spaces


问:
reverse engineering postgresql using hibernate tool in eclipse
I am trying to reverse engineer postgresql using hibernate tools in eclipse. It is not generating @Generated annotation.  postgres tables have primary key defined with serial keyword. what can be the problem?</p>

答:
You should modify the freemarker templates, and add someting like :

```<code>@${pojo.importType("javax.annotation.Generated")}(value = "Generated by Hibernate Tools ${version}", date = "${.now?iso_local}")
</code>```

For JPA entities, you could add it in pojo/PojoTypeDeclaration.ftl

It works with Hibernate Tools 5.2.3 and Freemarker 2.3.23.

You could also add block comments like :

```<code>// Generated ${date} by Hibernate Tools ${version}
// and FreeMarker ${.version}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You should modify the freemarker templates, and add someting like :

@${pojo.importType("javax.annotation.Generated")}(value = "Generated by Hibernate Tools ${version}", date = "${.now?iso_local}")

For JPA entities, you could add it in pojo/PojoTypeDeclaration.ftl

It works with Hibernate Tools 5.2.3 and Freemarker 2.3.23.

You could also add block comments like :

// Generated ${date} by Hibernate Tools ${version}
// and FreeMarker ${.version}


答:
Use nested for loops to create a new array:

function concatArr(arr1, arr2) {
  var newArr = [];
  for (var a = 0; a < arr1.length; a++) {
    var arr1Value = arr1[a];
    for (var b = 0; b < arr2.length; b++) {
      var arr2Value = arr2[b];
      newArr.push(arr1Value + " " + arr2Value);
    }
  }
  return newArr;
}
//TEST
var category = ['Jacket', 'Pants'];
var subcategory = ['Woman', 'Men', 'Kids'];
console.log(concatArr(category, subcategory));```


问:
Linq in from ObservableCollection in ObservableCollection
I am tring to get the value "thisValueIwant". Is there any possibility to get this value so easy? Or Maybe there is another solution for these 2 ObservableCollection</p>

```<code>public class Foo
{
    public int number { get; set; }
    public ObservableCollection<FooInFoo> Details { get; set; }
}

public class FooInFoo
{
    public string thisValueIwant { get; set; }
}

public class TestClass
{
    public void Test()
    {
        ObservableCollection<Foo> FooCollection = new ObservableCollection<Foo>();

        FooCollection.Add(new Foo{
            number =1,
            Details = new ObservableCollection<FooInFoo>{ new FooInFoo {thisValueIwant = "very important string"}}
        });

        string x = (from f in FooCollection
                    where f.number == 1
                    select ???)
    }
}
</code>```

答:
Since ObservableCollection<FooInFoo> Details is a collection, you have to decide which details you want: the first, last, any or all.

Assuming you want the first:

```<code>var d = FooCollection.Where(f => f.Number == 1).FirstOrDefault()?.Details.FirstOrDefault()?.thisValueIwant;
</code>```

Or the last:

```<code>var d = FooCollection.Where(f => f.Number == 1).FirstOrDefault()?.Details.LastOrDefault()?.thisValueIwant;
</code>```

Or all (materialized as an array):

```<code>var ds = FooCollection.Where(f => f.Number == 1).FirstOrDefault()?.Details.Select(d => d.thisValueIwant).ToArray();
</code>```

Body:
I am tring to get the value "thisValueIwant". Is there any possibility to get this value so easy? Or Maybe there is another solution for these 2 ObservableCollection

public class Foo
{
    public int number { get; set; }
    public ObservableCollection<FooInFoo> Details { get; set; }
}

public class FooInFoo
{
    public string thisValueIwant { get; set; }
}

public class TestClass
{
    public void Test()
    {
        ObservableCollection<Foo> FooCollection = new ObservableCollection<Foo>();

        FooCollection.Add(new Foo{
            number =1,
            Details = new ObservableCollection<FooInFoo>{ new FooInFoo {thisValueIwant = "very important string"}}
        });

        string x = (from f in FooCollection
                    where f.number == 1
                    select ???)
    }
}

Body:
Since ObservableCollection<FooInFoo> Details is a collection, you have to decide which details you want: the first, last, any or all.

Assuming you want the first:

var d = FooCollection.Where(f => f.Number == 1).FirstOrDefault()?.Details.FirstOrDefault()?.thisValueIwant;

Or the last:

var d = FooCollection.Where(f => f.Number == 1).FirstOrDefault()?.Details.LastOrDefault()?.thisValueIwant;

Or all (materialized as an array):

var ds = FooCollection.Where(f => f.Number == 1).FirstOrDefault()?.Details.Select(d => d.thisValueIwant).ToArray();


问:
OWIN SignOut doesn't remove cookie
I am using the OWIN middleware in an external Authentication Server that my applications authenticate to using OAuth Authorisation Code Grant flow.

I can redirect to the Authentication Server, authenticate against an external provider (Google) and redirect back to my client application with a logged in user and Application Cookie set just fine, however when I try to sign out the cookie remains after I call the AuthenticationManager.SignOut method.

My cookie options in Startup.Auth.cs are:

```<code>var cookieOptions = new CookieAuthenticationOptions
                    {
                        Provider = cookieProvider,
                        AuthenticationType = "Application",
                        AuthenticationMode = AuthenticationMode.Passive,
                        LoginPath = new PathString("/Account/Index"),
                        LogoutPath = new PathString("/Account/Logout"),
                        SlidingExpiration = true,
                        ExpireTimeSpan = TimeSpan.FromMinutes(30),
                    };
app.UseCookieAuthentication(cookieOptions);
app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ExternalCookie);
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
</code>```

My login method:

```<code>var loginInfo = await AuthManager.GetExternalLoginInfoAsync();
SignInManager.ExternalSignInAsync(loginInfo, true);
var identity = AuthManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie).Result.Identity;

if (identity != null)
{
    AuthManager.SignIn(
                  new AuthenticationProperties {IsPersistent = true},
                  new ClaimsIdentity(identity.Claims, "Application", identity.NameClaimType, identity.RoleClaimType));

        var ticket = AuthManager.AuthenticateAsync("Application").Result;
        var identity = ticket != null ? ticket.Identity : null;
        if (identity == null)
        {
            AuthManager.Challenge("Application");
            return new HttpUnauthorizedResult();
        }

        identity = new ClaimsIdentity(identity.Claims, "Bearer", identity.NameClaimType, identity.RoleClaimType);
        AuthManager.SignIn(identity);
}

return Redirect(Request.QueryString["ReturnUrl"]);
</code>```

Sign Out method:

```<code>var authTypeNames = new List<string>();
authTypeNames.Add("Google");
authTypeNames.Add("Application");
authTypeNames.Add("Bearer");
authTypeNames.Add(DefaultAuthenticationTypes.ExternalCookie);

Request.GetOwinContext().Authentication.SignOut(authTypeNames.ToArray());
</code>```

I have looked at other questions like:
OWIN authentication, expire current token and remove cookie
and
OWIN - Authentication.SignOut() doesn't remove cookies

with no luck. I'm aware I could manually delete the cookie by setting a negative expiry date, but I'd prefer to use in built method if possible.

How do I get the Application Cookie to be removed when I Sign Out?

答:
```<code> AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
 FormsAuthentication.SignOut();
 Session.Abandon();
</code>```

Title: OWIN SignOut doesn't remove cookie

Body:
I am using the OWIN middleware in an external Authentication Server that my applications authenticate to using OAuth Authorisation Code Grant flow.

I can redirect to the Authentication Server, authenticate against an external provider (Google) and redirect back to my client application with a logged in user and Application Cookie set just fine, however when I try to sign out the cookie remains after I call the AuthenticationManager.SignOut method.

My cookie options in Startup.Auth.cs are:

var cookieOptions = new CookieAuthenticationOptions
                    {
                        Provider = cookieProvider,
                        AuthenticationType = "Application",
                        AuthenticationMode = AuthenticationMode.Passive,
                        LoginPath = new PathString("/Account/Index"),
                        LogoutPath = new PathString("/Account/Logout"),
                        SlidingExpiration = true,
                        ExpireTimeSpan = TimeSpan.FromMinutes(30),
                    };
app.UseCookieAuthentication(cookieOptions);
app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ExternalCookie);
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

My login method:

var loginInfo = await AuthManager.GetExternalLoginInfoAsync();
SignInManager.ExternalSignInAsync(loginInfo, true);
var identity = AuthManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie).Result.Identity;

if (identity != null)
{
    AuthManager.SignIn(
                  new AuthenticationProperties {IsPersistent = true},
                  new ClaimsIdentity(identity.Claims, "Application", identity.NameClaimType, identity.RoleClaimType));

        var ticket = AuthManager.AuthenticateAsync("Application").Result;
        var identity = ticket != null ? ticket.Identity : null;
        if (identity == null)
        {
            AuthManager.Challenge("Application");
            return new HttpUnauthorizedResult();
        }

        identity = new ClaimsIdentity(identity.Claims, "Bearer", identity.NameClaimType, identity.RoleClaimType);
        AuthManager.SignIn(identity);
}

return Redirect(Request.QueryString["ReturnUrl"]);

Sign Out method:

var authTypeNames = new List<string>();
authTypeNames.Add("Google");
authTypeNames.Add("Application");
authTypeNames.Add("Bearer");
authTypeNames.Add(DefaultAuthenticationTypes.ExternalCookie);

Request.GetOwinContext().Authentication.SignOut(authTypeNames.ToArray());

I have looked at other questions like:
OWIN authentication, expire current token and remove cookie
and
OWIN - Authentication.SignOut() doesn't remove cookies

with no luck. I'm aware I could manually delete the cookie by setting a negative expiry date, but I'd prefer to use in built method if possible.

How do I get the Application Cookie to be removed when I Sign Out?


问:
How to reach derived class variable from base class vector?
```<code>#include <iostream>
#include <vector>

class Entity
{
public:
    bool hinders_sight = false;
};

class Pillar : public Entity
{
public:
    bool hinders_sight = true;
};

int main()
{
    std::vector<Entity*> Entities;

    Pillar pillar;

    Entities.push_back(&pillar);

    std::cout << pillar.hinders_sight << std::endl;
    std::cout << Entities[0]->hinders_sight << std::endl;

    return 0;
}
</code>```

pillar.hinders_sight returns true (as it should)

but

Entities[0]->hinders_sight returns false.

How can I reach hinders_sight of pillar from the vector?

答:
Use a virtual bool HindersSight(){return hinders_sight;} as variables are not virtual.

Edit: Oh and make your variables protected or private to promote encapsulation. You could complete get rid of the variable and implement HindersSight() for each class to directly return true or false.

Body:
#include <iostream>
#include <vector>

class Entity
{
public:
    bool hinders_sight = false;
};

class Pillar : public Entity
{
public:
    bool hinders_sight = true;
};

int main()
{
    std::vector<Entity*> Entities;

    Pillar pillar;

    Entities.push_back(&pillar);

    std::cout << pillar.hinders_sight << std::endl;
    std::cout << Entities[0]->hinders_sight << std::endl;

    return 0;
}

pillar.hinders_sight returns true (as it should)

but

Entities[0]->hinders_sight returns false.

How can I reach hinders_sight of pillar from the vector?


问:
How to autosize User control when it's shown
I have a Winforms project with a bunch of User controls.  I'd like the user control to move itself to be at the 1,1 position relative to its container (whether it's a form or a Panel control).  And resize itself to be able to fit half the container.

What event can I respond to in the UserControl to be able to do this without any code having to be written in the container (e.g. the form or panel).

答: The Paint event should work, unless I'm missing something.</p>

OwnerDisplayName: AngryHacker

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Ryan Arana


问:
Big ugly SQL query problem
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

```<code>SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id
</code>```

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

```<code>Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------
</code>```

答:
First you normalize that status table with a UNION and then you do the group by with the max values.

```<code>select status_id, max(levelid), max(levels) from (
select * from status_level, status where desc = desc1
union
select * from status_level, status where desc = desc2
union
select * from status_level, status where desc = desc3
union
select * from status_level, status where desc = desc4)
group by status_id;
</code>```

Here is the whole test script and output

```<code>    create table status (status_id number, desc1 varchar2(50), desc2 varchar2(50), desc3 varchar2(50), desc4 varchar2(50) );

    create table status_level (status_level_id number, descx varchar2(50), levelid number, levels number);

    insert into status values (1,'ABC_LEVEL_1','DEF_LEVEL_5','CBA_LEVEL_2','ABC_LEVEL_4');
    insert into status values (2,'ABC_LEVEL_1','DEF_LEVEL_1','CBA_LEVEL_2','ABC_LEVEL_1');
    insert into status values (3,'ABC_LEVEL_4','DEF_LEVEL_1','CBA_LEVEL_2','ABC_LEVEL_4');

    insert into status_level values (1,'ABC_LEVEL_1',1,7);
    insert into status_level values (1,'DEF_LEVEL_5',5,6);
    insert into status_level values (1,'CBA_LEVEL_2',2,3);
    insert into status_level values (1,'ABC_LEVEL_4',4,5);
    insert into status_level values (1,'DEF_LEVEL_1',1,2);

    commit;

    select * from status;

    select * from status_level;

    select * from status, status_level where descx = desc1
    union
    select * from status, status_level where descx = desc2
    union
    select * from status, status_level where descx = desc3
    union
    select * from status, status_level where descx = desc4;

    select status_id, max(levelid), max(levels) from (
    select * from status_level, status where descx = desc1
    union
    select * from status_level, status where descx = desc2
    union
    select * from status_level, status where descx = desc3
    union
    select * from status_level, status where descx = desc4)
    group by status_id;

    Table created.
    Table created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    Commit complete.

     STATUS_ID DESC1                                              DESC2                                              DESC3                                              DESC4
    ---------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --------------------------------------------------
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4
             2 ABC_LEVEL_1                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_1
             3 ABC_LEVEL_4                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_4

    3 rows selected.

    STATUS_LEVEL_ID DESCX                                                 LEVELID     LEVELS
    --------------- -------------------------------------------------- ---------- ----------
                  1 ABC_LEVEL_1                                                 1          7
                  1 DEF_LEVEL_5                                                 5          6
                  1 CBA_LEVEL_2                                                 2          3
                  1 ABC_LEVEL_4                                                 4          5
                  1 DEF_LEVEL_1                                                 1          2

    5 rows selected.

     STATUS_ID DESC1                                              DESC2                                              DESC3                                              DESC4                                              STATUS_LEVEL_ID DESCX                                                 LEVELID     LEVELS
    ---------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --------------- -------------------------------------------------- ---------- ----------
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 ABC_LEVEL_1                                                 1          7
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 ABC_LEVEL_4                                                 4          5
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 CBA_LEVEL_2                                                 2          3
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 DEF_LEVEL_5                                                 5          6
             2 ABC_LEVEL_1                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_1                                                      1 ABC_LEVEL_1                                                 1          7
             2 ABC_LEVEL_1                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_1                                                      1 CBA_LEVEL_2                                                 2          3
             2 ABC_LEVEL_1                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_1                                                      1 DEF_LEVEL_1                                                 1          2
             3 ABC_LEVEL_4                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 ABC_LEVEL_4                                                 4          5
             3 ABC_LEVEL_4                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 CBA_LEVEL_2                                                 2          3
             3 ABC_LEVEL_4                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 DEF_LEVEL_1                                                 1          2

    10 rows selected.

     STATUS_ID MAX(LEVELID) MAX(LEVELS)
    ---------- ------------ -----------
             1            5           7
             2            2           7
             3            4           5

    3 rows selected.
</code>```

Title: Big ugly SQL query problem

Body:
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------

Body:
First you normalize that status table with a UNION and then you do the group by with the max values.

select status_id, max(levelid), max(levels) from (
select * from status_level, status where desc = desc1
union
select * from status_level, status where desc = desc2
union
select * from status_level, status where desc = desc3
union
select * from status_level, status where desc = desc4)
group by status_id;

Here is the whole test script and output

    create table status (status_id number, desc1 varchar2(50), desc2 varchar2(50), desc3 varchar2(50), desc4 varchar2(50) );

    create table status_level (status_level_id number, descx varchar2(50), levelid number, levels number);

    insert into status values (1,'ABC_LEVEL_1','DEF_LEVEL_5','CBA_LEVEL_2','ABC_LEVEL_4');
    insert into status values (2,'ABC_LEVEL_1','DEF_LEVEL_1','CBA_LEVEL_2','ABC_LEVEL_1');
    insert into status values (3,'ABC_LEVEL_4','DEF_LEVEL_1','CBA_LEVEL_2','ABC_LEVEL_4');

    insert into status_level values (1,'ABC_LEVEL_1',1,7);
    insert into status_level values (1,'DEF_LEVEL_5',5,6);
    insert into status_level values (1,'CBA_LEVEL_2',2,3);
    insert into status_level values (1,'ABC_LEVEL_4',4,5);
    insert into status_level values (1,'DEF_LEVEL_1',1,2);

    commit;

    select * from status;

    select * from status_level;

    select * from status, status_level where descx = desc1
    union
    select * from status, status_level where descx = desc2
    union
    select * from status, status_level where descx = desc3
    union
    select * from status, status_level where descx = desc4;

    select status_id, max(levelid), max(levels) from (
    select * from status_level, status where descx = desc1
    union
    select * from status_level, status where descx = desc2
    union
    select * from status_level, status where descx = desc3
    union
    select * from status_level, status where descx = desc4)
    group by status_id;

    Table created.
    Table created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    1 row created.
    Commit complete.

     STATUS_ID DESC1                                              DESC2                                              DESC3                                              DESC4
    ---------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --------------------------------------------------
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4
             2 ABC_LEVEL_1                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_1
             3 ABC_LEVEL_4                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_4

    3 rows selected.

    STATUS_LEVEL_ID DESCX                                                 LEVELID     LEVELS
    --------------- -------------------------------------------------- ---------- ----------
                  1 ABC_LEVEL_1                                                 1          7
                  1 DEF_LEVEL_5                                                 5          6
                  1 CBA_LEVEL_2                                                 2          3
                  1 ABC_LEVEL_4                                                 4          5
                  1 DEF_LEVEL_1                                                 1          2

    5 rows selected.

     STATUS_ID DESC1                                              DESC2                                              DESC3                                              DESC4                                              STATUS_LEVEL_ID DESCX                                                 LEVELID     LEVELS
    ---------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --------------- -------------------------------------------------- ---------- ----------
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 ABC_LEVEL_1                                                 1          7
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 ABC_LEVEL_4                                                 4          5
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 CBA_LEVEL_2                                                 2          3
             1 ABC_LEVEL_1                                        DEF_LEVEL_5                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 DEF_LEVEL_5                                                 5          6
             2 ABC_LEVEL_1                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_1                                                      1 ABC_LEVEL_1                                                 1          7
             2 ABC_LEVEL_1                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_1                                                      1 CBA_LEVEL_2                                                 2          3
             2 ABC_LEVEL_1                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_1                                                      1 DEF_LEVEL_1                                                 1          2
             3 ABC_LEVEL_4                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 ABC_LEVEL_4                                                 4          5
             3 ABC_LEVEL_4                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 CBA_LEVEL_2                                                 2          3
             3 ABC_LEVEL_4                                        DEF_LEVEL_1                                        CBA_LEVEL_2                                        ABC_LEVEL_4                                                      1 DEF_LEVEL_1                                                 1          2

    10 rows selected.

     STATUS_ID MAX(LEVELID) MAX(LEVELS)
    ---------- ------------ -----------
             1            5           7
             2            2           7
             3            4           5

    3 rows selected.


问:
Displaying RTSP-Stream using Xuggler: org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 34 60, bytestream (td)
I'm new to displaying RTSP-Streams and Xuggler, so I really don't know what to do.

I'm trying to display the Main-Stream of my IP-Camera in a Java-Swing Window and get this:

I also get these errors:

13:21:45.941 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 8 7, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 34 60, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 8 36, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 68 62, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 118 38, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 60 62, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] cabac decode of qscale diff failed at 1 7

  13:21:46.940 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 1 7, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 28 37, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 18 35, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 17 41, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 53 32, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 31 29, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 21 29, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] left block unavailable for requested intra mode at 0 35

  13:21:49.902 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 0 35, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 17 21, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 46 10, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 109 28, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 60 10, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 11 14, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 101 9, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 76 9, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 86 11, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 60 24, bytestream (td)

This is part of the code that I use:

```<code>private IMediaListener mediaListener = new MediaListenerAdapter() {

    @Override
    public void onVideoPicture(IVideoPictureEvent event) {
        try {
            BufferedImage bi = event.getImage();
            if (bi != null)
                updateWindow(bi);
        } catch (Exception ex) {
            LOG.error("Error getting Image from IVideoPictureEvent: " + ex);
        }
    }
};

public DisplayWindow() {
    display();
}

private void display() {
    IMediaReader mediaReader = ToolFactory
            .makeReader("rtsp://user:password@192.168.1.22:554/Streaming/Channels/1");

    mediaReader
            .setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR);
    mediaReader.setQueryMetaData(false);
    mediaReader.addListener(mediaListener);

    openWindow();

    while (true) {
        IError error = null;
        if(mediaReader != null){
            error = mediaReader.readPacket();
            if(error != null){
                LOG.error("Error at mediaReader.readPacket(): " + error);
            }
        }
    }
}
</code>```

Displaying the Sub-Stream (which has lower resolution) works well.

I use Xuggler 5.4 with Maven.

There probably is a simple solution to this problem, but I've searched the whole internet and haven't found one, so I'd appreciate any help. Thank you!

UPDATE: I'd also be happy about (free!) alternatives to Xuggler.

答:
I fixed this error with a HIKVision camera by forcing TCP transport. To force TCP, need to manually create the IContainer and pass the setting in an IMetaData:</p>

```<code>    IMetaData im = IMetaData.make();
    im.setValue("rtsp_transport", "tcp");

    IContainer streamContainer = IContainer.make();
    int result = streamContainer.open("rtsp://user:password@192.168.1.22:554/Streaming/Channels/1", IContainer.Type.READ, null, true, false, im, null);

    if (result < 0) {
        // Error
    }

    IMediaReader mediaReader = ToolFactory.makeReader(streamContainer);
</code>```

Body:
I'm new to displaying RTSP-Streams and Xuggler, so I really don't know what to do.

I'm trying to display the Main-Stream of my IP-Camera in a Java-Swing Window and get this:

I also get these errors:

13:21:45.941 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 8 7, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 34 60, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 8 36, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 68 62, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 118 38, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 60 62, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] cabac decode of qscale diff failed at 1 7

  13:21:46.940 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 1 7, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 28 37, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 18 35, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 17 41, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 53 32, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 31 29, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 21 29, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] left block unavailable for requested intra mode at 0 35

  13:21:49.902 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 0 35, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 17 21, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 46 10, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 109 28, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 60 10, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 11 14, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 101 9, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 76 9, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 86 11, bytestream (td)

  17:47:04.192 [main] ERROR org.ffmpeg - [h264 @ 15AC7660] error while decoding MB 60 24, bytestream (td)

This is part of the code that I use:

private IMediaListener mediaListener = new MediaListenerAdapter() {

    @Override
    public void onVideoPicture(IVideoPictureEvent event) {
        try {
            BufferedImage bi = event.getImage();
            if (bi != null)
                updateWindow(bi);
        } catch (Exception ex) {
            LOG.error("Error getting Image from IVideoPictureEvent: " + ex);
        }
    }
};

public DisplayWindow() {
    display();
}

private void display() {
    IMediaReader mediaReader = ToolFactory
            .makeReader("rtsp://user:password@192.168.1.22:554/Streaming/Channels/1");

    mediaReader
            .setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR);
    mediaReader.setQueryMetaData(false);
    mediaReader.addListener(mediaListener);

    openWindow();

    while (true) {
        IError error = null;
        if(mediaReader != null){
            error = mediaReader.readPacket();
            if(error != null){
                LOG.error("Error at mediaReader.readPacket(): " + error);
            }
        }
    }
}

Displaying the Sub-Stream (which has lower resolution) works well.

I use Xuggler 5.4 with Maven.

There probably is a simple solution to this problem, but I've searched the whole internet and haven't found one, so I'd appreciate any help. Thank you!

UPDATE: I'd also be happy about (free!) alternatives to Xuggler.

Body:
I fixed this error with a HIKVision camera by forcing TCP transport. To force TCP, need to manually create the IContainer and pass the setting in an IMetaData:

    IMetaData im = IMetaData.make();
    im.setValue("rtsp_transport", "tcp");

    IContainer streamContainer = IContainer.make();
    int result = streamContainer.open("rtsp://user:password@192.168.1.22:554/Streaming/Channels/1", IContainer.Type.READ, null, true, false, im, null);

    if (result < 0) {
        // Error
    }

    IMediaReader mediaReader = ToolFactory.makeReader(streamContainer);


问:
IBM Watson Document Conversion not working
I recently implemented the Document Conversion API from IBM Watson. I always get an encoding error for converting pdf document!!!

```<code>#!/usr/bin/env python
#coding: utf-8

import json
from watson_developer_cloud import DocumentConversionV1
from io import open
document_conversion = DocumentConversionV1(
  username='{XXXXXXXXXXX}',
  password='{XXXXXXXXXXXXX}',
  version='2015-12-15'
)
config = {
  'conversion_target': 'ANSWER_UNITS',
  # Use a custom configuration.
  'word': {
    'heading': {
      'fonts': [
        {'level': 1, 'min_size': 24},
        {'level': 2, 'min_size': 16, 'max_size': 24}
      ]
    }
  }
}

with open(('sample.pdf'), 'r') as document:
  response = document_conversion.convert_document(document=document, config=config)
  print(json.dumps(response, indent=2))
</code>```

enter image description here

答:
enter code hereYour error is the config JSON. Your still using the word config instead of the pdf config JSON:

```<code>{
"pdf": {
    "heading": {
        "fonts": [
            {"level": 1, "min_size": 24},
            {"level": 2, "min_size": 18, "max_size": 23, "bold": true},
            {"level": 3, "min_size": 14, "max_size": 17, "italic": false},
            {"level": 4, "min_size": 12, "max_size": 13, "name": "Times New Roman"}
        ]
    }
}}
</code>```

If you want to use answer units please add this to your config file as well:

```<code>var config = {
conversion_target: "answer_units",
"pdf": {
    "heading": {
        "fonts": [{
            "level": 1,
            "min_size": 24,
            "max_size": 80
        },
            {
                "level": 2,
                "min_size": 18,
                "max_size": 24,
                "bold": false,
                "italic": false
            },
            {
                "level": 2,
                "min_size": 18,
                "max_size": 24,
                "bold": true
            },
            {
                "level": 3,
                "min_size": 13,
                "max_size": 18,
                "bold": false,
                "italic": false
            },
            {
                "level": 3,
                "min_size": 13,
                "max_size": 18,
                "bold": true
            },
            {
                "level": 4,
                "min_size": 11,
                "max_size": 13,
                "bold": true,
                "italic": false
            }
        ]
    }
}
</code>```

}

description:
https://www.ibm.com/watson/developercloud/doc/document-conversion/customizing.html

Body:
I recently implemented the Document Conversion API from IBM Watson. I always get an encoding error for converting pdf document!!!

#!/usr/bin/env python
#coding: utf-8

import json
from watson_developer_cloud import DocumentConversionV1
from io import open
document_conversion = DocumentConversionV1(
  username='{XXXXXXXXXXX}',
  password='{XXXXXXXXXXXXX}',
  version='2015-12-15'
)
config = {
  'conversion_target': 'ANSWER_UNITS',
  # Use a custom configuration.
  'word': {
    'heading': {
      'fonts': [
        {'level': 1, 'min_size': 24},
        {'level': 2, 'min_size': 16, 'max_size': 24}
      ]
    }
  }
}

with open(('sample.pdf'), 'r') as document:
  response = document_conversion.convert_document(document=document, config=config)
  print(json.dumps(response, indent=2))

enter image description here

Body:
enter code hereYour error is the config JSON. Your still using the word config instead of the pdf config JSON:

{
"pdf": {
    "heading": {
        "fonts": [
            {"level": 1, "min_size": 24},
            {"level": 2, "min_size": 18, "max_size": 23, "bold": true},
            {"level": 3, "min_size": 14, "max_size": 17, "italic": false},
            {"level": 4, "min_size": 12, "max_size": 13, "name": "Times New Roman"}
        ]
    }
}}

If you want to use answer units please add this to your config file as well:

var config = {
conversion_target: "answer_units",
"pdf": {
    "heading": {
        "fonts": [{
            "level": 1,
            "min_size": 24,
            "max_size": 80
        },
            {
                "level": 2,
                "min_size": 18,
                "max_size": 24,
                "bold": false,
                "italic": false
            },
            {
                "level": 2,
                "min_size": 18,
                "max_size": 24,
                "bold": true
            },
            {
                "level": 3,
                "min_size": 13,
                "max_size": 18,
                "bold": false,
                "italic": false
            },
            {
                "level": 3,
                "min_size": 13,
                "max_size": 18,
                "bold": true
            },
            {
                "level": 4,
                "min_size": 11,
                "max_size": 13,
                "bold": true,
                "italic": false
            }
        ]
    }
}

}

description:
https://www.ibm.com/watson/developercloud/doc/document-conversion/customizing.html


问:
Python-3.x Count the frequency of a specific number from user input
I'm trying to make a program that will output how many times the number 7 appears from a series of numbers (of no particular range) inputted by the user. Each number would be a separate input, not as one.

I have searched far and wide but the solutions I found involved letters, words, or numbers from pre-made lists rather than int from user input and errored when I tried to modify for purpose. I'm sure I'm missing something really obvious but I can't figure out how to do this.

(I tried Counter, if num == 100, count(100), for i in range, etc etc - but I'm clearly on the wrong path)

My starting point was trying to modify this one that prints the highest number because I am aiming for a similar format:

```<code>x = 0
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    num = int(y)
    if num != 0:
        if num > x:
            x = num
    else:
        done = True
print(str(x))
</code>```

Thank you for any advice with this.

答:
Consider

```<code>from collections import Counter

nums = []
c = Counter()
done = False
while not done:
    y = int(input("Enter a number (0 to end): "))
    if y == 0:
        done = True
    else:
        c.update([y])
        print(c)
</code>```

Example output:

```<code>Enter a number (0 to end): 1
Counter({1: 1})
Enter a number (0 to end): 2
Counter({1: 1, 2: 1})
Enter a number (0 to end): 2
Counter({2: 2, 1: 1})
Enter a number (0 to end): 2
Counter({2: 3, 1: 1})
Enter a number (0 to end): 0
</code>```

This will obviously break if user inputs a non-integer. Remove int(input..) or add try-except if needed.

Body:
I'm trying to make a program that will output how many times the number 7 appears from a series of numbers (of no particular range) inputted by the user. Each number would be a separate input, not as one.

I have searched far and wide but the solutions I found involved letters, words, or numbers from pre-made lists rather than int from user input and errored when I tried to modify for purpose. I'm sure I'm missing something really obvious but I can't figure out how to do this.

(I tried Counter, if num == 100, count(100), for i in range, etc etc - but I'm clearly on the wrong path)

My starting point was trying to modify this one that prints the highest number because I am aiming for a similar format:

x = 0
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    num = int(y)
    if num != 0:
        if num > x:
            x = num
    else:
        done = True
print(str(x))

Thank you for any advice with this.

Body:
Consider

from collections import Counter

nums = []
c = Counter()
done = False
while not done:
    y = int(input("Enter a number (0 to end): "))
    if y == 0:
        done = True
    else:
        c.update([y])
        print(c)

Example output:

Enter a number (0 to end): 1
Counter({1: 1})
Enter a number (0 to end): 2
Counter({1: 1, 2: 1})
Enter a number (0 to end): 2
Counter({2: 2, 1: 1})
Enter a number (0 to end): 2
Counter({2: 3, 1: 1})
Enter a number (0 to end): 0

This will obviously break if user inputs a non-integer. Remove int(input..) or add try-except if needed.


问:
Hide mouse cursor for specific time
```<code>public partial class Form3 : Form
{
    private readonly KeyboardHookListener m_KeyboardHookManager;
    private readonly MouseHookListener m_MouseHookManager;

    [DllImport("user32")]
    private static extern Int32 ClipCursor(RECT lpRect);

    [DllImport("user32")]
    private static extern Int32 ShowCursor(Int32 bShow);

    [DllImport("user32.dll")]
    public static extern bool GetCursorPos(out POINT lpPoint);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;

        public static implicit operator Point(POINT point)
        {
            return new Point(point.X, point.Y);
        }
    }

    public static Point GetCursorPosition()
    {
        POINT lpPoint;
        GetCursorPos(out lpPoint);
        //bool success = User32.GetCursorPos(out lpPoint);
        // if (!success)

        return lpPoint;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public Int32 Left;
        public Int32 Top;
        public Int32 Right;
        public Int32 Bottom;
    }

    public Form3()
    {
        InitializeComponent();

        m_KeyboardHookManager = new KeyboardHookListener(new GlobalHooker());
        m_KeyboardHookManager.Enabled = true;
        m_KeyboardHookManager.KeyDown += HookManager_KeyDown;
        m_KeyboardHookManager.KeyUp += HookManager_KeyUp;

        m_MouseHookManager = new MouseHookListener(new GlobalHooker());
        m_MouseHookManager.Enabled = true;
        m_MouseHookManager.MouseDown += HookManager_MouseDown;
        m_MouseHookManager.MouseUp += HookManager_MouseUp;
    }

    private void Form3_Load(object sender, EventArgs e)
    {
        //ShowCursor(0);
        //MoveCursor();
    }
    private void HookManager_KeyDown(object sender, KeyEventArgs e)
    {
        label1.Text = e.KeyData.ToString() + " Pressed";
    }

    private void HookManager_KeyUp(object sender, KeyEventArgs e)
    {
        label1.Text = e.KeyData.ToString() + " Released";
    }

    private void HookManager_MouseUp(object sender, MouseEventArgs e)
    {
        label1.Text = e.Button.ToString() + " Released";
    }

    private void HookManager_MouseDown(object sender, MouseEventArgs e)
    {
        label1.Text = e.Button.ToString() + " Pressed";
        ShowCursor(0);
        MoveCursor();
        System.Threading.Thread.Sleep(5000);//5 sec
        RestoreCursor(this);
        ShowCursor(1);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //RestoreCursor(this);
        //ShowCursor(1);
    }

    private void Form3_MouseMove(object sender, MouseEventArgs e)
    {
        //MoveCursor();
    }

    private RECT MouseTrap;
    public void RestoreCursor(System.Windows.Forms.Form ThisForm)
    {
        var _with1 = MouseTrap;
        _with1.Top = 0;
        _with1.Left = 0;
        _with1.Right = Screen.PrimaryScreen.Bounds.Width;
        _with1.Bottom = Screen.PrimaryScreen.Bounds.Height;

        ClipCursor(_with1);
    }

    private void MoveCursor()
    {
        // set the Current cursor, move the cursor's Position,
        // and set its clipping rectangle to the form.
        this.Cursor = new Cursor(Cursor.Current.Handle);
        Cursor.Position = new Point(this.Left, this.Top);
        Cursor.Clip = new Rectangle(this.Left, this.Top, this.Width, this.Height);
    }
}
</code>```

I am developing one sample application My requirement is when user clicks on anywhere on desktop for example click on Windows "Start" button then Hide the cursor for 2 sec then show the cursor after 2 sec at the same position.

For that I have written above code and used Thread.Sleep(2000) for waiting but cursor position restores to Form's left.

https://stackoverflow.com/questions/16781948/how-can-i-hook-globaly-all-the-keys-and-all-the-mouse-buttons/16782294

GlobalMouseHookDLL

答:
you can achieve that using System.Windows.Forms.Timer.

Declare Timer on your form.

```<code>public partial class Form3 : Form
{
    private Timer timer = new Timer();
</code>```

Set it on Form_Load

```<code>timer.Enabled = false;
timer.Tick += Timer_Tick;
timer.Interval = 5000;
</code>```

When user moves mouse, instead of Thread.Sleep activate timer. When timer ticks (when specified 5000 milliseconds pass), Timer_Tick method will execute. In it, show pointer.

```<code>private void HookManager_MouseDown(object sender, MouseEventArgs e)
{
    label1.Text = e.Button.ToString() + " Pressed";
    ShowCursor(0);
    MoveCursor();
    timer.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{

    RestoreCursor(this);
    ShowCursor(1);
    timer.Stop();
}
</code>```

Title: Hide mouse cursor for specific time

Body:
public partial class Form3 : Form
{
    private readonly KeyboardHookListener m_KeyboardHookManager;
    private readonly MouseHookListener m_MouseHookManager;

    [DllImport("user32")]
    private static extern Int32 ClipCursor(RECT lpRect);

    [DllImport("user32")]
    private static extern Int32 ShowCursor(Int32 bShow);

    [DllImport("user32.dll")]
    public static extern bool GetCursorPos(out POINT lpPoint);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;

        public static implicit operator Point(POINT point)
        {
            return new Point(point.X, point.Y);
        }
    }

    public static Point GetCursorPosition()
    {
        POINT lpPoint;
        GetCursorPos(out lpPoint);
        //bool success = User32.GetCursorPos(out lpPoint);
        // if (!success)

        return lpPoint;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public Int32 Left;
        public Int32 Top;
        public Int32 Right;
        public Int32 Bottom;
    }

    public Form3()
    {
        InitializeComponent();

        m_KeyboardHookManager = new KeyboardHookListener(new GlobalHooker());
        m_KeyboardHookManager.Enabled = true;
        m_KeyboardHookManager.KeyDown += HookManager_KeyDown;
        m_KeyboardHookManager.KeyUp += HookManager_KeyUp;

        m_MouseHookManager = new MouseHookListener(new GlobalHooker());
        m_MouseHookManager.Enabled = true;
        m_MouseHookManager.MouseDown += HookManager_MouseDown;
        m_MouseHookManager.MouseUp += HookManager_MouseUp;
    }

    private void Form3_Load(object sender, EventArgs e)
    {
        //ShowCursor(0);
        //MoveCursor();
    }
    private void HookManager_KeyDown(object sender, KeyEventArgs e)
    {
        label1.Text = e.KeyData.ToString() + " Pressed";
    }

    private void HookManager_KeyUp(object sender, KeyEventArgs e)
    {
        label1.Text = e.KeyData.ToString() + " Released";
    }

    private void HookManager_MouseUp(object sender, MouseEventArgs e)
    {
        label1.Text = e.Button.ToString() + " Released";
    }

    private void HookManager_MouseDown(object sender, MouseEventArgs e)
    {
        label1.Text = e.Button.ToString() + " Pressed";
        ShowCursor(0);
        MoveCursor();
        System.Threading.Thread.Sleep(5000);//5 sec
        RestoreCursor(this);
        ShowCursor(1);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //RestoreCursor(this);
        //ShowCursor(1);
    }

    private void Form3_MouseMove(object sender, MouseEventArgs e)
    {
        //MoveCursor();
    }

    private RECT MouseTrap;
    public void RestoreCursor(System.Windows.Forms.Form ThisForm)
    {
        var _with1 = MouseTrap;
        _with1.Top = 0;
        _with1.Left = 0;
        _with1.Right = Screen.PrimaryScreen.Bounds.Width;
        _with1.Bottom = Screen.PrimaryScreen.Bounds.Height;

        ClipCursor(_with1);
    }

    private void MoveCursor()
    {
        // set the Current cursor, move the cursor's Position,
        // and set its clipping rectangle to the form.
        this.Cursor = new Cursor(Cursor.Current.Handle);
        Cursor.Position = new Point(this.Left, this.Top);
        Cursor.Clip = new Rectangle(this.Left, this.Top, this.Width, this.Height);
    }
}

I am developing one sample application My requirement is when user clicks on anywhere on desktop for example click on Windows "Start" button then Hide the cursor for 2 sec then show the cursor after 2 sec at the same position.

For that I have written above code and used Thread.Sleep(2000) for waiting but cursor position restores to Form's left.

https://stackoverflow.com/questions/16781948/how-can-i-hook-globaly-all-the-keys-and-all-the-mouse-buttons/16782294

GlobalMouseHookDLL

Body:
you can achieve that using System.Windows.Forms.Timer.

Declare Timer on your form.

public partial class Form3 : Form
{
    private Timer timer = new Timer();

Set it on Form_Load

timer.Enabled = false;
timer.Tick += Timer_Tick;
timer.Interval = 5000;

When user moves mouse, instead of Thread.Sleep activate timer. When timer ticks (when specified 5000 milliseconds pass), Timer_Tick method will execute. In it, show pointer.

private void HookManager_MouseDown(object sender, MouseEventArgs e)
{
    label1.Text = e.Button.ToString() + " Pressed";
    ShowCursor(0);
    MoveCursor();
    timer.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{

    RestoreCursor(this);
    ShowCursor(1);
    timer.Stop();
}


问:
The transaction manager has disabled its support for remote/network transactions
I'm using SQL Server and ASP.NET. I have the following function:

```<code>Using js = daoFactory.CreateJoinScope()
    Using tran = New Transactions.TransactionScope()
        '...
        tran.Complete()
    End Using
End Using
</code>```

However, the following exception is thrown:

The transaction manager has disabled its support for remote/network transactions.

Description of JoinScope:

```<code>Public Class JoinScope
    Implements IJoinScope
    Implements IDisposable
    '...
End Class
</code>```

I have worked this way in another application with the same environment without a problem, but here I have this problem. What could I do to fix the issue?

答:
I had a store procedure that call another  store Procedure in "linked server".when I execute it in ssms it was ok,but when I call it in application(By Entity Framework),I got this error.
This article helped me and I used this script:

```<code>EXEC sp_serveroption @server = 'LinkedServer IP or Name',@optname = 'remote proc transaction promotion', @optvalue = 'false' ;
</code>```

for more detail look at this:
Linked server : The partner transaction manager has disabled its support for remote/network transactions

Body:
I'm using SQL Server and ASP.NET. I have the following function:

Using js = daoFactory.CreateJoinScope()
    Using tran = New Transactions.TransactionScope()
        '...
        tran.Complete()
    End Using
End Using

However, the following exception is thrown:

The transaction manager has disabled its support for remote/network transactions.

Description of JoinScope:

Public Class JoinScope
    Implements IJoinScope
    Implements IDisposable
    '...
End Class

I have worked this way in another application with the same environment without a problem, but here I have this problem. What could I do to fix the issue?

Body:
I had a store procedure that call another  store Procedure in "linked server".when I execute it in ssms it was ok,but when I call it in application(By Entity Framework),I got this error.
This article helped me and I used this script:

EXEC sp_serveroption @server = 'LinkedServer IP or Name',@optname = 'remote proc transaction promotion', @optvalue = 'false' ;

for more detail look at this:
Linked server : The partner transaction manager has disabled its support for remote/network transactions


问:
Map is omitting one curly braces
I have a json array which i am putting in a map.

```<code>  for(int i = 0; i < jsonarr.length(); i++){

                try {
                    JSONObject jsonobj = jsonarr.getJSONObject(i);

                    Iterator<Object> keysItr = jsonobj.keys();
                    while(keysItr.hasNext()) {
                        Object key = keysItr.next();
                        Object value = jsonobj.get((String) key);

                        map.put((String) key, value);

                    }
                System.out.println(map);
</code>```

But when I display the map it gives me a string in which there is one curly brace missing.

Output

```<code>{
  subtype=text,
  maxlength=22,
  values=[
    {
      "label":"Time",
      "value":"two",
      "selected":true
    },{
      "label":"Milk",
      "value":"hot"
    },{
      "label":"sky",
      "value":"blue"
    }
  ],
  (HERE)
  name=text-1496816623336,
  description=sa,
  className=form-control,
  label=Text Field,
  type=text,
  required=true
}
</code>```

I have used jackson and gson also but in that case they weren't even putting the whole json into map.It might be a stupid question but thanks.

EDIT :

Here is the JSON used to create the Map

```<code>[
  {
    "type":"select",
    "label":"Select",
    "className":"form-control",
    "name":"select-1496823185891",
    "values":[
      {
        "label":"Option 1",
        "value":"option-1",
        "selected":true
      },{
        "label":"Option 2",
        "value":"option-2"
      },{
        "label":"Option 3",
        "value":"option-3"
      }
    ]
  },{
    "type":"text",
    "label":"Text Field",
    "className":"form-control",
    "name":"text-1496823186970",
    "subtype":"text"
  }
]
</code>```

答:
If what I thing is that you expect to still have two JsonObject in the Map. The problem is that you iterate the JsonArray to put every key/value in the same Map, that means you override the previous value with the last one.

```<code>--first item :
map.put("type","select");
--seconds item:
map.put("type","text");

-- result
map.get("type"); //"text"
</code>```

A Map is flat, you can't have two values for two keys, you could create a collection of Map to store every value like a List<Map>, on each JsonObject to iterate, you create a new Map that you store in the list

Title: Map is omitting one curly braces

Body:
I have a json array which i am putting in a map.

  for(int i = 0; i < jsonarr.length(); i++){

                try {
                    JSONObject jsonobj = jsonarr.getJSONObject(i);

                    Iterator<Object> keysItr = jsonobj.keys();
                    while(keysItr.hasNext()) {
                        Object key = keysItr.next();
                        Object value = jsonobj.get((String) key);

                        map.put((String) key, value);

                    }
                System.out.println(map);

But when I display the map it gives me a string in which there is one curly brace missing.

Output

{
  subtype=text,
  maxlength=22,
  values=[
    {
      "label":"Time",
      "value":"two",
      "selected":true
    },{
      "label":"Milk",
      "value":"hot"
    },{
      "label":"sky",
      "value":"blue"
    }
  ],
  (HERE)
  name=text-1496816623336,
  description=sa,
  className=form-control,
  label=Text Field,
  type=text,
  required=true
}

I have used jackson and gson also but in that case they weren't even putting the whole json into map.It might be a stupid question but thanks.

EDIT :

Here is the JSON used to create the Map

[
  {
    "type":"select",
    "label":"Select",
    "className":"form-control",
    "name":"select-1496823185891",
    "values":[
      {
        "label":"Option 1",
        "value":"option-1",
        "selected":true
      },{
        "label":"Option 2",
        "value":"option-2"
      },{
        "label":"Option 3",
        "value":"option-3"
      }
    ]
  },{
    "type":"text",
    "label":"Text Field",
    "className":"form-control",
    "name":"text-1496823186970",
    "subtype":"text"
  }
]

Body:
If what I thing is that you expect to still have two JsonObject in the Map. The problem is that you iterate the JsonArray to put every key/value in the same Map, that means you override the previous value with the last one.

--first item :
map.put("type","select");
--seconds item:
map.put("type","text");

-- result
map.get("type"); //"text"

A Map is flat, you can't have two values for two keys, you could create a collection of Map to store every value like a List<Map>, on each JsonObject to iterate, you create a new Map that you store in the list


问:
ASP.NET MVC Page Won't Load and says "The resource cannot be found"
I am having a problem where I try to open my ASP.NET MVC application but I get the ASP.NET error page which says this:

Server Error in '/' Application.

The resource cannot be found.
  Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /EventScheduler/account.aspx/login

Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053**

I am using the URL trick from this blog post and that is why I have the .aspx in the URL:

http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/

It works on my other sandbox server (not a dev machine), and now I just deployed it to my production site as a new virtual directory, but for some reason it seems like it's actually looking for a .aspx file.

Any ideas?  I think I must be forgetting a step.

答:
Two Things Needs To Be Ensure:

1) Route should be proper in Global.ascx file

2) Don't forget to add reference of Controller Project in your Web Project (view is in separate project from controller)

The second one is my case.


问:
How can I add a class to select2 selectbox?
I want to add the class pink to my select2 selectbox. It works with the option but not with the box:

$("select").select2({
  templateResult: function (data, container) {
    if (data.element) {
      $(container).addClass($(data.element).attr("class"));
    }
    return data.text;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.yellow { background-color: yellow; }
.blue { background-color: blue }
.green { background-color: green }
.pink { background-color: pink }</code>```

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" rel="stylesheet"/>

<select class="select2 pink">
  <option value="AL" class="yellow">Alabama</option>
  <option value="AK" class="blue">Alaska</option>
  <option value="AZ" class="green" selected>Arizona</option>
</select>

<select class="select2">
  <option value="Something else" >Something else</option>
  <option value="Something else" >Something else</option>
  <option value="Something else">Something else</option>
</select>```

The result I need:

答:
The reason why it did not work is, I used the wrong select2 version.

It is important to integrate: select2.full.js

$(".mybox").select2({
 containerCssClass: "pink",
   templateResult: function (data, container) {
    if (data.element) {
      $(container).addClass($(data.element).attr("class"));
    }
    return data.text;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.yellow { background-color: yellow; }
.blue { background-color: blue }
.green { background-color: green }
.pink { background-color: pink!important }</code>```

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" rel="stylesheet"/>

<select class="select2 mybox">
  <option value="AL" class="yellow">Alabama</option>
  <option value="AK" class="blue">Alaska</option>
  <option value="AZ" class="green" selected>Arizona</option>
</select>```

Body:
I want to add the class pink to my select2 selectbox. It works with the option but not with the box:

$("select").select2({
  templateResult: function (data, container) {
    if (data.element) {
      $(container).addClass($(data.element).attr("class"));
    }
    return data.text;
  }
});

.yellow { background-color: yellow; }
.blue { background-color: blue }
.green { background-color: green }
.pink { background-color: pink }

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" rel="stylesheet"/>

<select class="select2 pink">
  <option value="AL" class="yellow">Alabama</option>
  <option value="AK" class="blue">Alaska</option>
  <option value="AZ" class="green" selected>Arizona</option>
</select>

<select class="select2">
  <option value="Something else" >Something else</option>
  <option value="Something else" >Something else</option>
  <option value="Something else">Something else</option>
</select>

The result I need:

Body:
The reason why it did not work is, I used the wrong select2 version.

It is important to integrate: select2.full.js

$(".mybox").select2({
 containerCssClass: "pink",
   templateResult: function (data, container) {
    if (data.element) {
      $(container).addClass($(data.element).attr("class"));
    }
    return data.text;
  }
});

.yellow { background-color: yellow; }
.blue { background-color: blue }
.green { background-color: green }
.pink { background-color: pink!important }

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.full.js"></script>

<select class="select2 mybox">
  <option value="AL" class="yellow">Alabama</option>
  <option value="AK" class="blue">Alaska</option>
  <option value="AZ" class="green" selected>Arizona</option>
</select>