问:
Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4
I am doing assets pre-compile, and running the application in production mode. After compilation when I load the my index page I got followings warnings in the chrome console:

```<code>Failed to decode downloaded font: http://localhost:3000/fonts/ionicons.ttf?v=2.0.0
prospects:1 OTS parsing error: invalid version tag
Failed to decode downloaded font: http://localhost:3000/fonts/ionicons.woff?v=2.0.0
prospects:1 OTS parsing error: invalid version tag
</code>```

The issue is its not loading icons instead of that its showing squares.

we used the custom fonts and the code is:

```<code>@font-face {
  font-family: 'icomoon';
  src: font-url('icomoon.eot');
  src: font-url('icomoon.eot?#iefix') format('embedded-opentype'),
       font-url('icomoon.ttf') format('truetype'),
       font-url('icomoon.woff') format('woff'),
       font-url('icomoon.svg#icomoon') format('svg');
  font-weight: normal;
  font-style: normal;
}
</code>```

I don't know what is missing from my end . I searched a lot and also tried solution but not got any success.In development mode its working fine but don't know why its showing square in the production mode.

答:
When using angular-cli, this is what works for me:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <staticContent>
            <remove fileExtension=".eot" />
            <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
            <remove fileExtension=".ttf" />
            <mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
            <remove fileExtension=".svg" />
            <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
            <remove fileExtension=".woff" />
            <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
            <remove fileExtension=".woff2" />
            <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
            <remove fileExtension=".json" />
            <mimeMap fileExtension=".json" mimeType="application/json" />
        </staticContent>
        <rewrite>
            <rules>
                <rule name="AngularJS" stopProcessing="true">
                    <match url="^(?!.*(.bundle.js|.bundle.js.map|.bundle.js.gz|.bundle.css|.bundle.css.gz|.chunk.js|.chunk.js.map|.png|.jpg|.ico|.eot|.svg|.woff|.woff2|.ttf|.html)).*$" />
                    <conditions logicalGrouping="MatchAll">
                    </conditions>
                    <action type="Rewrite" url="/"  appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

Body:
I am doing assets pre-compile, and running the application in production mode. After compilation when I load the my index page I got followings warnings in the chrome console:

Failed to decode downloaded font: http://localhost:3000/fonts/ionicons.ttf?v=2.0.0
prospects:1 OTS parsing error: invalid version tag
Failed to decode downloaded font: http://localhost:3000/fonts/ionicons.woff?v=2.0.0
prospects:1 OTS parsing error: invalid version tag

The issue is its not loading icons instead of that its showing squares.

we used the custom fonts and the code is:

@font-face {
  font-family: 'icomoon';
  src: font-url('icomoon.eot');
  src: font-url('icomoon.eot?#iefix') format('embedded-opentype'),
       font-url('icomoon.ttf') format('truetype'),
       font-url('icomoon.woff') format('woff'),
       font-url('icomoon.svg#icomoon') format('svg');
  font-weight: normal;
  font-style: normal;
}

I don't know what is missing from my end . I searched a lot and also tried solution but not got any success.In development mode its working fine but don't know why its showing square in the production mode.

Body:
When using angular-cli, this is what works for me:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <staticContent>
            <remove fileExtension=".eot" />
            <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
            <remove fileExtension=".ttf" />
            <mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
            <remove fileExtension=".svg" />
            <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
            <remove fileExtension=".woff" />
            <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
            <remove fileExtension=".woff2" />
            <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
            <remove fileExtension=".json" />
            <mimeMap fileExtension=".json" mimeType="application/json" />
        </staticContent>
        <rewrite>
            <rules>
                <rule name="AngularJS" stopProcessing="true">
                    <match url="^(?!.*(.bundle.js|.bundle.js.map|.bundle.js.gz|.bundle.css|.bundle.css.gz|.chunk.js|.chunk.js.map|.png|.jpg|.ico|.eot|.svg|.woff|.woff2|.ttf|.html)).*$" />
                    <conditions logicalGrouping="MatchAll">
                    </conditions>
                    <action type="Rewrite" url="/"  appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>


来源: stackexchange

问:
Ohm symbol shows in gnuplot wxt window, exported SVG from the window, but not in SVG term output
I have a sequence of gnuplot commands that produces a label with an underscript _{1} and the Ω symbol {/Symbol W} preceded by a small space &{.}, which

show correctly in the wxt window

show correctly on a  SVG file exported from the wxt window

shows no underscript and .W if plotted to the SVG terminal

Here's a snippet of the code:

```<code>set label 3 "R_{1} 100&{.}{/Symbol W}"
set terminal svg size 1024,768 dynamic font 'Lohit' fsize 14 enhanced background 'white'
set output 'svg-file.svg'
plot ...
set terminal wxt 0 font 'Lohit,14' enhanced
set output
plot ...
</code>```

I set both terminal to enhanced mode. What am I missing?

答:
The output of your example with gnuplot's svg terminal contains the label as

```<code><tspan font-family="Symbol" >W</tspan>
</code>```

which leaves it to the viewer/browser to display it correctly. Your example works fine for me with Chrome/Edge, but not with Firefox.

The output of the wxt-svg-export doesn't contain text like show above, but the text is converted to paths in order to avoid such platform and viewer dependency (but has other drawbacks)

ContentLicense: CC BY-SA 3.0

Body:
I have a sequence of gnuplot commands that produces a label with an underscript _{1} and the Ω symbol {/Symbol W} preceded by a small space &{.}, which

show correctly in the wxt window

show correctly on a  SVG file exported from the wxt window

shows no underscript and .W if plotted to the SVG terminal

Here's a snippet of the code:

set label 3 "R_{1} 100&{.}{/Symbol W}"
set terminal svg size 1024,768 dynamic font 'Lohit' fsize 14 enhanced background 'white'
set output 'svg-file.svg'
plot ...
set terminal wxt 0 font 'Lohit,14' enhanced
set output
plot ...

I set both terminal to enhanced mode. What am I missing?

Body:
The output of your example with gnuplot's svg terminal contains the label as

<tspan font-family="Symbol" >W</tspan>

which leaves it to the viewer/browser to display it correctly. Your example works fine for me with Chrome/Edge, but not with Firefox.

The output of the wxt-svg-export doesn't contain text like show above, but the text is converted to paths in order to avoid such platform and viewer dependency (but has other drawbacks)


问:
function not returning as expected, returns before loop, but not after.
My function is not returning a string as expected, however, it does return before the for loop, and even returns a string if I place the return statement within the loop, but seems to ignore afterward.I'm at a complete loss as to why it doesn't return anything after the loop.  Here's my code: </p>

```<code>char * encode(char *plaintext, char *key){
   char *message, *keyStr, *crypt;
   char str[0], letter;
   int keysize, i, num, n, plainInput[sizeof(plaintext)],
   keyInt[sizeof(plaintext)], keyAndMessage[sizeof(plaintext)];
   unsigned size;

   size = (unsigned)strlen(plaintext);
   keysize = (unsigned)strlen(key);

  if(size != keysize){
     printf("the key size is: %d\n", keysize);
     printf("the plain text size is %d\n", size);
     return "Key and Plaintext Size Mismatch.";
  }

 message = malloc(size);
 keyStr = malloc(size);
 crypt = malloc(size);

for(i = 0; i < size; i++){

   // convert plaintext to ints
   letter = plaintext[i];                // could be any upper or lower case

   str[0] = letter;                     // place char into new memory location
   num = strtol( str, NULL, 36 ) - 10;  // convert the letter to a number
   plainInput[i] = num;                 // store each number in an array ->
   numInput

   // convert keys to ints
   letter = key[i];                     // could be any upper or lower case
   str[0] = letter;                     // place char into new memory location
   num = strtol( str, NULL, 36 ) - 10;  // convert the letter to a number
   keyInt[i] = num;                     // store each number in an array ->

   keyAndMessage[i] = (keyInt[i] + plainInput[i]) % 27;

   // convert key to ascii for debugging only
    keyStr[i] = (char)keyInt[i]+65;

   // convert message to ascii text
   message[i] = (char)plainInput[i]+65;

   // combine message and key
   plaintext[i] = (char)keyAndMessage[i]+65;

}

printf("the original message is: %s\n", message);
printf("the key is             : %s\n", key);
printf("the crypt is           : %s\n", plaintext);
printf("the size of origin is: %lu\n", sizeof(message));
printf("the size of key    is: %lu\n", sizeof(key));
printf("the size of crypt  is: %lu\n", sizeof(plaintext));

return plaintext;
</code>```

