问:
MongoDB + merge dictionaries
I have a database, which is constructed as

```<code>{"id":5,

 "type":{"hello":1,"sad":2,"luck":1}})
</code>```

Now I do the search

```<code> db.collection.distinct("type")
[
    {
        "hello" : 1,
        "sad" : 2
},
    {
        "hello" : 1,
        "sad" : 2,
        "luck" : 1
    }
]
</code>```

Now I want to sum all the values for each key to a result like:

```<code> { "hello" : 2, "sad" : 4, "luck" : 1 }}
</code>```

Is  there a method to achieve this, thanks in advance.

答:
Mongo 3.4.4 version

You can use $objectToArray which creates a array of key value pairs.

```<code>db.collection.aggregate({
    "$project": {
        "type": {
            "$objectToArray": "$type"
        }
    }
}, {
    "$unwind": "$type"
}, {
    "$group": {
        "_id": "$type.k",
        "count": {
            "$sum": "$type.v"
        }
    }
})
</code>```

Older Versions

You can use mapreduce

```<code>var map = function() {
   var type = this.type;
   Object.keys(type).forEach( function(key) { emit( key, type[key] ); } );
};

var reduce = function( key, values ) {
   return values.length;
};

db.collection.mapReduce( map, reduce, { out: { "inline" : 1}  } )['results']
</code>```

Title: MongoDB + merge dictionaries

Body:
I have a database, which is constructed as

{"id":5,

 "type":{"hello":1,"sad":2,"luck":1}})

Now I do the search

 db.collection.distinct("type")
[
    {
        "hello" : 1,
        "sad" : 2
},
    {
        "hello" : 1,
        "sad" : 2,
        "luck" : 1
    }
]

Now I want to sum all the values for each key to a result like:

 { "hello" : 2, "sad" : 4, "luck" : 1 }}

Is  there a method to achieve this, thanks in advance.

Body:
Mongo 3.4.4 version

You can use $objectToArray which creates a array of key value pairs.

db.collection.aggregate({
    "$project": {
        "type": {
            "$objectToArray": "$type"
        }
    }
}, {
    "$unwind": "$type"
}, {
    "$group": {
        "_id": "$type.k",
        "count": {
            "$sum": "$type.v"
        }
    }
})

Older Versions

You can use mapreduce

var map = function() {
   var type = this.type;
   Object.keys(type).forEach( function(key) { emit( key, type[key] ); } );
};

var reduce = function( key, values ) {
   return values.length;
};

db.collection.mapReduce( map, reduce, { out: { "inline" : 1}  } )['results']


来源: stackexchange

问:
java.util.Set is is failing ParameterizedType check
I have the following code. At runtime typeClassz is java.util.Set. But the typeClassz instanceof ParameterizedType evaluates to false. For java.util.Set it goes to else clause. Any ideas ?

```<code>final Type typeClassz = methods.get(index).getParameterTypes()[0];
if(typeClassz instanceof ParameterizedType){
    final ParameterizedType classType = (ParameterizedType) ((ParameterizedType) typeClassz).getActualTypeArguments()[0];
    return mongoTemplate.findOne(query, (Class<?>) classType.getRawType());
}else{
    return mongoTemplate.findOne(query, (Class<?>) typeClassz);
}
</code>```

答:
Method.getParameterTypes() returns Class<?>[], so your typeClassz can only be a Class<?>, not a ParameterizedType.

You should use getGenericParameterTypes() instead, which returns a Type[].

ContentLicense: CC BY-SA 3.0

Body:
I have the following code. At runtime typeClassz is java.util.Set. But the typeClassz instanceof ParameterizedType evaluates to false. For java.util.Set it goes to else clause. Any ideas ?

final Type typeClassz = methods.get(index).getParameterTypes()[0];
if(typeClassz instanceof ParameterizedType){
    final ParameterizedType classType = (ParameterizedType) ((ParameterizedType) typeClassz).getActualTypeArguments()[0];
    return mongoTemplate.findOne(query, (Class<?>) classType.getRawType());
}else{
    return mongoTemplate.findOne(query, (Class<?>) typeClassz);
}


问:
Table is specified twice, both as a target for 'UPDATE' and as a separate source for data in mysql
I have below query in mysql where I want to check if branch id and year of finance type from branch_master are equal with branch id and year of manager then update status in manager table against branch id in manager

```<code>UPDATE manager as m1
  SET m1.status = 'Y'
  WHERE m1.branch_id IN (
    SELECT m2.branch_id FROM manager as m2
     WHERE (m2.branch_id,m2.year) IN (
        (
          SELECT DISTINCT branch_id,year
            FROM `branch_master`
           WHERE type = 'finance'
        )
     )
  )
</code>```

but getting error

Table 'm1' is specified twice, both as a target for 'UPDATE' and as a
  separate source for data

答:
Try :::</p>

```<code>UPDATE manager as m1
SET m1.status = 'Y'
WHERE m1.branch_id IN (
  (SELECT DISTINCT branch_id
  FROM branch_master
  WHERE type = 'finance'))
  AND m1.year IN ((SELECT DISTINCT year
  FROM branch_master
  WHERE type = 'finance'))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have below query in mysql where I want to check if branch id and year of finance type from branch_master are equal with branch id and year of manager then update status in manager table against branch id in manager

UPDATE manager as m1
  SET m1.status = 'Y'
  WHERE m1.branch_id IN (
    SELECT m2.branch_id FROM manager as m2
     WHERE (m2.branch_id,m2.year) IN (
        (
          SELECT DISTINCT branch_id,year
            FROM `branch_master`
           WHERE type = 'finance'
        )
     )
  )

but getting error

Table 'm1' is specified twice, both as a target for 'UPDATE' and as a
  separate source for data

Body:
Try :::

UPDATE manager as m1
SET m1.status = 'Y'
WHERE m1.branch_id IN (
  (SELECT DISTINCT branch_id
  FROM branch_master
  WHERE type = 'finance'))
  AND m1.year IN ((SELECT DISTINCT year
  FROM branch_master
  WHERE type = 'finance'))


问:
How does LSTM in Keras access the input?
I am a little bit confused with how LSTM handle the input.
As we all know, the input of LSTM model in Keras has the form (batch_size, timesteps, input_dim).
My data is a time series data, where each sequence of n time steps are fed in to predict the value at n+1 time steps. Then, how do they access the input? They process each time steps in the sequence or have access to all of them at the same time?
As i check the number of parameters of each LSTM layer. They have 4*d*(n+d) where n is the dimension of input and d is the number of memory cell.
In my case i have d=10, and the number of parameters is 440 (without bias). So it means n=1 here, so seems like the input has dimension 1*1.
Then they have access to all of them spontaniously.
Anyone has some ideas about this?</p>

答:
First, think of a convolutional layer (it's easier).

It has parameters that depend only on the "filter size", "input channels" and "number of filters". But never on the "size of the image".

That happens because it's somewhat a "walking operation". The same group of filters is applied throughout the image. The total operations increase with the size of the image, but the parameters, which only define the filters, are independent from the image size. (Imagine a filter to detect a circle, this filter doesn't need to change to detect circles in different parts of the image, although it's applied for each step in the entire image).

So:

Parameters: number of filters * size of filters² * input channels

Calculation steps: size of image (considering strides, padding, etc.)

With LSTM layers, a similar thing happens. The parameters are related to what they call "gates". (Take a look here)

There is a "state", and "gates" that are applied in each time iteration to determine how the state will change.

The gates are not time dependent, though. The calculations are time iterations indeed, but every iteration uses the same group of gates.

Comparing to the convolutional layers:

Parameters: number of cells, data dimension

Calculation steps: time steps


问:
Why is an empty loop invalid in shell script?
I wanted to make my shell script wait infinitely and thought the below code would do it.

```<code>#!/bin/bash
while true
do
done
</code>```

However, the above script reports syntax error.

./Infinite_Loop.sh: line 4: syntax error near unexpected token `done'

./Infinite_Loop.sh: line 4: `done'

Unlike programming languages, why does shell script expect at least one statement in loops?

答:
It’s not part of Bash’s syntax. The manual tells us that:

The syntax of the while command is:

```<code>while test-commands; do consequent-commands; done
</code>```

In fact, if you dig in the Bash source code you can find how it parses a while loop:

```<code>shell_command:  ...
    |   WHILE compound_list DO compound_list DONE
</code>```

If you check compound_list’s definition you can see it must contains at least one shell instruction; it can’t be empty.

There’s no reason for writing an empty (infinite) loop unless you want to heat up your CPU and drain your battery. That’s probably why Bash disallow empty loops.

As others have stated you can use either true or : (the latter is an alias for the former):

```<code>while true; do true; done
while :; do :; done
</code>```

Body:
I wanted to make my shell script wait infinitely and thought the below code would do it.

#!/bin/bash
while true
do
done

However, the above script reports syntax error.

./Infinite_Loop.sh: line 4: syntax error near unexpected token `done'

./Infinite_Loop.sh: line 4: `done'

Unlike programming languages, why does shell script expect at least one statement in loops?

Body:
It’s not part of Bash’s syntax. The manual tells us that:

The syntax of the while command is:

while test-commands; do consequent-commands; done

In fact, if you dig in the Bash source code you can find how it parses a while loop:

shell_command:  ...
    |   WHILE compound_list DO compound_list DONE

If you check compound_list’s definition you can see it must contains at least one shell instruction; it can’t be empty.

There’s no reason for writing an empty (infinite) loop unless you want to heat up your CPU and drain your battery. That’s probably why Bash disallow empty loops.

As others have stated you can use either true or : (the latter is an alias for the former):

while true; do true; done
while :; do :; done


问:
GPT reload ad in the same div element
For single page apps, I'd like to know if it's possible to request a new ad, to replace existing ad in a div container

```<code>var slotName = '/blogs/peter/recentPosts' // this changes according to route
var adContainer = 'div-common-container' // this never changes
window.googletag.defineSlot(slotName), ['fluid'], adContainer).addService(this.googletag.pubads())
</code>```

The example I found so far, confirm that is possible to refresh existing slots, but my use case is different ( https://support.google.com/dfp_premium/answer/2694377?hl=en&ref_topic=4390040 )

My goal is to have a common ad container element for common template pages, and for each pageTransition where the taxonomy is different
request a new advert.

The current tests I did so far, try to just change the slotName and then call refresh() but it doesn't seem to work! For example (was way more complex than the following example, but just to expose the point):

```<code><!DOCTYPE html>
<html>
<head>
  <script async='async' src='https://www.googletagservices.com/tag/js/gpt.js'></script>
  <script>
    var myAddSlot
    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
  </script>

  <script>
    googletag.cmd.push(function() {
      myAddSlot = googletag.defineSlot('/6355419/Travel/Europe/France/Paris', ['fluid'], 'div-common-ad-container')
                  .addService(googletag.pubads());
      googletag.enableServices();
    });
  </script>
</head>
<body>
  <div id='div-common-ad-container' />
  <button id="refresh">refresh</button>
  <script>
  googletag.cmd.push(function() { googletag.display('div-common-ad-container'); });
  document.querySelector('#refresh').addEventListener('click', function () {
    googletag.destroySlots()
    googletag.cmd.push(function() {
      myAddSlot = googletag.defineSlot('/6355419/Travel', ['fluid'], 'div-common-ad-container')
                  .addService(googletag.pubads());
      googletag.enableServices();
    });
  })
  </script>
</body>
</html>
</code>```

答:
This may be useful for someone else in the future. Not sure if it's the best approach, but it works.

I'm destroying the slot with the method provided by gpt and also clearing the container element and the data-google-query-id attribute!

```<code><!DOCTYPE html>
<html>
<head>
  <script async='async' src='https://www.googletagservices.com/tag/js/gpt.js'></script>
  <script>
    var myAddSlot
    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
  </script>

  <script>
    googletag.cmd.push(function() {
      myAddSlot = googletag.defineSlot('/6355419/Travel/Europe/France/Paris', ['fluid'], 'div-common-ad-container')
                  .addService(googletag.pubads());
      googletag.enableServices();
    });
  </script>
</head>
<body>
  <div id='div-common-ad-container'></div>
  <button id="refresh">refresh</button>
  <script>
  googletag.cmd.push(function() { googletag.display('div-common-ad-container'); });
  document.querySelector('#refresh').addEventListener('click', function () {
    googletag.destroySlots()
    document.querySelector('#div-common-ad-container').setAttribute('data-google-query-id', '')
    document.querySelector('#div-common-ad-container').innerHTML = ''
    googletag.cmd.push(function() {
      myAddSlot = googletag.defineSlot('/6355419/Travel/Europe', ['fluid'], 'div-common-ad-container')
                  .addService(googletag.pubads());
      googletag.enableServices();
      googletag.display('div-common-ad-container');
    });
  })
  </script>
</body>
</html>
</code>```

Title: GPT reload ad in the same div element

Body:
For single page apps, I'd like to know if it's possible to request a new ad, to replace existing ad in a div container

var slotName = '/blogs/peter/recentPosts' // this changes according to route
var adContainer = 'div-common-container' // this never changes
window.googletag.defineSlot(slotName), ['fluid'], adContainer).addService(this.googletag.pubads())

The example I found so far, confirm that is possible to refresh existing slots, but my use case is different ( https://support.google.com/dfp_premium/answer/2694377?hl=en&ref_topic=4390040 )

My goal is to have a common ad container element for common template pages, and for each pageTransition where the taxonomy is different
request a new advert.

The current tests I did so far, try to just change the slotName and then call refresh() but it doesn't seem to work! For example (was way more complex than the following example, but just to expose the point):

<!DOCTYPE html>

  <button id="refresh">refresh</button>

Body:
This may be useful for someone else in the future. Not sure if it's the best approach, but it works.

I'm destroying the slot with the method provided by gpt and also clearing the container element and the data-google-query-id attribute!

<!DOCTYPE html>
<html>
<head>
  <script async='async' src='https://www.googletagservices.com/tag/js/gpt.js'></script>
  <script>
    var myAddSlot
    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
  </script>

  <script>
    googletag.cmd.push(function() {
      myAddSlot = googletag.defineSlot('/6355419/Travel/Europe/France/Paris', ['fluid'], 'div-common-ad-container')
                  .addService(googletag.pubads());
      googletag.enableServices();
    });
  </script>
</head>
<body>
  <div id='div-common-ad-container'></div>
  <button id="refresh">refresh</button>
  <script>
  googletag.cmd.push(function() { googletag.display('div-common-ad-container'); });
  document.querySelector('#refresh').addEventListener('click', function () {
    googletag.destroySlots()
    document.querySelector('#div-common-ad-container').setAttribute('data-google-query-id', '')
    document.querySelector('#div-common-ad-container').innerHTML = ''
    googletag.cmd.push(function() {
      myAddSlot = googletag.defineSlot('/6355419/Travel/Europe', ['fluid'], 'div-common-ad-container')
                  .addService(googletag.pubads());
      googletag.enableServices();
      googletag.display('div-common-ad-container');
    });
  })
  </script>
</body>
</html>


问:
redundant rows are then in answer
```<code>SELECT item_id,
       CREDITBAL= (SELECT Sum(quantity)
                   FROM   axi_quantity_registers
                   WHERE  from_where != 'OPENING'
                          AND transaction_type = 'C'),
       OPENBAL = (SELECT Sum(quantity)
                  FROM   axi_quantity_registers
                  WHERE  from_where = 'OPENING'),
       DEBITBAL = (SELECT Sum(quantity)
                   FROM   axi_quantity_registers
                   WHERE  transaction_type = 'D')