答:
@BLUEPIXY makes one good point... probably the best solution to that is to define size earlier, then use that for your array sizes (use size+1 to allow room for terminating null):

```<code>char * encode(char *plaintext, char *key){
    char *message, *keyStr, *crypt;
    size_t size = strlen(plaintext);
    int plainInput[size+1], keyInt[size+1], keyAndMessage[size+1];
        :
        :
</code>```

but you have another problem as well: you've defined str to be an array of length 0, when it should be length 2... one for the letter, one for the terminating null character.

```<code>char str[2];
</code>```

Though your conversion would be simpler (and more efficient) if you just used the character encoding directly:

```<code>num = toupper(letter) - 'A';  // convert the letter to a number
</code>```

Also, you've allowed no space in your mallocs for a terminating null, and you have not put in the terminating null, so you are printing unterminated strings... which produces undefined behavior.  Change your mallocs as follows:

```<code>message = malloc(size+1);
keyStr = malloc(size+1);
crypt = malloc(size+1);
</code>```

and be sure to terminate your strings before trying to print them:

```<code>message[size] = 0;
keyStr[size] = 0;
crypt[size] = 0;
</code>```

Oh, and as pointed out earlier, sizeof will only give you the size of the pointers (in the printfs at the end), not the size of the string.  You need strlen there again.

And one more thing... your function tries to modify the string passed in (plaintext), which is  a bad idea because it could be a constant string. Better to put the new characters into a malloced buffer, as with message, et.al.  Also, you neglected to free your malloced buffers...memory leak!

Hopefully this will get you closer!

Body:
My function is not returning a string as expected, however, it does return before the for loop, and even returns a string if I place the return statement within the loop, but seems to ignore afterward.I'm at a complete loss as to why it doesn't return anything after the loop.  Here's my code:

char * encode(char *plaintext, char *key){
   char *message, *keyStr, *crypt;
   char str[0], letter;
   int keysize, i, num, n, plainInput[sizeof(plaintext)],
   keyInt[sizeof(plaintext)], keyAndMessage[sizeof(plaintext)];
   unsigned size;

   size = (unsigned)strlen(plaintext);
   keysize = (unsigned)strlen(key);

  if(size != keysize){
     printf("the key size is: %d\n", keysize);
     printf("the plain text size is %d\n", size);
     return "Key and Plaintext Size Mismatch.";
  }

 message = malloc(size);
 keyStr = malloc(size);
 crypt = malloc(size);

for(i = 0; i < size; i++){

   // convert plaintext to ints
   letter = plaintext[i];                // could be any upper or lower case

   str[0] = letter;                     // place char into new memory location
   num = strtol( str, NULL, 36 ) - 10;  // convert the letter to a number
   plainInput[i] = num;                 // store each number in an array ->
   numInput

   // convert keys to ints
   letter = key[i];                     // could be any upper or lower case
   str[0] = letter;                     // place char into new memory location
   num = strtol( str, NULL, 36 ) - 10;  // convert the letter to a number
   keyInt[i] = num;                     // store each number in an array ->

   keyAndMessage[i] = (keyInt[i] + plainInput[i]) % 27;

   // convert key to ascii for debugging only
    keyStr[i] = (char)keyInt[i]+65;

   // convert message to ascii text
   message[i] = (char)plainInput[i]+65;

   // combine message and key
   plaintext[i] = (char)keyAndMessage[i]+65;

}

printf("the original message is: %s\n", message);
printf("the key is             : %s\n", key);
printf("the crypt is           : %s\n", plaintext);
printf("the size of origin is: %lu\n", sizeof(message));
printf("the size of key    is: %lu\n", sizeof(key));
printf("the size of crypt  is: %lu\n", sizeof(plaintext));

return plaintext;

Body:
@BLUEPIXY makes one good point... probably the best solution to that is to define size earlier, then use that for your array sizes (use size+1 to allow room for terminating null):

char * encode(char *plaintext, char *key){
    char *message, *keyStr, *crypt;
    size_t size = strlen(plaintext);
    int plainInput[size+1], keyInt[size+1], keyAndMessage[size+1];
        :
        :

but you have another problem as well: you've defined str to be an array of length 0, when it should be length 2... one for the letter, one for the terminating null character.

char str[2];

Though your conversion would be simpler (and more efficient) if you just used the character encoding directly:

num = toupper(letter) - 'A';  // convert the letter to a number

Also, you've allowed no space in your mallocs for a terminating null, and you have not put in the terminating null, so you are printing unterminated strings... which produces undefined behavior.  Change your mallocs as follows:

message = malloc(size+1);
keyStr = malloc(size+1);
crypt = malloc(size+1);

and be sure to terminate your strings before trying to print them:

message[size] = 0;
keyStr[size] = 0;
crypt[size] = 0;

Oh, and as pointed out earlier, sizeof will only give you the size of the pointers (in the printfs at the end), not the size of the string.  You need strlen there again.

And one more thing... your function tries to modify the string passed in (plaintext), which is  a bad idea because it could be a constant string. Better to put the new characters into a malloced buffer, as with message, et.al.  Also, you neglected to free your malloced buffers...memory leak!

Hopefully this will get you closer!


问:
How do I list all the attributes of an object in python pdb?
I try to list all the attributes of an object in Python pdb.

Let's say I want to list all the attributes and all methods of sys.stderr.

How can I do that?

答: print dir(object_name) will list all the attributes of object for you.


问:
Get HTML with current input values
I need to get the HTML of the whole page, with the current values of all inputs in their value="...".

I've tried this:

```<code>document.getElementById("htmlId").innerHTML;
</code>```

and this:

```<code>$('html').html();
</code>```

but the both return the HTML page but without the input values.

I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.

答:
for input value inside html use this code may got some help

```<code>$("#html input[type=text]").each(function(index,value) {
    val = $("#"+value.id).val();
    alert(val)
});
</code>```

Title: Get HTML with current input values

Body:
I need to get the HTML of the whole page, with the current values of all inputs in their value="...".

I've tried this:

document.getElementById("htmlId").innerHTML;

and this:

$('html').html();

but the both return the HTML page but without the input values.

I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.

Body:
for input value inside html use this code may got some help

$("#html input[type=text]").each(function(index,value) {
    val = $("#"+value.id).val();
    alert(val)
});


问:
How to find if any jar is using a deprecated class
I was migrating from Spring boot 1.3 to 1.5 and am getting a class not found error for ServletRegistrationBean.
Which is expected as this has been deprecated.
What am not able to understand is which jar is causing this?
I would like to understand how can debug it further?
Basically how to walk through jars to see which class is getting loaded at the time of failure and where it is from so I can correct my dependencies

I have used couple of tools to walk through the jars and find dependencies but that did not help me

```<code>    org.springframework.boot.SpringApplication Application startup failed
java.lang.NoClassDefFoundError: org/springframework/boot/context/embedded/ServletRegistrationBean
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.getDeclaredMethods(Class.java:1975)
        at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:613)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510)
        at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:570)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:697)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:640)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:609)
        at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1484)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:425)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:395)
        at org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$BeanPostProcessorsRegistrar.registerSyntheticBeanIfMissing(EmbeddedServletContainerAutoConfiguration.java:148)
        at org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$BeanPostProcessorsRegistrar.registerBeanDefinitions(EmbeddedServletContainerAutoConfiguration.java:137)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:354)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:143)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:320)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:228)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:270)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:93)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:686)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:524)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.ail.myaccount.MyApplication.main(MyApplication.java:20)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.context.embedded.ServletRegistrationBean
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 31 common frames omitted
[INFO] [] [] 2017-06-09_12:14:59.184 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@485e36bc: startup date [Fri Jun 09 12:14:53 IST 2017]; root of context hierarchy
[WARN] [] [] 2017-06-09_12:14:59.188 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@485e36bc: startup date [Fri Jun 09 12:14:53 IST 2017]; root of context hierarchy
        at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:417)
        at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1002)
        at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:961)
        at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:794)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:325)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.ail.myaccount.MyApplication.main(MyApplication.java:20)
[ERROR] [] [] 2017-06-09_12:14:59.189 org.springframework.beans.factory.support.DefaultListableBeanFactory Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@485e36bc: startup date [Fri Jun 09 12:14:53 IST 2017]; root of context hierarchy
        at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404)
        at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97)
        at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968)
        at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1033)
        at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1009)
        at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:961)
        at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:794)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:325)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.ail.myaccount.MyApplication.main(MyApplication.java:20)
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/context/embedded/ServletRegistrationBean
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.getDeclaredMethods(Class.java:1975)
        at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:613)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510)
        at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:570)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:697)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:640)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:609)
        at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1484)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:425)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:395)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:515)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:508)
        at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1189)
        at org.springframework.boot.SpringApplication.getExitCodeFromMappedException(SpringApplication.java:862)
        at org.springframework.boot.SpringApplication.getExitCodeFromException(SpringApplication.java:848)
        at org.springframework.boot.SpringApplication.handleExitCode(SpringApplication.java:834)
        at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:788)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:325)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.ail.myaccount.MyApplication.main(MyApplication.java:20)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.context.embedded.ServletRegistrationBean
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 24 more
:bootRun FAILED
</code>```

答:
Most probably you simply left both versions on the classpath, APIs are getting mixed up. Double check your classpath for duplicated libraries

Also please reffer to this github issue https://github.com/spring-projects/spring-boot/issues/8186

Body:
I was migrating from Spring boot 1.3 to 1.5 and am getting a class not found error for ServletRegistrationBean.
Which is expected as this has been deprecated.
What am not able to understand is which jar is causing this?
I would like to understand how can debug it further?
Basically how to walk through jars to see which class is getting loaded at the time of failure and where it is from so I can correct my dependencies

I have used couple of tools to walk through the jars and find dependencies but that did not help me

    org.springframework.boot.SpringApplication Application startup failed
java.lang.NoClassDefFoundError: org/springframework/boot/context/embedded/ServletRegistrationBean
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.getDeclaredMethods(Class.java:1975)
        at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:613)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510)
        at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:570)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:697)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:640)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:609)
        at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1484)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:425)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:395)
        at org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$BeanPostProcessorsRegistrar.registerSyntheticBeanIfMissing(EmbeddedServletContainerAutoConfiguration.java:148)
        at org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$BeanPostProcessorsRegistrar.registerBeanDefinitions(EmbeddedServletContainerAutoConfiguration.java:137)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:354)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:143)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:320)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:228)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:270)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:93)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:686)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:524)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.ail.myaccount.MyApplication.main(MyApplication.java:20)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.context.embedded.ServletRegistrationBean
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 31 common frames omitted
[INFO] [] [] 2017-06-09_12:14:59.184 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@485e36bc: startup date [Fri Jun 09 12:14:53 IST 2017]; root of context hierarchy
[WARN] [] [] 2017-06-09_12:14:59.188 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@485e36bc: startup date [Fri Jun 09 12:14:53 IST 2017]; root of context hierarchy
        at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:417)
        at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1002)
        at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:961)
        at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:794)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:325)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.ail.myaccount.MyApplication.main(MyApplication.java:20)
[ERROR] [] [] 2017-06-09_12:14:59.189 org.springframework.beans.factory.support.DefaultListableBeanFactory Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@485e36bc: startup date [Fri Jun 09 12:14:53 IST 2017]; root of context hierarchy
        at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404)
        at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97)
        at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968)
        at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1033)
        at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1009)
        at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:961)
        at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:794)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:325)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.ail.myaccount.MyApplication.main(MyApplication.java:20)
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/context/embedded/ServletRegistrationBean
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.getDeclaredMethods(Class.java:1975)
        at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:613)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510)
        at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:570)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:697)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:640)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:609)
        at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1484)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:425)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:395)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:515)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:508)
        at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1189)
        at org.springframework.boot.SpringApplication.getExitCodeFromMappedException(SpringApplication.java:862)
        at org.springframework.boot.SpringApplication.getExitCodeFromException(SpringApplication.java:848)
        at org.springframework.boot.SpringApplication.handleExitCode(SpringApplication.java:834)
        at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:788)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:325)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
        at com.ail.myaccount.MyApplication.main(MyApplication.java:20)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.context.embedded.ServletRegistrationBean
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 24 more
:bootRun FAILED


问:
How to decrypt django hashed sha256 password?
How to decrypt django hashed sha256 password?

I have a encrypted password:

pbkdf2_sha256$12000$laEnG5drNrAt$mFMVBvQh8YF+vriNXbe/Nb8eYEySWwPT5+oSaMPvUiA=

Its equivalent to "admin".

Now I need to decrypt the password. Means I wanted "admin" as output.

Is this possible?

答:
How to decrypt django hashed sha256 password?

SHA256 is not an encryption function, it cannot be decrypted

Is this possible?

NO

Here is a post you should read.

First, there is a difference between hashing and encryption. SHA256 is a hashing function, not an encryption function.

Secondly, since SHA256 is not an encryption function, it cannot be decrypted. What you mean is probably reversing it. In that case, SHA256 cannot be reversed because it's a one-way function. Reversing it would cause a preimage attack, which defeats its design goal.

Thirdly, SHA256 verification works by computing it again and comparing the result with the result at hand. If both results match, then the verification is successful. The theoretical background is that it's difficult to find another input which gives the same hash result. Violation of this creates a second-preimage attack, which defeats its design goal.

Finally, digital signatures are not simply hash and key combinations. But a hash function may improve its security.

ContentLicense: CC BY-SA 4.0


问:
How to refresh ToolTipText on ToolStripButton?
I want to implement simple toggle functionality on a ToolStripButton.

View Mode --> Edit Mode

Edit Mode --> View Mode

This piece of code is working fine except that ToolTip doesn't refresh. I tried AutoToolTip  property. I also tried setting ToolTipText to string.Empty. But my toolstrip continues to show old tooltip text. ToolTipText should also change when I toggle.

```<code>private void btnTrackingMode_Click(object sender, EventArgs e)
{
    if (_currentSheetTrackingMode == SheetTrackingMode.ViewMode)
    {
        _currentTrackingMode = TrackingMode.EditMode;

        btnTrackingMode.AutoToolTip = true;
        btnTrackingMode.ToolTipText = string.Empty;
        btnTrackingMode.ToolTipText = "You are currently in Edit Mode. Click here to enter into View Mode";
        btnTrackingMode.Image = ((System.Drawing.Image) ((Image) new ComponentResourceManager(typeof(MyForm)).GetObject("btnTrackingEditMode.Image")));
        btnTrackingMode.ImageTransparentColor = System.Drawing.Color.Magenta;
    }
    else
    {
        _currentTrackingMode = TrackingMode.ViewMode;

        btnTrackingMode.AutoToolTip = true;
        btnTrackingMode.ToolTipText = string.Empty;
        btnTrackingMode.ToolTipText = "You are currently in View Mode. Click here to enter into Edit Mode";
        btnTrackingMode.Image = ((System.Drawing.Image) ((Image) new ComponentResourceManager(typeof(MyForm)).GetObject("btnTrackingViewMode.Image")));
        btnTrackingMode.ImageTransparentColor = System.Drawing.Color.Magenta;
    }
}
</code>```

答:
You can try to refresh the button's parent ToolStrip

```<code>btnTrackingMode.ToolTipText = "something";
//put your toolstrip's name here
buttonsToolStrip.Refresh();
</code>```