FROM   axi_quantity_registers
</code>```

答:
Looks like you want a GROUP BY with conditional aggregation:

```<code>SELECT item_id,
       sum(case when from_where != 'OPENING' AND transaction_type = 'C' then quantity end) as CREDITBAL,
       sum(case when from_where = 'OPENING' then quantity end) as OPENBAL,
       sum(case when transaction_type = 'D' then quantity end) as DEBITBAL
FROM   axi_quantity_registers
group by item_id
</code>```

Title: redundant rows are then in answer

Body:
Looks like you want a GROUP BY with conditional aggregation:

SELECT item_id,
       sum(case when from_where != 'OPENING' AND transaction_type = 'C' then quantity end) as CREDITBAL,
       sum(case when from_where = 'OPENING' then quantity end) as OPENBAL,
       sum(case when transaction_type = 'D' then quantity end) as DEBITBAL
FROM   axi_quantity_registers
group by item_id


问:
asp.net login Page
I have an asp.net webpage.  I want the other pages to expire when the user clicks the logout button.  Im not using the login control, im just using a textbox for the login page.  When the user enters username and password, i check to see if that matches with the one in the database.  How do i make it so when the user logs out, they cant click the back button, or just cant type the specific URL without goin through the login page first</p>

答:
This should be automatically handled by ASP.NET. Make sure that you are abandoning the Session when the user clicks logout and you have the configuration similar to this in web.config</p>

```<code><authentication mode="Forms">
<forms loginUrl="~/Login.aspx"
       defaultUrl="Default.aspx" timeout="30"
       slidingExpiration="true"/>
</authentication>
</code>```

ContentLicense: CC BY-SA 2.5

Title: asp.net login Page

Body:
This should be automatically handled by ASP.NET. Make sure that you are abandoning the Session when the user clicks logout and you have the configuration similar to this in web.config

<authentication mode="Forms">
<forms loginUrl="~/Login.aspx"
       defaultUrl="Default.aspx" timeout="30"
       slidingExpiration="true"/>
</authentication>


问:
Support library and compileSdkVersion version mismatch
I am buidling an application and I am using my old HTC Desire S to debug and test the application. On this phone runs Android version 2.3.5, and the minimum SDK of my application is set on 10.

Also, because of these awesome specs, my phone has trouble when importing JPEGs, as a bitmap, in ImageView (probably because of the size of the JPEGs), and crashes when handling certain files.

```<code>   public void showImage() {
            String filePath = contentDirectory + "/" + filesInFolder[image_index];
            ImageView imgView = (ImageView) findViewById(R.id.myimage);
            Bitmap bitmap = BitmapFactory.decodeFile(filePath);
            ImageView imgView = (ImageView) findViewById(R.id.myimage);
            imgView.setImageBitmap(bitmap);
        }
</code>```

After some searching around I figured that I should use Glide to fix my issues.

Following the instructions on the Glide GitHub page, I insert the following in build.gradle:

```<code>dependencies {
   compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
   compile 'com.android.support:support-v4:25.3.1'
   annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC1'
}
</code>```

And dislplay the image as:

```<code>public void showImage() {
        String filePath = contentDirectory + "/" + filesInFolder[image_index];
        ImageView imgView = (ImageView) findViewById(R.id.myimage);
        Glide.with(this).load(filePath).into(imgView);
}
</code>```

When running my application, it crashes. I therefore changed compile 'com.android.support:support-v4:25.3.1' into compile 'com.android.support:support-v4:10.3.1' (version 25 into 10).

I now get the error

This support library should not use a different version (10) than the
  compileSdkVersion (25)

And I therefore set compileSdkVersion to 10:

```<code>android {
    compileSdkVersion 10
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.XXX.myapplication"
        minSdkVersion 10
        targetSdkVersion 10
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
}
</code>```

After syncing the gradle file, I get a whole lot of errors, all of them are located within

C:...\MyApplication\app\build\intermediates\res\merged\debug\

If necessary I can post them all (there are many), but I think that the main issue here is that I get the error:

Cannot resolve symbol 'R'

Is there anyone who can provide a solution or point me in the right direction?

Crashdump at line:

Glide.with(this).load(filePath).into(imgView);

```<code>01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication I/dalvikvm: Failed resolving Lcom/bumptech/glide/Glide; interface 59 'Landroid/content/ComponentCallbacks2;'
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication W/dalvikvm: Link of class 'Lcom/bumptech/glide/Glide;' failed
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication I/dalvikvm: Could not find method com.bumptech.glide.Glide.with, referenced from method com.imageviewexample.ImageViewExample.showImage
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication W/dalvikvm: VFY: unable to resolve static method 17289: Lcom/bumptech/glide/Glide;.with (Landroid/app/Activity;)Lcom/bumptech/glide/RequestManager;
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication D/dalvikvm: VFY: replacing opcode 0x71 at 0x0028
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication D/dalvikvm: VFY: dead code 0x002b-0033 in Lcom/imageviewexample/ImageViewExample;.showImage ()V
01-06 04:05:13.959 21324-21324/com.example.XXX.myapplication D/AndroidRuntime: Shutting down VM
01-06 04:05:13.959 21324-21324/com.example.XXX.myapplication W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)
01-06 04:05:13.969 21324-21324/com.example.XXX.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                java.lang.NoClassDefFoundError: com.bumptech.glide.Glide
                                                                                at com.imageviewexample.ImageViewExample.showImage(ImageViewExample.java:78)
                                                                                at com.imageviewexample.ImageViewExample.onCreate(ImageViewExample.java:53)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1836)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1893)
                                                                                at android.app.ActivityThread.access$1500(ActivityThread.java:135)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1054)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:150)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:4385)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:507)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
                                                                                at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
The reason for me using Glide in the first place was a memory issue with bitmaps and ImageView. Unfortunately I and the helpful members above, were not able to solve the issue regarding the Glide crash as described above.

Rather than that I went back to my first problem, which was the memory issue, and solved that by including bitmap.recycle() within my code the moment a new bitmap was displayed.

Body:
I am buidling an application and I am using my old HTC Desire S to debug and test the application. On this phone runs Android version 2.3.5, and the minimum SDK of my application is set on 10.

Also, because of these awesome specs, my phone has trouble when importing JPEGs, as a bitmap, in ImageView (probably because of the size of the JPEGs), and crashes when handling certain files.

   public void showImage() {
            String filePath = contentDirectory + "/" + filesInFolder[image_index];
            ImageView imgView = (ImageView) findViewById(R.id.myimage);
            Bitmap bitmap = BitmapFactory.decodeFile(filePath);
            ImageView imgView = (ImageView) findViewById(R.id.myimage);
            imgView.setImageBitmap(bitmap);
        }

After some searching around I figured that I should use Glide to fix my issues.

Following the instructions on the Glide GitHub page, I insert the following in build.gradle:

dependencies {
   compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
   compile 'com.android.support:support-v4:25.3.1'
   annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC1'
}

And dislplay the image as:

public void showImage() {
        String filePath = contentDirectory + "/" + filesInFolder[image_index];
        ImageView imgView = (ImageView) findViewById(R.id.myimage);
        Glide.with(this).load(filePath).into(imgView);
}

When running my application, it crashes. I therefore changed compile 'com.android.support:support-v4:25.3.1' into compile 'com.android.support:support-v4:10.3.1' (version 25 into 10).

I now get the error

This support library should not use a different version (10) than the
  compileSdkVersion (25)

And I therefore set compileSdkVersion to 10:

android {
    compileSdkVersion 10
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.XXX.myapplication"
        minSdkVersion 10
        targetSdkVersion 10
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
}

After syncing the gradle file, I get a whole lot of errors, all of them are located within

C:...\MyApplication\app\build\intermediates\res\merged\debug\

If necessary I can post them all (there are many), but I think that the main issue here is that I get the error:

Cannot resolve symbol 'R'

Is there anyone who can provide a solution or point me in the right direction?

Crashdump at line:

Glide.with(this).load(filePath).into(imgView);

01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication I/dalvikvm: Failed resolving Lcom/bumptech/glide/Glide; interface 59 'Landroid/content/ComponentCallbacks2;'
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication W/dalvikvm: Link of class 'Lcom/bumptech/glide/Glide;' failed
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication I/dalvikvm: Could not find method com.bumptech.glide.Glide.with, referenced from method com.imageviewexample.ImageViewExample.showImage
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication W/dalvikvm: VFY: unable to resolve static method 17289: Lcom/bumptech/glide/Glide;.with (Landroid/app/Activity;)Lcom/bumptech/glide/RequestManager;
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication D/dalvikvm: VFY: replacing opcode 0x71 at 0x0028
01-06 04:05:13.929 21324-21324/com.example.XXX.myapplication D/dalvikvm: VFY: dead code 0x002b-0033 in Lcom/imageviewexample/ImageViewExample;.showImage ()V
01-06 04:05:13.959 21324-21324/com.example.XXX.myapplication D/AndroidRuntime: Shutting down VM
01-06 04:05:13.959 21324-21324/com.example.XXX.myapplication W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)
01-06 04:05:13.969 21324-21324/com.example.XXX.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                java.lang.NoClassDefFoundError: com.bumptech.glide.Glide
                                                                                at com.imageviewexample.ImageViewExample.showImage(ImageViewExample.java:78)
                                                                                at com.imageviewexample.ImageViewExample.onCreate(ImageViewExample.java:53)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1836)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1893)
                                                                                at android.app.ActivityThread.access$1500(ActivityThread.java:135)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1054)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:150)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:4385)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:507)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
                                                                                at dalvik.system.NativeStart.main(Native Method)


问:
Error: Could not find or load main class org.hibernate.dialect.DB2390Dialect
When I run my program I get this error:

Error: Could not find or load main class
  org.hibernate.dialect.DB2390Dialect

I have checked all the jar files required are in place. Please help. I guess there is problem with the hibernate configuration file. Find the configuration file below:

```<code><?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.password">batch</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="hibernate.connection.username">batch</property>
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">none</property>
        <mapping resource="galaxe.model.Network" />
    </session-factory>
</hibernate-configuration>
</code>```

答:
In configuration you need to mention for DB2390 as below
 property name="hibernate.dialect" value="org.hibernate.dialect.DB2390Dialect"

if you use oracle, it will be different
 property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect">

Body:
When I run my program I get this error:

Error: Could not find or load main class
  org.hibernate.dialect.DB2390Dialect

I have checked all the jar files required are in place. Please help. I guess there is problem with the hibernate configuration file. Find the configuration file below:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.password">batch</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="hibernate.connection.username">batch</property>
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">none</property>
        <mapping resource="galaxe.model.Network" />
    </session-factory>
</hibernate-configuration>


问:
Cannot add foreign key with WordPress wp_posts table
I'm trying to add a new table which has a relation with {wp_posts} table, This code is working properly in localhost and it passes all tests but it failed on server database and generates [Cannot add foreign key constraint].

The [post_id] field is exactly like {wp_posts->ID} field .. I don't know what I missed.

```<code>global $wpdb;
$charset_collate = $wpdb->collate;

$tbl_my_users = $wpdb->prefix . '_TABLE_NAME';

dbDelta( "CREATE TABLE IF NOT EXISTS {$tbl_my_users} (
            user_id BIGINT(20) UNSIGNED NOT NULL,
            post_id BIGINT(20) UNSIGNED NOT NULL,
            name VARCHAR(150) NOT NULL,
            email TINYTEXT NULL,
            INDEX (name),
            PRIMARY KEY  (user_id),
            CONSTRAINT Constr_Unique_UserID UNIQUE( user_id ),
            CONSTRAINT Constr_Unique_PostID UNIQUE( post_id ),
            CONSTRAINT Constr_Unique_User UNIQUE( name ),
            CONSTRAINT Constr_My_Users
                FOREIGN KEY FK_My_Users (post_id) REFERENCES {$wpdb->posts} (ID) ON DELETE CASCADE ON UPDATE CASCADE
        ) COLLATE {$charset_collate}" );
</code>```

答:
try this bewlo query     </p>

```<code>  global $wpdb;
$charset_collate = $wpdb->collate;

$tbl_my_users = $wpdb->prefix . '_TABLE_NAME';

dbDelta("CREATE TABLE IF NOT EXISTS  ".$tbl_my_users."  (
            user_id BIGINT(20) UNSIGNED NOT NULL,
            post_id BIGINT(20) UNSIGNED NOT NULL,
            name VARCHAR(150) NOT NULL,
            email TINYTEXT NULL,
            INDEX (name),
            PRIMARY KEY  (user_id),
            CONSTRAINT Constr_Unique_UserID UNIQUE( user_id ),
            CONSTRAINT Constr_Unique_PostID UNIQUE( post_id ),
            CONSTRAINT Constr_Unique_User UNIQUE( name ),
            CONSTRAINT Constr_My_Users
                FOREIGN KEY (`post_id`) REFERENCES ".$wpdb->prefix."posts (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
        ) COLLATE SET utf8 COLLATE utf8_general_ci" );
</code>```

Body:
I'm trying to add a new table which has a relation with {wp_posts} table, This code is working properly in localhost and it passes all tests but it failed on server database and generates [Cannot add foreign key constraint].

The [post_id] field is exactly like {wp_posts->ID} field .. I don't know what I missed.

global $wpdb;
$charset_collate = $wpdb->collate;

$tbl_my_users = $wpdb->prefix . '_TABLE_NAME';

dbDelta( "CREATE TABLE IF NOT EXISTS {$tbl_my_users} (
            user_id BIGINT(20) UNSIGNED NOT NULL,
            post_id BIGINT(20) UNSIGNED NOT NULL,
            name VARCHAR(150) NOT NULL,
            email TINYTEXT NULL,
            INDEX (name),
            PRIMARY KEY  (user_id),
            CONSTRAINT Constr_Unique_UserID UNIQUE( user_id ),
            CONSTRAINT Constr_Unique_PostID UNIQUE( post_id ),
            CONSTRAINT Constr_Unique_User UNIQUE( name ),
            CONSTRAINT Constr_My_Users
                FOREIGN KEY FK_My_Users (post_id) REFERENCES {$wpdb->posts} (ID) ON DELETE CASCADE ON UPDATE CASCADE
        ) COLLATE {$charset_collate}" );

Body:
try this bewlo query

  global $wpdb;
$charset_collate = $wpdb->collate;

$tbl_my_users = $wpdb->prefix . '_TABLE_NAME';