You should be able to access the parent tool strip through btnTrackingMode.Owner if it's not directly available for some reason.

Body:
I want to implement simple toggle functionality on a ToolStripButton.

View Mode --> Edit Mode

Edit Mode --> View Mode

This piece of code is working fine except that ToolTip doesn't refresh. I tried AutoToolTip  property. I also tried setting ToolTipText to string.Empty. But my toolstrip continues to show old tooltip text. ToolTipText should also change when I toggle.

private void btnTrackingMode_Click(object sender, EventArgs e)
{
    if (_currentSheetTrackingMode == SheetTrackingMode.ViewMode)
    {
        _currentTrackingMode = TrackingMode.EditMode;

        btnTrackingMode.AutoToolTip = true;
        btnTrackingMode.ToolTipText = string.Empty;
        btnTrackingMode.ToolTipText = "You are currently in Edit Mode. Click here to enter into View Mode";
        btnTrackingMode.Image = ((System.Drawing.Image) ((Image) new ComponentResourceManager(typeof(MyForm)).GetObject("btnTrackingEditMode.Image")));
        btnTrackingMode.ImageTransparentColor = System.Drawing.Color.Magenta;
    }
    else
    {
        _currentTrackingMode = TrackingMode.ViewMode;

        btnTrackingMode.AutoToolTip = true;
        btnTrackingMode.ToolTipText = string.Empty;
        btnTrackingMode.ToolTipText = "You are currently in View Mode. Click here to enter into Edit Mode";
        btnTrackingMode.Image = ((System.Drawing.Image) ((Image) new ComponentResourceManager(typeof(MyForm)).GetObject("btnTrackingViewMode.Image")));
        btnTrackingMode.ImageTransparentColor = System.Drawing.Color.Magenta;
    }
}

Body:
You can try to refresh the button's parent ToolStrip

btnTrackingMode.ToolTipText = "something";
//put your toolstrip's name here
buttonsToolStrip.Refresh();

You should be able to access the parent tool strip through btnTrackingMode.Owner if it's not directly available for some reason.


问:
CodeIgniter auth security model
I've built a custom auth system for CodeIgniter (I know there are various 3rd party libraries available but this is for my own benefit) but I'm worried I'm missing something obvious that could bring the whole thing down.

I use CI sessions (through the database) and encrypt cookie values for a little bit of probably pointless obfuscation. Logins take place over SSL (and cookies are modified to be secure only). I also use phpass to hash passwords for storage, though thats not really relevant here. There may be a weak link in this part somewhere but my main concern is that page-to-page checks basically consist of a if is_logged_in = true type approach along with their username in the session. This bit concerns me as it seems a bit too 'easy'. Is this approach quite vulnerable? Should I be computing a page-by-page hash of, say, user-agent or whatever and making sure they match?

Any pointers would be most appreciated. Like I said, I'm aware of pre-existing solutions but I'm trying to learn me some learning here :)

答:
P.S:  I am no security expert so I prefer using system that are inspected by security-experts: openid, facebook connect, twitter(oauth), google signin, etc

But here is my Checklist(I can think off):

use SSL to make sure nobody can read your password when sent over the wire.

you should sanitize all your input($_POST, $_GET, $_SERVER, etc). If is not a local variable you should be careful. So for example you should sanitize $_SESSION['is_logged_in'] using this filter => $var = filter_var($_SESSION['is_logged_in'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); AGAIN You should do that for all input coming from the server, because they aren't safe. The best approach is to use whitelist instead of blacklist. Because there is a chance you will miss something.

Use PDO to minimize risk of sql-injection.

Don't store your passwords in your database in plain text, but hash them.  Still risky business I guess. Because recently gawker/lifehacker has been comprimised(wondering how it could happen?). I guess your phpass is pretty solid because owasp also recommends it.

Be aware off for XSS attacks. Is already done because of sanitizing input

Take measures against CSRF. This can also be very dangerous if for example you can modify e-mail adress when user is logged in. Next step is to sent an e-mail to reset your password and your system is comprimised.

ContentLicense: CC BY-SA 2.5

Title: CodeIgniter auth security model


问:
C#: Error while decoding OAEP padding weird issue
I'm currently working on a class that encrypts large amounts of text with a randomly generated encryption key encrypted by a X509 certificate from a smart card, using a RSACryptoServiceProvider to perform the master key encryption and decryption operations. However, when I have the fOEAP padding option set to true, I have the "Error while decoding OAEP padding" error on decryption every time. I've checked the key size and it is within acceptable limits. And I've gone through breakpoints to make sure that the Base64 string that gets returned from the encryption function is the exact same as the encrypted Base64 string that gets passed back to the decryption function when the file gets loaded again.

The key pair is definitely correct, since it works fine without OAEP. And I've checked the text encoding too.

EDIT: It turns out this could be a smart card specific issue, when I tried decryption with a local X509 certificate the decryption succeeded.

EDIT: This is the decryption code that fails:

```<code>string TestString = "Hello World!";
X509Certificate2 cert = DRXEncrypter.GetCertificate("Select a test certificate", "Select a certificate to use for this test from the local store.");
string key = DRXEncrypter.GenerateEncryptionKey(214);
Console.WriteLine("Encryption Key: " + key);

string encrypted = DRXEncrypter.EncryptBody(TestString, key);
Console.WriteLine("Encrypted Body: " + encrypted);

string cryptokey = DRXEncrypter.EncryptWithCert(cert, key);
Console.WriteLine("Encrypted Decryption Key: " + cryptokey);

string decrypted = DRXEncrypter.DecryptBody(encrypted, cryptokey, cert);
Console.WriteLine("Decrypted Body: " + decrypted);

Console.WriteLine("Output String: " + decrypted + ".");
</code>```

Here is the code from the crypto provider class I've written. I've been stuck on this issue for hours, so it would be great if someone could help me out.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace CoreDRXEditor
{
public class DRXEncrypter
{
    private byte[] Salt = Encoding.ASCII.GetBytes("81PO9j8I1a94j");
    private string EncryptionKey;
    private const bool UseOAEP = true;

    public DRXEncrypter(string EncryptionKey)
    {
        this.EncryptionKey = EncryptionKey;
    }

    public static string EncryptBody(string body, string encryptionkey)
    {
        // Use the plaintext master key to encrypt the body.
        DRXEncrypter enc = new DRXEncrypter(encryptionkey);

        // Encrypt the body.
        return enc.Encrypt(body);
    }

    public static int GetMaxKeySize(X509Certificate2 cert)
    {
        RSACryptoServiceProvider csp = cert.PublicKey.Key as RSACryptoServiceProvider;

        return csp.KeySize;
    }

    public static string DecryptBody(string body, string encryptionkey, X509Certificate2 cert)
    {
        // Decrypt the encrypted encryption key with the certificate.
        string DecryptedKey = Convert.ToBase64String(DecryptWithCert(cert, encryptionkey));

        // Create a new DRXEncrypter using the decrypted encryption key to decrypt the body.
        DRXEncrypter enc = new DRXEncrypter(DecryptedKey);

        // Return the decrypted body.
        return enc.Decrypt(body);
    }

    public static string GenerateEncryptionKey(int KeyLength)
    {
        using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
        {
            byte[] CryptoBytes = new byte[KeyLength];
            rng.GetBytes(CryptoBytes);

            return Convert.ToBase64String(CryptoBytes);
        }
    }

    public static X509Certificate2 GetCertificate(string title, string message)
    {
        X509Store cstore = new X509Store(StoreLocation.CurrentUser);
        cstore.Open(OpenFlags.ReadOnly);

        X509CertificateCollection certs = X509Certificate2UI.SelectFromCollection(cstore.Certificates, title, message, X509SelectionFlag.SingleSelection);

        if (certs.Count == 1)
        {
            X509Certificate2 mcert = certs[0] as X509Certificate2;
            return mcert;
        }
        else
        {
            return null;
        }
    }

    public static string EncryptWithCert(X509Certificate2 cert, string PlainText)
    {
        RSACryptoServiceProvider csp = cert.PublicKey.Key as RSACryptoServiceProvider;

        byte[] PlainBytes = Convert.FromBase64String(PlainText);

        // This converts the plain text into a byte array and then encrypts the raw bytes.
        byte[] CryptoBytes = csp.Encrypt(PlainBytes, UseOAEP);

        // This converts the encrypted bytes into a Base64 string.
        string ReturnString = Convert.ToBase64String(CryptoBytes);

        return ReturnString;
    }

    public static byte[] DecryptWithCert(X509Certificate2 cert, string EncryptedText)
    {
        RSACryptoServiceProvider csp = cert.PrivateKey as RSACryptoServiceProvider;

        //CspParameters csps = new CspParameters();

        byte[] EncryptedBytes = Convert.FromBase64String(EncryptedText);

        // This converts the encrypted, Base64 encoded byte array from EncryptWithCert() to a byte[] and decrypts it.
        byte[] CryptoBytes = csp.Decrypt(EncryptedBytes, UseOAEP);

        return CryptoBytes;
    }

    public string Encrypt(string PlainText)
    {
        RijndaelManaged Algorithm = null;
        string Output = null;

        try
        {
            Rfc2898DeriveBytes PrivateKey = new Rfc2898DeriveBytes(this.EncryptionKey, this.Salt);

            Algorithm = new RijndaelManaged();
            Algorithm.Key = PrivateKey.GetBytes(Algorithm.KeySize / 8);
            Algorithm.Padding = PaddingMode.PKCS7;

            ICryptoTransform Encryption = Algorithm.CreateEncryptor(Algorithm.Key, Algorithm.IV);

            using (MemoryStream msa = new MemoryStream())
            {
                msa.Write(BitConverter.GetBytes(Algorithm.IV.Length), 0, sizeof(int));
                msa.Write(Algorithm.IV, 0, Algorithm.IV.Length);
                using (CryptoStream csa = new CryptoStream(msa, Encryption, CryptoStreamMode.Write))
                {
                    using (StreamWriter swa = new StreamWriter(csa))
                    {
                        swa.Write(PlainText);
                    }
                }
                Output = Convert.ToBase64String(msa.ToArray());
            }
        }
        finally
        {
            if (Algorithm != null)
            {
                Algorithm.Clear();
            }
        }

        return Output;
    }

    public string Decrypt(string EncryptedText)
    {
        RijndaelManaged Algorithm = null;
        string Output = null;

        try
        {
            Rfc2898DeriveBytes PrivateKey = new Rfc2898DeriveBytes(this.EncryptionKey, this.Salt);

            byte[] KeyBytes = Convert.FromBase64String(EncryptedText);
            using (MemoryStream msb = new MemoryStream(KeyBytes))
            {
                Algorithm = new RijndaelManaged();
                Algorithm.Key = PrivateKey.GetBytes(Algorithm.KeySize / 8);
                Algorithm.IV = ReadByteArray(msb);
                Algorithm.Padding = PaddingMode.PKCS7;
                ICryptoTransform Decryption = Algorithm.CreateDecryptor(Algorithm.Key, Algorithm.IV);
                using (CryptoStream csb = new CryptoStream(msb, Decryption, CryptoStreamMode.Read))
                {
                    using (StreamReader srb = new StreamReader(csb))
                    {
                        Output = srb.ReadToEnd();
                    }
                }

            }
        }
        finally
        {
            if (Algorithm != null)
            {
                Algorithm.Clear();
            }
        }

        return Output;
    }

    public static string Sha512(string ToHash)
    {
        using (SHA512 SHA = new SHA512Managed())
        {
            byte[] HashByte = Encoding.UTF8.GetBytes(ToHash);
            byte[] HashBytes = SHA.ComputeHash(HashByte);
            string Hash = System.Text.Encoding.UTF8.GetString(HashBytes, 0, HashBytes.Length);
            return Hash;
        }
    }

    public static string Base64Encode(string data)
    {
        byte[] str = Encoding.UTF8.GetBytes(data);
        return Convert.ToBase64String(str);
    }

    public static string Base64Decode(string data)
    {
        byte[] str = Convert.FromBase64String(data);
        return Encoding.UTF8.GetString(str);
    }

    private byte[] ReadByteArray(Stream st)
    {
        byte[] Length = new byte[sizeof(int)];
        st.Read(Length, 0, Length.Length);
        byte[] Buffer = new byte[BitConverter.ToInt32(Length, 0)];
        st.Read(Buffer, 0, Buffer.Length);

        return Buffer;
    }
}
}
</code>```

答:
Make sure your key size is not too small or too large.

See comments from MSDN

The RSACryptoServiceProvider supports key sizes from 384 bits to 16384
  bits in increments of 8 bits if you have the Microsoft Enhanced
  Cryptographic Provider installed. It supports key sizes from 384 bits
  to 512 bits in increments of 8 bits if you have the Microsoft Base
  Cryptographic Provider installed.

So you might need to pad short key strings with some bytes to get the minimum  key length

Body:
I'm currently working on a class that encrypts large amounts of text with a randomly generated encryption key encrypted by a X509 certificate from a smart card, using a RSACryptoServiceProvider to perform the master key encryption and decryption operations. However, when I have the fOEAP padding option set to true, I have the "Error while decoding OAEP padding" error on decryption every time. I've checked the key size and it is within acceptable limits. And I've gone through breakpoints to make sure that the Base64 string that gets returned from the encryption function is the exact same as the encrypted Base64 string that gets passed back to the decryption function when the file gets loaded again.

The key pair is definitely correct, since it works fine without OAEP. And I've checked the text encoding too.

EDIT: It turns out this could be a smart card specific issue, when I tried decryption with a local X509 certificate the decryption succeeded.

EDIT: This is the decryption code that fails:

string TestString = "Hello World!";
X509Certificate2 cert = DRXEncrypter.GetCertificate("Select a test certificate", "Select a certificate to use for this test from the local store.");
string key = DRXEncrypter.GenerateEncryptionKey(214);
Console.WriteLine("Encryption Key: " + key);

string encrypted = DRXEncrypter.EncryptBody(TestString, key);
Console.WriteLine("Encrypted Body: " + encrypted);

string cryptokey = DRXEncrypter.EncryptWithCert(cert, key);
Console.WriteLine("Encrypted Decryption Key: " + cryptokey);

string decrypted = DRXEncrypter.DecryptBody(encrypted, cryptokey, cert);
Console.WriteLine("Decrypted Body: " + decrypted);

Console.WriteLine("Output String: " + decrypted + ".");

Here is the code from the crypto provider class I've written. I've been stuck on this issue for hours, so it would be great if someone could help me out.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace CoreDRXEditor
{
public class DRXEncrypter
{
    private byte[] Salt = Encoding.ASCII.GetBytes("81PO9j8I1a94j");
    private string EncryptionKey;
    private const bool UseOAEP = true;

    public DRXEncrypter(string EncryptionKey)
    {
        this.EncryptionKey = EncryptionKey;
    }

    public static string EncryptBody(string body, string encryptionkey)
    {
        // Use the plaintext master key to encrypt the body.
        DRXEncrypter enc = new DRXEncrypter(encryptionkey);

        // Encrypt the body.
        return enc.Encrypt(body);
    }

    public static int GetMaxKeySize(X509Certificate2 cert)
    {
        RSACryptoServiceProvider csp = cert.PublicKey.Key as RSACryptoServiceProvider;

        return csp.KeySize;
    }

    public static string DecryptBody(string body, string encryptionkey, X509Certificate2 cert)
    {
        // Decrypt the encrypted encryption key with the certificate.
        string DecryptedKey = Convert.ToBase64String(DecryptWithCert(cert, encryptionkey));

        // Create a new DRXEncrypter using the decrypted encryption key to decrypt the body.
        DRXEncrypter enc = new DRXEncrypter(DecryptedKey);

        // Return the decrypted body.
        return enc.Decrypt(body);
    }

    public static string GenerateEncryptionKey(int KeyLength)
    {
        using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
        {
            byte[] CryptoBytes = new byte[KeyLength];
            rng.GetBytes(CryptoBytes);

            return Convert.ToBase64String(CryptoBytes);
        }
    }

    public static X509Certificate2 GetCertificate(string title, string message)
    {
        X509Store cstore = new X509Store(StoreLocation.CurrentUser);
        cstore.Open(OpenFlags.ReadOnly);

        X509CertificateCollection certs = X509Certificate2UI.SelectFromCollection(cstore.Certificates, title, message, X509SelectionFlag.SingleSelection);

        if (certs.Count == 1)
        {
            X509Certificate2 mcert = certs[0] as X509Certificate2;
            return mcert;
        }
        else
        {
            return null;
        }
    }

    public static string EncryptWithCert(X509Certificate2 cert, string PlainText)
    {
        RSACryptoServiceProvider csp = cert.PublicKey.Key as RSACryptoServiceProvider;

        byte[] PlainBytes = Convert.FromBase64String(PlainText);

        // This converts the plain text into a byte array and then encrypts the raw bytes.
        byte[] CryptoBytes = csp.Encrypt(PlainBytes, UseOAEP);

        // This converts the encrypted bytes into a Base64 string.
        string ReturnString = Convert.ToBase64String(CryptoBytes);

        return ReturnString;
    }

    public static byte[] DecryptWithCert(X509Certificate2 cert, string EncryptedText)
    {
        RSACryptoServiceProvider csp = cert.PrivateKey as RSACryptoServiceProvider;

        //CspParameters csps = new CspParameters();

        byte[] EncryptedBytes = Convert.FromBase64String(EncryptedText);

        // This converts the encrypted, Base64 encoded byte array from EncryptWithCert() to a byte[] and decrypts it.
        byte[] CryptoBytes = csp.Decrypt(EncryptedBytes, UseOAEP);

        return CryptoBytes;
    }

    public string Encrypt(string PlainText)
    {
        RijndaelManaged Algorithm = null;
        string Output = null;

        try
        {
            Rfc2898DeriveBytes PrivateKey = new Rfc2898DeriveBytes(this.EncryptionKey, this.Salt);

            Algorithm = new RijndaelManaged();
            Algorithm.Key = PrivateKey.GetBytes(Algorithm.KeySize / 8);
            Algorithm.Padding = PaddingMode.PKCS7;

            ICryptoTransform Encryption = Algorithm.CreateEncryptor(Algorithm.Key, Algorithm.IV);

            using (MemoryStream msa = new MemoryStream())
            {
                msa.Write(BitConverter.GetBytes(Algorithm.IV.Length), 0, sizeof(int));
                msa.Write(Algorithm.IV, 0, Algorithm.IV.Length);
                using (CryptoStream csa = new CryptoStream(msa, Encryption, CryptoStreamMode.Write))
                {
                    using (StreamWriter swa = new StreamWriter(csa))
                    {
                        swa.Write(PlainText);
                    }
                }
                Output = Convert.ToBase64String(msa.ToArray());
            }
        }
        finally
        {
            if (Algorithm != null)
            {
                Algorithm.Clear();
            }
        }

        return Output;
    }

    public string Decrypt(string EncryptedText)
    {
        RijndaelManaged Algorithm = null;
        string Output = null;

        try
        {
            Rfc2898DeriveBytes PrivateKey = new Rfc2898DeriveBytes(this.EncryptionKey, this.Salt);

            byte[] KeyBytes = Convert.FromBase64String(EncryptedText);
            using (MemoryStream msb = new MemoryStream(KeyBytes))
            {
                Algorithm = new RijndaelManaged();
                Algorithm.Key = PrivateKey.GetBytes(Algorithm.KeySize / 8);
                Algorithm.IV = ReadByteArray(msb);
                Algorithm.Padding = PaddingMode.PKCS7;
                ICryptoTransform Decryption = Algorithm.CreateDecryptor(Algorithm.Key, Algorithm.IV);
                using (CryptoStream csb = new CryptoStream(msb, Decryption, CryptoStreamMode.Read))
                {
                    using (StreamReader srb = new StreamReader(csb))
                    {
                        Output = srb.ReadToEnd();
                    }
                }

            }
        }
        finally
        {
            if (Algorithm != null)
            {
                Algorithm.Clear();
            }
        }

        return Output;
    }

    public static string Sha512(string ToHash)
    {
        using (SHA512 SHA = new SHA512Managed())
        {
            byte[] HashByte = Encoding.UTF8.GetBytes(ToHash);
            byte[] HashBytes = SHA.ComputeHash(HashByte);
            string Hash = System.Text.Encoding.UTF8.GetString(HashBytes, 0, HashBytes.Length);
            return Hash;
        }
    }

    public static string Base64Encode(string data)
    {
        byte[] str = Encoding.UTF8.GetBytes(data);
        return Convert.ToBase64String(str);
    }

    public static string Base64Decode(string data)
    {
        byte[] str = Convert.FromBase64String(data);
        return Encoding.UTF8.GetString(str);
    }

    private byte[] ReadByteArray(Stream st)
    {
        byte[] Length = new byte[sizeof(int)];
        st.Read(Length, 0, Length.Length);
        byte[] Buffer = new byte[BitConverter.ToInt32(Length, 0)];
        st.Read(Buffer, 0, Buffer.Length);

        return Buffer;
    }
}
}


答:
Your problem can be solved as follows:

```<code>from itertools import cycle

def func(indict):
    dictlist = [dict(indict)] # make copy to not change original dict
    for key in indict: # loop keys to find lists
        if type(indict[key]) == list:
            listlength = len(indict[key])
            dictlist = listlength * dictlist # elements are not unique
            for dictindex, listelement in zip(range(len(dictlist)), cycle(indict[key])):
                dictlist[dictindex] = dict(dictlist[dictindex]) # uniquify
                dictlist[dictindex][key] = listelement # replace list by list element
    return dictlist
</code>```

In the general case you can have multiple lists in your dict. My solution assumes you want to unroll all of these.

Looking at the details of the solution, it starts by adding a copy of your original dict to dictlist then it cycles the elements and whenever it finds a list, it multiplies the dictlist with the the length of the list found. This will ensure that dictlist contains the correct number of elements.

However, the elements will not be unique as they will be references to the same underlying dicts.

To fix this, the elements of the dict list are "uniquified" by looping the list and replacing every element with a copy of itself and the list in the original indict is replaced by each element of the list, cycling the different elements of dictlist.

I know my explanation is a bit messy. I'm sorry about that, but I find it hard to explain in a short and simple way.

Also, the order of the element in the list, is not identical to what you ask for in the question. Since the individual key-value pairs of the dict are not ordered, it is not possible to ensure which order the elements will be unrolled, which leads to the list order is also not ensured.

Title: How does python achieve the following data format conversion?

Body:
I would like to achieve a function that deals with the following data：'d' and generate 'L'. How to achieve?

def func(**d):
   'do something'
    return [....]

source:

   d = {'a': 1, 'b': 2, 'c': [3, 4, 5]}

or

   d = {'a': 1, 'b': 2, 'c': [3, 4, 5], 'd': [6, 7]}

TO:

  L=[{'a':1,'b':2,'c':3},
   {'a':1,'b':2,'c':4},
   {'a':1,'b':2,'c':5}]

or

  L=[{'a': 1, 'b': 2, 'c': 3, 'd': 6},
    {'a': 1, 'b': 2, 'c': 3, 'd': 7},
    {'a': 1, 'b': 2, 'c': 4, 'd': 6},
    {'a': 1, 'b': 2, 'c': 4, 'd': 7},
    {'a': 1, 'b': 2, 'c': 5, 'd': 6},
    {'a': 1, 'b': 2, 'c': 5, 'd': 7}]

Body:
Your problem can be solved as follows:

from itertools import cycle

def func(indict):
    dictlist = [dict(indict)] # make copy to not change original dict
    for key in indict: # loop keys to find lists
        if type(indict[key]) == list:
            listlength = len(indict[key])
            dictlist = listlength * dictlist # elements are not unique
            for dictindex, listelement in zip(range(len(dictlist)), cycle(indict[key])):
                dictlist[dictindex] = dict(dictlist[dictindex]) # uniquify
                dictlist[dictindex][key] = listelement # replace list by list element
    return dictlist

In the general case you can have multiple lists in your dict. My solution assumes you want to unroll all of these.

Looking at the details of the solution, it starts by adding a copy of your original dict to dictlist then it cycles the elements and whenever it finds a list, it multiplies the dictlist with the the length of the list found. This will ensure that dictlist contains the correct number of elements.

However, the elements will not be unique as they will be references to the same underlying dicts.

To fix this, the elements of the dict list are "uniquified" by looping the list and replacing every element with a copy of itself and the list in the original indict is replaced by each element of the list, cycling the different elements of dictlist.

I know my explanation is a bit messy. I'm sorry about that, but I find it hard to explain in a short and simple way.

Also, the order of the element in the list, is not identical to what you ask for in the question. Since the individual key-value pairs of the dict are not ordered, it is not possible to ensure which order the elements will be unrolled, which leads to the list order is also not ensured.


问:
python 2 get the number between Chinese characters from the urllib2 response result
I want to get the digit 805 between the html tag using urllib2 from a web page.

```<code><span class="count">(共805张)</span>
</code>```

Here is the python code I wrote to get the number:

```<code>url = "https://movie.douban.com/celebrity/1044996/photos/"
request = urllib2.Request(url,headers=headers)
response = urllib2.urlopen(request)
content = response.read().decode('utf-8')
pattern1 = re.compile(r'<span\sclass="count">(.*?)</', re.S)
result1 = re.search(pattern1, content)
total_num = result1.group(1)
total_num = total_num
</code>```

But when I print the total_num, the console shows:

```<code>u'(\u5171805\u5f20)'
</code>```

How can I get the number 805 expect using regular expression?

答:
If your html tag is always like this form:

```<code><span class="count">(共805张)</span>
</code>```

Which means the number is between two non latin characters and '(' and ')' you can use this pattern:

```<code>import re
a = <span class="count">(共805张)</span>
# This will work if theString is unicode,
# or a string in an encoding where ASCII
# occupies values 0 to 0x7F (latin-1, UTF-8, etc.)
final = re.findall('\([^\x00-\x7F]+(\d+)[^\x00-\x7F]+\)', a)

print final
</code>```

Output:

```<code>['805']
</code>```

PS: Credit to this asnwer with some modifications.

Body:
I want to get the digit 805 between the html tag using urllib2 from a web page.

(共805张)

Here is the python code I wrote to get the number:

url = "https://movie.douban.com/celebrity/1044996/photos/"
request = urllib2.Request(url,headers=headers)
response = urllib2.urlopen(request)
content = response.read().decode('utf-8')
pattern1 = re.compile(r'(.*?)</', re.S)
result1 = re.search(pattern1, content)
total_num = result1.group(1)
total_num = total_num

But when I print the total_num, the console shows:

u'(\u5171805\u5f20)'

How can I get the number 805 expect using regular expression?

Body:
If your html tag is always like this form:

<span class="count">(共805张)</span>

Which means the number is between two non latin characters and '(' and ')' you can use this pattern:

import re
a = <span class="count">(共805张)</span>
# This will work if theString is unicode,
# or a string in an encoding where ASCII
# occupies values 0 to 0x7F (latin-1, UTF-8, etc.)
final = re.findall('\([^\x00-\x7F]+(\d+)[^\x00-\x7F]+\)', a)

print final

Output:

['805']

PS: Credit to this asnwer with some modifications.


问:
SQL to convert distinct item in row to column
I have a table as

```<code>Date          Item          Quantity
20170101      Mango         5
20170101      Orange        6
20170102      Mango         7
20170102      Orange        8
</code>```

I want below output

```<code>Date        Mango       Orange
20170101    5           6
20170102    7           8
</code>```

for this i used below sql query

```<code>SELECT
   Date,
   SUM(case when Item='Mango' then Quantity else 0 end) AS Mango,
   SUM(case when Item='Orange' then Quantity else 0 end) AS Orange
FROM orderTable
GROUP BY date
</code>```

but this is kind of hard coding for Mango and Orange. What if I need new item in orderTable. Can any one suggest me how can I make this query dynamic. So that if I add new item it automatically create new coulmn having item name as name and it will have 0 value under column against date when order not placed for that item.

like

```<code>Date          Item          Quantity
20170101      Mango         5
20170101      Orange        6
20170102      Mango         7
20170102      Orange        8
20170102      Cherry        9
</code>```

then output should be as ...

```<code>Date        Mango       Orange    Cherry
20170101    5           6         0
20170102    7           8         9
</code>```

答:
```<code>IF OBJECT_ID('Tempdb..#Temp') IS NOt NUll
Drop Table #Temp

;With cte([Date] ,Item ,Quantity)
AS
(
SELECT '20170101','Mango'  ,5 Union all
SELECT '20170101','Orange' ,6 Union all
SELECT '20170102','Mango'  ,7 Union all
SELECT '20170102','Orange' ,8 Union all
SELECT '20170102','Cherry' ,9
)
SELECT * INTO #Temp FROM cte

DECLARE @dynamicCol nvarchar(max),
        @Sql nvarchar(max),
        @dynamicCol2 nvarchar(max)

SELECT @dynamicCol=STUFF((SELECT DISTINCT ', ' + 'ISNULL('+Item +',''0'')  AS '+ Item  FROM  #Temp
FOR XML PATH('')),1,1,'')

SELECT @dynamicCol2=STUFF((SELECT DISTINCT ', ' + Item  FROM  #Temp
FOR XML PATH('')),1,1,'')

SET @Sql='
            SELECT [Date] , '+ @dynamicCol +' From
            (
            SELECT [Date] ,Item ,Quantity From
            #temp
            )AS Src
            PIVOT
            (
            MAX([Quantity]) For [Item ] IN ('+@dynamicCol2+')
            )
            AS Pvt
            '

PRINT @Sql

EXEC(@Sql)
</code>```

OutPut

```<code>Date        Cherry  Mango   Orange
----------------------------------
20170101     0       5       6
20170102     9       7       8
</code>```

Body:
I have a table as

Date          Item          Quantity
20170101      Mango         5
20170101      Orange        6
20170102      Mango         7
20170102      Orange        8

I want below output

Date        Mango       Orange
20170101    5           6
20170102    7           8

for this i used below sql query

SELECT
   Date,
   SUM(case when Item='Mango' then Quantity else 0 end) AS Mango,
   SUM(case when Item='Orange' then Quantity else 0 end) AS Orange
FROM orderTable
GROUP BY date

but this is kind of hard coding for Mango and Orange. What if I need new item in orderTable. Can any one suggest me how can I make this query dynamic. So that if I add new item it automatically create new coulmn having item name as name and it will have 0 value under column against date when order not placed for that item.

like

Date          Item          Quantity
20170101      Mango         5
20170101      Orange        6
20170102      Mango         7
20170102      Orange        8
20170102      Cherry        9

then output should be as ...

Date        Mango       Orange    Cherry
20170101    5           6         0
20170102    7           8         9

Body:
IF OBJECT_ID('Tempdb..#Temp') IS NOt NUll
Drop Table #Temp

;With cte([Date] ,Item ,Quantity)
AS
(
SELECT '20170101','Mango'  ,5 Union all
SELECT '20170101','Orange' ,6 Union all
SELECT '20170102','Mango'  ,7 Union all
SELECT '20170102','Orange' ,8 Union all
SELECT '20170102','Cherry' ,9
)
SELECT * INTO #Temp FROM cte

DECLARE @dynamicCol nvarchar(max),
        @Sql nvarchar(max),
        @dynamicCol2 nvarchar(max)

SELECT @dynamicCol=STUFF((SELECT DISTINCT ', ' + 'ISNULL('+Item +',''0'')  AS '+ Item  FROM  #Temp
FOR XML PATH('')),1,1,'')

SELECT @dynamicCol2=STUFF((SELECT DISTINCT ', ' + Item  FROM  #Temp
FOR XML PATH('')),1,1,'')

SET @Sql='
            SELECT [Date] , '+ @dynamicCol +' From
            (
            SELECT [Date] ,Item ,Quantity From
            #temp
            )AS Src
            PIVOT
            (
            MAX([Quantity]) For [Item ] IN ('+@dynamicCol2+')
            )
            AS Pvt
            '

PRINT @Sql

EXEC(@Sql)

OutPut

Date        Cherry  Mango   Orange
----------------------------------
20170101     0       5       6
20170102     9       7       8


问:
Is there a free tool which can help visualize the logic of a stored procedure in SQL Server 2008 R2?
I would like to be able to plot a call graph of a stored procedure. I am not interested in every detail, and I am not concerned with dynamic SQL (although it would be cool to detect it and skip it maybe or mark it as such.)

I would like the tool to generate a tree for me, given the server name, db name, stored proc name, a "call tree", which includes:

Parent stored procedure.

Every other stored procedure that is being called as a child of the caller.

Every table that is being modified (updated or deleted from) as a child of the stored proc which does it.

Hopefully it is clear what I am after; if not - please do ask. If there is not a tool that can do this, then I would like to try to write one myself. Python 2.6 is my language of choice, and I would like to use standard libraries as much as possible. Any suggestions?

EDIT: For the purposes of bounty Warning: SQL syntax is COMPLEX. I need something that can parse all kinds of SQL 2008, even if it looks stupid. No corner cases barred :)

EDIT2: I would be OK if all I am missing is graphics.

答:
**I just realized you might be looking for a Python library that can do this for you.  If so, I apologize for the dud answer lol, but if you're trying to visualize a DB so you can perform maintenance, then my answer is the same :) **

It's not free, but I assure you SQL Dependency Tracker from RedGate is well worth the money.  It produces a graph like you're describing, allowing you to see all the participants in every procedure, key, view, trigger, etc.  Awesome software:
http://www.red-gate.com/products/sql-development/sql-dependency-tracker/

I know you said free, but I was in the same boat as you several years ago and looked quite a bit for something that could do the job, free or not.  Until I found this software, nothing else could do what I needed.  I strongly encourage you to find the money for this tool if you need to do this sort of thing on a regular basis.


问:
TensorFlow: How can I summary two objects networks for TensorBoard?
I have a class which has method to create network.

```<code>class DQN:
    def __init__(self, session, input_size, output_size, name):
        .
        .
        .
        self._build_network()

    def _build_network(self, h_size=16, l_rate=0.01):
        with tf.variable_scope(self.net_name):
            self._X = tf.placeholder(tf.float32, [None, self.input_size], name="input_x")
            net = self._X
            net = tf.layers.dense(net, h_size, activation=lambda x: tf.maximum(0.3*x,x))
            net = tf.layers.dense(net, self.output_size)
            self._Qpred = net

        self._Y = tf.placeholder(shape=[None, self.output_size], dtype=tf.float32)

        # Loss function
        with tf.name_scope("loss") as scope:
            self._loss = tf.reduce_mean(tf.square(self._Y - self._Qpred))
            self._loss_summary = tf.summary.scalar("loss", self._loss)

        # Learning
        self._train = tf.train.AdamOptimizer(learning_rate=l_rate).minimize(self._loss)

    def update(self, x_stack, y_stack, merged_summary):
        return self.session.run(
            [self._loss, self._train, merged_summary],
            feed_dict={
                self._X: x_stack,
                self._Y: y_stack,
            }
        )
</code>```

And have to create two DQNinstances (separate networks).

```<code>def main():
    with tf.Session() as sess:
        mainDQN = dqn.DQN(sess, input_size, output_size, name="main")
        targetDQN = dqn.DQN(sess, input_size, output_size, name="target")

        merged_summary = tf.summary.merge_all()
        writer = tf.summary.FileWriter("./logs/dqn_log")
        writer.add_graph(sess.graph)
        .
        .
        .
        loss, _, summary = mainDQN.update(x_stack, y_stack, merged_summary)
        writer.add_summary(summary, global_step=episode)
</code>```

What I want to do is to keep track of mainDQN's loss function. But with above codes, it occurs an error when calling update() .
:

```<code>tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'target/input_x' with dtype float
     [[Node: target/input_x = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code>```

I think this error is related with targetDQN...

But have no idea how to deal with it.

Need your advices, thanks.

答:
You're right, the issue is related to targetDQN object. Basically what happens is that your merged_summary is an op which relies both on your main loss and on your target loss. Therefore when you ask its evaluation it will require the inputs for both DQN.

I would suggest to refactor your update function this way:

```<code>def update(self, x_stack, y_stack):
    return self.session.run(
        [self._loss, self._train, self._loss_summary],
        feed_dict={
            self._X: x_stack,
            self._Y: y_stack,
        }
    )
</code>```

so you only ask for the evaluation of the right summary.

EDIT: If you want more summaries associated to one of your DQN object, you could merge them using the tf.summary.merge method (see the API documentation) and ask for its evaluation.

Body:
I have a class which has method to create network.

class DQN:
    def __init__(self, session, input_size, output_size, name):
        .
        .
        .
        self._build_network()

    def _build_network(self, h_size=16, l_rate=0.01):
        with tf.variable_scope(self.net_name):
            self._X = tf.placeholder(tf.float32, [None, self.input_size], name="input_x")
            net = self._X
            net = tf.layers.dense(net, h_size, activation=lambda x: tf.maximum(0.3*x,x))
            net = tf.layers.dense(net, self.output_size)
            self._Qpred = net

        self._Y = tf.placeholder(shape=[None, self.output_size], dtype=tf.float32)

        # Loss function
        with tf.name_scope("loss") as scope:
            self._loss = tf.reduce_mean(tf.square(self._Y - self._Qpred))
            self._loss_summary = tf.summary.scalar("loss", self._loss)

        # Learning
        self._train = tf.train.AdamOptimizer(learning_rate=l_rate).minimize(self._loss)

    def update(self, x_stack, y_stack, merged_summary):
        return self.session.run(
            [self._loss, self._train, merged_summary],
            feed_dict={
                self._X: x_stack,
                self._Y: y_stack,
            }
        )

And have to create two DQNinstances (separate networks).

def main():
    with tf.Session() as sess:
        mainDQN = dqn.DQN(sess, input_size, output_size, name="main")
        targetDQN = dqn.DQN(sess, input_size, output_size, name="target")

        merged_summary = tf.summary.merge_all()
        writer = tf.summary.FileWriter("./logs/dqn_log")
        writer.add_graph(sess.graph)
        .
        .
        .
        loss, _, summary = mainDQN.update(x_stack, y_stack, merged_summary)
        writer.add_summary(summary, global_step=episode)

What I want to do is to keep track of mainDQN's loss function. But with above codes, it occurs an error when calling update() .
:

tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'target/input_x' with dtype float
     [[Node: target/input_x = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

I think this error is related with targetDQN...

But have no idea how to deal with it.

Need your advices, thanks.

Body:
You're right, the issue is related to targetDQN object. Basically what happens is that your merged_summary is an op which relies both on your main loss and on your target loss. Therefore when you ask its evaluation it will require the inputs for both DQN.

I would suggest to refactor your update function this way:

def update(self, x_stack, y_stack):
    return self.session.run(
        [self._loss, self._train, self._loss_summary],
        feed_dict={
            self._X: x_stack,
            self._Y: y_stack,
        }
    )

so you only ask for the evaluation of the right summary.

EDIT: If you want more summaries associated to one of your DQN object, you could merge them using the tf.summary.merge method (see the API documentation) and ask for its evaluation.