dbDelta("CREATE TABLE IF NOT EXISTS  ".$tbl_my_users."  (
            user_id BIGINT(20) UNSIGNED NOT NULL,
            post_id BIGINT(20) UNSIGNED NOT NULL,
            name VARCHAR(150) NOT NULL,
            email TINYTEXT NULL,
            INDEX (name),
            PRIMARY KEY  (user_id),
            CONSTRAINT Constr_Unique_UserID UNIQUE( user_id ),
            CONSTRAINT Constr_Unique_PostID UNIQUE( post_id ),
            CONSTRAINT Constr_Unique_User UNIQUE( name ),
            CONSTRAINT Constr_My_Users
                FOREIGN KEY (`post_id`) REFERENCES ".$wpdb->prefix."posts (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
        ) COLLATE SET utf8 COLLATE utf8_general_ci" );


问:
Reload Ajax Content from on.Change function after Page has been refreshed
I use a dropdown menu where the user can select specific subjects. If a subject is selected via dropdown, a textbox pops up via ajax and the user can enter stuff.

The problem is that if the form has been submitted and stuff in the form was missing or if the user simply refreshes the page, the ajax content (the text box) disappears and only shows up again, when another subject is selected.

This probably stems from my ajax script, which uses change and thus only puts the ajax-input into the div when the dropdown is changed again:

```<code>$(function() {
$('#subjectapp1').change(function()
{
var self = $(this);

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

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

My dropdown menu:

```<code><select name="subject1" id="subjectapp1">
<option value="">Please choose</option>
<?php foreach ($subjects as $subject){ ?>
  <option <?php if ($_POST['subject1'] == $fach['subject_id']) {echo 'selected';} ?> value="<?php echo $subject['subject_id']; ?>"><?php echo $subject['subject']; ?></option>
</code>```

The div it is loaded into:

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

The ajax content (subjectpartial1.php) simply contains a text box in which the user can enter his qualification.

Is there a possibility that the ajax content is automatically loaded into the div when the page refreshes without the need to change the subjects again?

EDIT (WORKS): Based on the comments I tried the following, which yields the desired result:

```<code>$(document).ready(function () {
// For loading the ajax content on refresh/form submit
    var subject1 = $('#subjectapp1');

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: subject1.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

$('#subjectapp1').change(function()
{
var self = $(this);

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

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

Thank you!

答:
You can do this along with your current code:</p>

```<code>$(document).ready(function () {
 $("#subjectapp1").trigger('change');
}
</code>```

Body:
I use a dropdown menu where the user can select specific subjects. If a subject is selected via dropdown, a textbox pops up via ajax and the user can enter stuff.

The problem is that if the form has been submitted and stuff in the form was missing or if the user simply refreshes the page, the ajax content (the text box) disappears and only shows up again, when another subject is selected.

This probably stems from my ajax script, which uses change and thus only puts the ajax-input into the div when the dropdown is changed again:

$(function() {
$('#subjectapp1').change(function()
{
var self = $(this);

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

});
});

My dropdown menu:

<select name="subject1" id="subjectapp1">
<option value="">Please choose</option>
<?php foreach ($subjects as $subject){ ?>
  <option <?php if ($_POST['subject1'] == $fach['subject_id']) {echo 'selected';} ?> value="<?php echo $subject['subject_id']; ?>"><?php echo $subject['subject']; ?></option>

The div it is loaded into:

The ajax content (subjectpartial1.php) simply contains a text box in which the user can enter his qualification.

Is there a possibility that the ajax content is automatically loaded into the div when the page refreshes without the need to change the subjects again?

EDIT (WORKS): Based on the comments I tried the following, which yields the desired result:

$(document).ready(function () {
// For loading the ajax content on refresh/form submit
    var subject1 = $('#subjectapp1');

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: subject1.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

$('#subjectapp1').change(function()
{
var self = $(this);

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

});
});

Thank you!

Body:
You can do this along with your current code:

$(document).ready(function () {
 $("#subjectapp1").trigger('change');
}


问:
How to display a list of records with value event in firebase?
I am using firebase to create a blog. And I am referring to firebase documentation for the same purpose.
I am wondering how to retrieve a list of records from the database using value event...!
Can someone explain me the difference between value event and child_added event?

答:
You can retrieve your data using below code. Here just console the data after that you can access what ever like. So here just get data. Like below :

```<code>var ref = firebase.database().ref();
ref.on("value", function(snapshot) {
   console.log(snapshot.val());
}, function (error) {
   console.log("Error: " + error.code);
});
</code>```

1) 'Value' event will be triggered every time the data changes and it will retrieve all data including children

2) child_added
This event type will be triggered once for every 'blog' and every time new 'blog' is added to our data. It is useful for reading list data because we get access of the added player and previous player from the list.

For Nested child try with below code

```<code>ref.on("value", function(snapshot) {
  snapshot.forEach(function(messageSnapshot) {
    console.log(messageSnapshot.val());
  }
});
</code>```

Body:
You can retrieve your data using below code. Here just console the data after that you can access what ever like. So here just get data. Like below :

var ref = firebase.database().ref();
ref.on("value", function(snapshot) {
   console.log(snapshot.val());
}, function (error) {
   console.log("Error: " + error.code);
});

1) 'Value' event will be triggered every time the data changes and it will retrieve all data including children

2) child_added
This event type will be triggered once for every 'blog' and every time new 'blog' is added to our data. It is useful for reading list data because we get access of the added player and previous player from the list.

For Nested child try with below code

ref.on("value", function(snapshot) {
  snapshot.forEach(function(messageSnapshot) {
    console.log(messageSnapshot.val());
  }
});


问:
Intellij checkstyle - setting path relative to the module
My company is switching from Eclipse to IntelliJ. In Eclipse we had a following configuration for suppression filters in checkstyle.xml

<module name="SuppressionFilter">
    <property name="file" value="${checkstyle.config.dir}/suppressions.xml"/>
</module>
<module name="SuppressionFilter">
    <property name="file" value="${common.checkstyle.config.dir}/global-suppressions.xml"/>
</module>
```

Where:

common.checkstyle.config.dir was an absolute path to the common project(module in IntelliJ).

checkstyle.config.dir was an relative path to the project(module), and has a value of checkstyle.config.dir=${root.dir}/config/checkstyle

We would like to define a path for this file in IntelliJ, so it would look for the suppression filter in each MODULE/config/checkstyle directory(each module has a different suppression).

Does anyone know if it is possible? We have tried to find a solution for quite some time, but no luck so far.

答:
The Checkstyle integration in Eclipse is more powerful in some respects than the one in IntelliJ. This is one such case, I believe.

I would recommend changing the Checkstyle setup so that you have only one Checkstyle configuration and a central suppressions file for all modules. As you will see, modules are more tightly related in IntelliJ than projects are in Eclipse, so this is actually a good idea.

In order to keep module-specific configuration and/or suppressions, you would have to do the following:

Define all of the module-specific configurations in the central Checkstyle settings (so you have module1-rules, module2-rules etc. in your list).

In each module, select the appropriate configuration from the drop-down box.

This is quite a lot of work though, so I think you will find centralizing the configuration more convenient. (By the way, here are the supported variables, none of which will help you, I'm afraid.)

Body:
My company is switching from Eclipse to IntelliJ. In Eclipse we had a following configuration for suppression filters in checkstyle.xml

<module name="SuppressionFilter">
    <property name="file" value="${checkstyle.config.dir}/suppressions.xml"/>
</module>
<module name="SuppressionFilter">
    <property name="file" value="${common.checkstyle.config.dir}/global-suppressions.xml"/>
</module>

Where:

common.checkstyle.config.dir was an absolute path to the common project(module in IntelliJ).

checkstyle.config.dir was an relative path to the project(module), and has a value of checkstyle.config.dir=${root.dir}/config/checkstyle

We would like to define a path for this file in IntelliJ, so it would look for the suppression filter in each MODULE/config/checkstyle directory(each module has a different suppression).

Does anyone know if it is possible? We have tried to find a solution for quite some time, but no luck so far.


问:
Weka J48 classification not following tree
My original tree was much bigger, but since I'm stuck with this issue for quite some time I decided to try to simplify my tree. I Ended up with something like this:

As you can see, I only have a single attribute called "LarguraBandaRede" with 3 possible nominal values "Congestionado", "Livre" and "Merda".

After that I exported the j48.model from weka to use on my java code.

With this piece of code I import the model to use as a classifier:

```<code>ObjectInputStream objectInputStream = new ObjectInputStream(in);
classifier = (J48) objectInputStream.readObject();
</code>```

After that I started to create a arraylist of my attributes and a Instances File

```<code>for (int i = 0; i <features.length; i++) {
        String feature = features[i];
        Attribute attribute;
        if (feature.equals("TamanhoDados(Kb)")) {
            attribute = new Attribute(feature);
        } else {
            String[] strings = null;
            if(i==0) strings = populateAttributes(7);
            if(i==1) strings = populateAttributes(10);
            ArrayList<String> attValues = new ArrayList<String>(Arrays.asList(strings));
            attribute = new Attribute(feature,attValues);
        }
        atts.add(attribute);
    }
</code>```

where populateAttributes gives the possible values for each attribute, in this case "Livre, Merda, Congestionado;" for LarguraBandaRede and "Sim,Nao" for Resultado, my class attribute.

```<code>Instances instances = new Instances("header",atts,atts.size());
instances.setClassIndex(instances.numAttributes()-1);
</code>```

After creating my instances is time to create my Instance File, that is, the instances that I'm trying to classify

```<code>Instance instanceLivre = new DenseInstance(features.length);
Instance instanceMediano = new DenseInstance(features.length);
Instance instanceCongestionado = new DenseInstance(features.length);
instanceLivre.setDataset(instances);
instanceMediano.setDataset(instances);
instanceCongestionado.setDataset(instances);
</code>```

then I set each of this instances with the 3 possible values for "LarguraBandaRede". 'instanceLivre' with "Livre", 'instanceMediano' with "Merda" and 'instanceCongestionado' with "Congestionado".

After that I only classify this 3 instances using the classifyInstance method

```<code>System.out.println(instance.toString());
double resp = classifier.classifyInstance(instance);
System.out.println("valor: "+resp);
</code>```

and this is my result:

As you can see, the instance that has Merda as "LarguraBandaRede" was classify to be the same class as Congestionado, the class 'Nao'. But that doesn't make any sense, since the tree above clearly show that when "LarguraBandaRede" is "Merda" or "Livre" the class should be the same.

So that's my question. How this happened and how to fix it?

Thanks in advance.

EDIT

I didn't know that this:

made any difference in the way the model works. But we have to follow this order when feeding a nominal attribute with possible values.

答: Have you checked if the weka nominal attribute index is equal in order to your populateAttributes method?

Body:
My original tree was much bigger, but since I'm stuck with this issue for quite some time I decided to try to simplify my tree. I Ended up with something like this:

As you can see, I only have a single attribute called "LarguraBandaRede" with 3 possible nominal values "Congestionado", "Livre" and "Merda".

After that I exported the j48.model from weka to use on my java code.

With this piece of code I import the model to use as a classifier:

ObjectInputStream objectInputStream = new ObjectInputStream(in);
classifier = (J48) objectInputStream.readObject();

After that I started to create a arraylist of my attributes and a Instances File

for (int i = 0; i <features.length; i++) {
        String feature = features[i];
        Attribute attribute;
        if (feature.equals("TamanhoDados(Kb)")) {
            attribute = new Attribute(feature);
        } else {
            String[] strings = null;
            if(i==0) strings = populateAttributes(7);
            if(i==1) strings = populateAttributes(10);
            ArrayList<String> attValues = new ArrayList<String>(Arrays.asList(strings));
            attribute = new Attribute(feature,attValues);
        }
        atts.add(attribute);
    }

where populateAttributes gives the possible values for each attribute, in this case "Livre, Merda, Congestionado;" for LarguraBandaRede and "Sim,Nao" for Resultado, my class attribute.

Instances instances = new Instances("header",atts,atts.size());
instances.setClassIndex(instances.numAttributes()-1);

After creating my instances is time to create my Instance File, that is, the instances that I'm trying to classify

Instance instanceLivre = new DenseInstance(features.length);
Instance instanceMediano = new DenseInstance(features.length);
Instance instanceCongestionado = new DenseInstance(features.length);
instanceLivre.setDataset(instances);
instanceMediano.setDataset(instances);
instanceCongestionado.setDataset(instances);

then I set each of this instances with the 3 possible values for "LarguraBandaRede". 'instanceLivre' with "Livre", 'instanceMediano' with "Merda" and 'instanceCongestionado' with "Congestionado".

After that I only classify this 3 instances using the classifyInstance method

System.out.println(instance.toString());
double resp = classifier.classifyInstance(instance);
System.out.println("valor: "+resp);

and this is my result:

As you can see, the instance that has Merda as "LarguraBandaRede" was classify to be the same class as Congestionado, the class 'Nao'. But that doesn't make any sense, since the tree above clearly show that when "LarguraBandaRede" is "Merda" or "Livre" the class should be the same.

So that's my question. How this happened and how to fix it?

Thanks in advance.

EDIT

I didn't know that this:

made any difference in the way the model works. But we have to follow this order when feeding a nominal attribute with possible values.


问:
How to include only certain properties and fields of my object to be serialized by Jackson?
I have a class I need to serialize and it contains a lot of properties and fields, but I only need a small subset to be serialized, not the entire class. I also want to guarantee that I won't inadvertently add fields in the future which would be serialized and break my expectation of what gets serialized by suddenly including something new.

So is there any annotation I can use to basically specify what gets serialize only?

I'd need like the opposite of @JsonIgnoreProperties. Something that acts as a whitelist instead of a blacklist.

答:
So far I have preferred using wrapper objects to achieve this whitelist effect (in my case the additional complication is that the POJO I want to selectively serialize is part of an object hierarchy, so using Views is not possible).

If MyClass is the original class and MyClassForJson is the wrapper, this is how I use it:

```<code>public class MyClassForJson {

    private MyClass wrapped;

    public MyClassForJson(MyClass toBeWrapped) {
        this.wrapped = toBeWrapped;
    }

    /**
     * Delegate method exposing a property
     */
    public String getExposedProperty() {
        return this.wrapped.getExposedProperty();
    }
}
</code>```

Now only properties I create delegate getter methods for will ever be exposed to Jackson when serializing, irrespective of how many properties I add to MyClass. Delegate methods can be auto-generated by most IDEs today for selected properties of the wrapped class.

If I want to have different sets of whitelisted properties for serializing MyClass in different ways, all I have to do is create different wrapper classes.

Body:
So far I have preferred using wrapper objects to achieve this whitelist effect (in my case the additional complication is that the POJO I want to selectively serialize is part of an object hierarchy, so using Views is not possible).

If MyClass is the original class and MyClassForJson is the wrapper, this is how I use it:

public class MyClassForJson {

    private MyClass wrapped;

    public MyClassForJson(MyClass toBeWrapped) {
        this.wrapped = toBeWrapped;
    }

    /**
     * Delegate method exposing a property
     */
    public String getExposedProperty() {
        return this.wrapped.getExposedProperty();
    }
}

Now only properties I create delegate getter methods for will ever be exposed to Jackson when serializing, irrespective of how many properties I add to MyClass. Delegate methods can be auto-generated by most IDEs today for selected properties of the wrapped class.

If I want to have different sets of whitelisted properties for serializing MyClass in different ways, all I have to do is create different wrapper classes.


问:
REST json api with symfony 2.7, form not validating even when filled
I'm trying to figure out why the form is not validating when I create one with a pre-populated entity with values coming from a json request.

Here is the controller in Symfony with the FosRestBundle already configured:

```<code>public function createAction(Request $request)
{
    $house = new House();
    $house->setTitle($request->get('title'));
    $house->setDescription($request->get('description'));
    $house->setPostcode($request->get('postCode'));
    $house->setPhoneNumber((int) $request->get('phoneNumber'));
    $availability = $request->get('available') ? true : false;
    $house->setAvailability($availability);

    $form = $this->createCreateForm($house);

    $form->handleRequest($request);

    $response = new JsonResponse();

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($house);
        $em->flush();

        return $response->setData(array(
            'success' => true
        ));
    }

    return $response->setData(array(
        'success' => false,
        'errors' => $this->getFormErrors($form)
    ));
}

private function createCreateForm(House $entity)
{
    $form = $this->createForm(new HouseType(), $entity, array(
        'action' => $this->generateUrl('houses_create'),
        'method' => 'POST',
        'csrf_protection' => false
    ));

    return $form;
}
</code>```

the yaml config file:

```<code># app/config/config.yml
fos_rest:
    param_fetcher_listener: true
    body_listener: true
    routing_loader:
        default_format: json
    exception:
        enabled: true
    # configure the view handler
    view:
        force_redirects:
            html: true
        formats:
            json: true
            xml: true
        templating_formats:
            html: true
    # add a content negotiation rule, enabling support for json/xml for the entire website
    format_listener:
        enabled: true
        rules:
            - { path: ^/, priorities: [ json, xml, html ], fallback_format: html, prefer_extension: false }
</code>```

If I execute $form->get('title')->getData() for example I can see that the form is filled correctly but still doesn't pass the validation and when I execute $this->getFormErrors($form) I just get an empty array.

Any idea on how I could debug this issue?

答:
In order to receive json, you need to enable the body listener feature.

In your config.yml:

```<code>fos_rest:
    body_listener: true
</code>```

You should also check the documentation for advanced usage.

Body:
I'm trying to figure out why the form is not validating when I create one with a pre-populated entity with values coming from a json request.

Here is the controller in Symfony with the FosRestBundle already configured:

public function createAction(Request $request)
{
    $house = new House();
    $house->setTitle($request->get('title'));
    $house->setDescription($request->get('description'));
    $house->setPostcode($request->get('postCode'));
    $house->setPhoneNumber((int) $request->get('phoneNumber'));
    $availability = $request->get('available') ? true : false;
    $house->setAvailability($availability);

    $form = $this->createCreateForm($house);

    $form->handleRequest($request);

    $response = new JsonResponse();

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($house);
        $em->flush();

        return $response->setData(array(
            'success' => true
        ));
    }

    return $response->setData(array(
        'success' => false,
        'errors' => $this->getFormErrors($form)
    ));
}

private function createCreateForm(House $entity)
{
    $form = $this->createForm(new HouseType(), $entity, array(
        'action' => $this->generateUrl('houses_create'),
        'method' => 'POST',
        'csrf_protection' => false
    ));

    return $form;
}

the yaml config file:

# app/config/config.yml
fos_rest:
    param_fetcher_listener: true
    body_listener: true
    routing_loader:
        default_format: json
    exception:
        enabled: true
    # configure the view handler
    view:
        force_redirects:
            html: true
        formats:
            json: true
            xml: true
        templating_formats:
            html: true
    # add a content negotiation rule, enabling support for json/xml for the entire website
    format_listener:
        enabled: true
        rules:
            - { path: ^/, priorities: [ json, xml, html ], fallback_format: html, prefer_extension: false }

If I execute $form->get('title')->getData() for example I can see that the form is filled correctly but still doesn't pass the validation and when I execute $this->getFormErrors($form) I just get an empty array.

Any idea on how I could debug this issue?

Body:
In order to receive json, you need to enable the body listener feature.

In your config.yml:

fos_rest:
    body_listener: true

You should also check the documentation for advanced usage.


问:
Using Cloud Stream Test does not work
I tried some stuff with spring-cloud-stream. Everything works and now I tried to write some test cases. Unfortunately they are not working. I reduced everything to the following (Everything is in the same boot app):

The Sender:

```<code>@EnableBinding(Sender.Emitter.class)
public class Sender {

    public interface Emitter {
        String CHANNEL = "emitter";
        @Output(CHANNEL)
        MessageChannel events();
    }
    private Emitter emitter;

    public Sender(Emitter emitter) {
        this.emitter = emitter;
    }

    public void sendMessage(String massage) {
        emitter.events().send(MessageBuilder.withPayload(massage).build());
    }
}
</code>```

The Receiver:

```<code>@EnableBinding(Receiver.Subscriber.class)
public class Receiver {
    public interface Subscriber {
        String CHANNEL = "subscriber";
        @Input(CHANNEL)
        SubscribableChannel events();
    }
    private String lastMessage;

    public String getLastMessage() {
        return lastMessage;
    }

    @StreamListener(Subscriber.CHANNEL)
    public void event(String message) {
        this.lastMessage = message;
    }
}
</code>```

My config:

```<code>spring:
  cloud:
    stream:
      default-binder: rabbit
      bindings:
        emitter:
          destination: testtock
          content-type: application/json
        subscriber:
          destination: testtock
</code>```

The Test:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class BasicTest {

    @Autowired
    private Receiver receiver;
    @Autowired
    private Sender sender;

    @Test
    public void test() throws InterruptedException {
        String massage = UUID.randomUUID().toString();
        sender.sendMessage(massage);
        //Thread.sleep(1000);
        assertEquals(massage, receiver.getLastMessage());
    }
}
</code>```

I want use spring-cloud-stream-test-support for testing to not need a AMQP message broker. Outside of testing I use a rabbitmq, there everything is working.
Maybe the spring-cloud-stream-test-support does not really route messages? Or what is the Problem here?

答:
Maybe the spring-cloud-stream-test-support does not really route messages?

Correct; the test binder is just a harness, it doesn't route between bindings; it's unusual to have a producer and consumer binding for the same destination in the same app.

When you send a message in a test, you have to query the binder to ensure it was sent expected. You use a MessageCollector to do that. See the documentation and you can also look at the tests for some of the out of the box apps.

Title: Using Cloud Stream Test does not work

Body:
I tried some stuff with spring-cloud-stream. Everything works and now I tried to write some test cases. Unfortunately they are not working. I reduced everything to the following (Everything is in the same boot app):

The Sender:

@EnableBinding(Sender.Emitter.class)
public class Sender {

    public interface Emitter {
        String CHANNEL = "emitter";
        @Output(CHANNEL)
        MessageChannel events();
    }
    private Emitter emitter;

    public Sender(Emitter emitter) {
        this.emitter = emitter;
    }

    public void sendMessage(String massage) {
        emitter.events().send(MessageBuilder.withPayload(massage).build());
    }
}

The Receiver:

@EnableBinding(Receiver.Subscriber.class)
public class Receiver {
    public interface Subscriber {
        String CHANNEL = "subscriber";
        @Input(CHANNEL)
        SubscribableChannel events();
    }
    private String lastMessage;

    public String getLastMessage() {
        return lastMessage;
    }

    @StreamListener(Subscriber.CHANNEL)
    public void event(String message) {
        this.lastMessage = message;
    }
}

My config:

spring:
  cloud:
    stream:
      default-binder: rabbit
      bindings:
        emitter:
          destination: testtock
          content-type: application/json
        subscriber:
          destination: testtock

The Test:

@RunWith(SpringRunner.class)
@SpringBootTest
public class BasicTest {

    @Autowired
    private Receiver receiver;
    @Autowired
    private Sender sender;

    @Test
    public void test() throws InterruptedException {
        String massage = UUID.randomUUID().toString();
        sender.sendMessage(massage);
        //Thread.sleep(1000);
        assertEquals(massage, receiver.getLastMessage());
    }
}

I want use spring-cloud-stream-test-support for testing to not need a AMQP message broker. Outside of testing I use a rabbitmq, there everything is working.
Maybe the spring-cloud-stream-test-support does not really route messages? Or what is the Problem here?


问:
Asp.Identity OWIN Cookie not Authenticating
Below is the code I use to sign in. It comes back and says success. But If I tried to get the UserID, or do a User.Identity.IsAuthenticated on any page, it says false.

I can't figure out what could be going on here.

```<code>var SignInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

        var result = SignInManager.PasswordSignIn(txtUsername.Text, txtPassword.Text, false, true);

        switch (result)
        {
            case SignInStatus.Success:
                Response.Redirect(User.IsInRole("Admin") ? "~/Admin/Dashboard.aspx" : "~/User/Dashboard.aspx");
                break;
            case SignInStatus.LockedOut:
                Response.Redirect("~/Account/Lockout");
                break;
            case SignInStatus.RequiresVerification:
                Response.Redirect("~/Account/Unknown",true);
                break;
            case SignInStatus.Failure:
            default:
                txtErrorMessage.Text = "Invalid Username/Password";
                txtPassword.Text = "";
                break;
        }
</code>```

It's almost like its saying Success, but its really not working correctly.
I've tried a lot of different things, but nothing seems to keep me authenticated at all.

答:
For some reason, changing this:

```<code>var result = SignInManager.PasswordSignIn(txtUsername.Text, txtPassword.Text, false, true);
</code>```

to this fixed it, have no idea why.

```<code>var result = await SignInManager.PasswordSignInAsync(txtUsername.Text, txtPassword.Text, false, true);
</code>```

Body:
Below is the code I use to sign in. It comes back and says success. But If I tried to get the UserID, or do a User.Identity.IsAuthenticated on any page, it says false.

I can't figure out what could be going on here.

var SignInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

        var result = SignInManager.PasswordSignIn(txtUsername.Text, txtPassword.Text, false, true);

        switch (result)
        {
            case SignInStatus.Success:
                Response.Redirect(User.IsInRole("Admin") ? "~/Admin/Dashboard.aspx" : "~/User/Dashboard.aspx");
                break;
            case SignInStatus.LockedOut:
                Response.Redirect("~/Account/Lockout");
                break;
            case SignInStatus.RequiresVerification:
                Response.Redirect("~/Account/Unknown",true);
                break;
            case SignInStatus.Failure:
            default:
                txtErrorMessage.Text = "Invalid Username/Password";
                txtPassword.Text = "";
                break;
        }

It's almost like its saying Success, but its really not working correctly.
I've tried a lot of different things, but nothing seems to keep me authenticated at all.

Body:
For some reason, changing this:

var result = SignInManager.PasswordSignIn(txtUsername.Text, txtPassword.Text, false, true);

to this fixed it, have no idea why.

var result = await SignInManager.PasswordSignInAsync(txtUsername.Text, txtPassword.Text, false, true);


问:
Java exception factory for higher level exceptions
I am looking to create a exception factory

I have a service that connects to different data stores and these data stores throw a number of exceptions.
I do not want to return these exceptions to users of the service but instead return higher level exception
e.g. storeServiceTransientReadException

When connecting to the data store I will use a try, catch throw pattern; e.g for a Cassandra connection:

```<code>public ResultSet safeExecute(Statement statement) throws StoreServiceException {
    try {
        return session.execute(statement);
    }
    catch(QueryExecutionException ex){
        log.error(ex);
        StoreServiceException storeException = StoreServiceExceptionFactory.getTransientException(ex);
        throw storeException;
    }
</code>```

In the cassandra example I want the factory to create a read or write storeServiceException  exception depending on whether the exception is a ReadFailureException, ReadTimeoutException, WriteFailureException or  WriteTimeoutException

For other data stores I want to follow the same pattern then users of the service will only have to worry about the service errors and not specific data store errors.

For the factory I was think something along the lines of (in pseudo):

```<code>public class ExceptionsFactory {

public StoreServiceTransientException getTransientException(Exception ex){

    if  ReadException
        return  StoreServiceTransientException("read exception ")

    if WriteException
        return  StoreServiceTransientException("write exception ")

}

public StoreServiceNonTransientException getTransientNonException(Exception ex){

    if  ReadException
        return  StoreServiceNonTransientException("read exception ")

    if WriteException
        return  StoreServiceNonTransientException("write exception ")

}
</code>```

But I cannot  find many online example of this which worries me.
It is a really bad idea?
I should just have lots more specific catch blocks that return the storeServiceException I want?

答:
It is a really bad idea? In my opinion, yes. This is a bad idea. The expensive part of using Exception(s) is filling in the stack trace. If you pre-create and save the Exception you throw then the stack trace will be meaningless (or at least of greatly reduced value). You aren't currently logging stack traces, so I would also change

```<code>log.error(ex);
</code>```

to

```<code>log.error("Caught exception: " + ex.getMessage(), ex);
</code>```

And similarly instantiate exceptions with the underlying cause -

```<code>throw new storeServiceException("Exception in storage.", ex);
</code>```

And the name should follow normal naming conventions. Java class names start with a capital letter - yours' looks like a variable.

Body:
I am looking to create a exception factory

I have a service that connects to different data stores and these data stores throw a number of exceptions.
I do not want to return these exceptions to users of the service but instead return higher level exception
e.g. storeServiceTransientReadException

When connecting to the data store I will use a try, catch throw pattern; e.g for a Cassandra connection:

public ResultSet safeExecute(Statement statement) throws StoreServiceException {
    try {
        return session.execute(statement);
    }
    catch(QueryExecutionException ex){
        log.error(ex);
        StoreServiceException storeException = StoreServiceExceptionFactory.getTransientException(ex);
        throw storeException;
    }

In the cassandra example I want the factory to create a read or write storeServiceException  exception depending on whether the exception is a ReadFailureException, ReadTimeoutException, WriteFailureException or  WriteTimeoutException

For other data stores I want to follow the same pattern then users of the service will only have to worry about the service errors and not specific data store errors.

For the factory I was think something along the lines of (in pseudo):

public class ExceptionsFactory {

public StoreServiceTransientException getTransientException(Exception ex){

    if  ReadException
        return  StoreServiceTransientException("read exception ")

    if WriteException
        return  StoreServiceTransientException("write exception ")

}

public StoreServiceNonTransientException getTransientNonException(Exception ex){

    if  ReadException
        return  StoreServiceNonTransientException("read exception ")

    if WriteException
        return  StoreServiceNonTransientException("write exception ")

}

But I cannot  find many online example of this which worries me.
It is a really bad idea?
I should just have lots more specific catch blocks that return the storeServiceException I want?

Body:
It is a really bad idea? In my opinion, yes. This is a bad idea. The expensive part of using Exception(s) is filling in the stack trace. If you pre-create and save the Exception you throw then the stack trace will be meaningless (or at least of greatly reduced value). You aren't currently logging stack traces, so I would also change

log.error(ex);

to

log.error("Caught exception: " + ex.getMessage(), ex);

And similarly instantiate exceptions with the underlying cause -

throw new storeServiceException("Exception in storage.", ex);

And the name should follow normal naming conventions. Java class names start with a capital letter - yours' looks like a variable.


问:
Notepad User defined Language Folding LESS
I have an Issue with Notpad++ and LESS. I can't get the normal folding to work.
Notepad++ is the Editor I prefer the most so I wouldn't want to change.
At the Moment a LESS file looks like:

I've searched and googled to find an solution but was unsuccessful.
Most of the time it says to go in the menu 'Define your language...' and define there the starting and endpoints.
I've tried that but the result doesn't change.

I would love some advice on how to fix this since the next project is the 5th or so with LESS and I'm getting pretty annoyed by files with 1500 lines without folding.

Thank you Guys for your help.

答:
So I've finally found an solution.
You not only need to ad '{' as start and '}' as endpoint, you also need to erase '{}' from Operators & Delimiters (4. tab).</p>