问:
PyDev - unresolved import only on IDE, still running
I'm trying to understand what PyDev doesn't like. I'm under Ubuntu and it seems that PyDev doesn't see the libraries like bash does.
I have a problem with two libraries, sqlite3 and peewee. If I run my program on a shell, all fine; if I open it in my newly installed PyDev I see a couple of instruction underlined with the message

Unresolved import: sqlite3

And

Undefined variable from import: get

The first error comes from the following code:

```<code>from pprint import pprint
import sqlite3
from bs4 import BeautifulSoup
import codecs
from database import Tbrecipe
from datetime import datetime
import logging

def main():
    logger = logging.getLogger('peewee')
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())
    CONN = sqlite3.connect('ent.db')
</code>```

The import error happens at the.. import. Second line.This happens because I've personally added /usr/lib/python2.7/sqlite3 to the pythonpath on the pydev's python interpreter. If I remove it, the error is at "sqlite3.connect". I suppose connect is not defined on that directory. I didn't find it.

Peewee has other issues. I created an object class for my database's table. All fine until I try to use some methods inherited from peewee.

My database.py looks like this:

from peewee import *
database = MySQLDatabase('test', **{'host': 'localhost',
 'password': 'rt', 'user': 'rt','charset':'utf8mb4'})

class UnknownField(object):
    def init(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = database

class Tbitem(BaseModel):
    source = IntegerField()
    name = CharField(null=True)

on my main.py

```<code>...
from database import Tbitem
item = Tbitem.get(Tbitem.id==id_item)
</code>```

both "get" and "Tbitem.id" are underlined in red with the error

Undefined variable from import: get

I can continue to work as nothing happens, or I can go back to vim or vscode (slow debugger), but I"d prefer using this since I'm used to eclipse and I like the idea of pydev. What should I do? I did check pythonpath on a shell and it looks the same, other than a directory that doesn't exist anymore.

I read on the FAQ of pydev that it doesn't like softlinks. Should I remove all softlinks? peewee is not softlinked and sqlite3 I don't even know where it finish.

Anyone with similar issues and a solution? I did read most of the questions here on SO, but they don't work for me.

答:
I solved it by forcing the build of all external libraries that caused that error (force builtins under interpreter's properties)
For my libraries I deleted all .pyc files and tried again and it worked.</p>

Body:
I'm trying to understand what PyDev doesn't like. I'm under Ubuntu and it seems that PyDev doesn't see the libraries like bash does.
I have a problem with two libraries, sqlite3 and peewee. If I run my program on a shell, all fine; if I open it in my newly installed PyDev I see a couple of instruction underlined with the message

Unresolved import: sqlite3

And

Undefined variable from import: get

The first error comes from the following code:

from pprint import pprint
import sqlite3
from bs4 import BeautifulSoup
import codecs
from database import Tbrecipe
from datetime import datetime
import logging

def main():
    logger = logging.getLogger('peewee')
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())
    CONN = sqlite3.connect('ent.db')

The import error happens at the.. import. Second line.This happens because I've personally added /usr/lib/python2.7/sqlite3 to the pythonpath on the pydev's python interpreter. If I remove it, the error is at "sqlite3.connect". I suppose connect is not defined on that directory. I didn't find it.

Peewee has other issues. I created an object class for my database's table. All fine until I try to use some methods inherited from peewee.

My database.py looks like this:

from peewee import *
database = MySQLDatabase('test', **{'host': 'localhost',
 'password': 'rt', 'user': 'rt','charset':'utf8mb4'})

class UnknownField(object):
    def init(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = database

class Tbitem(BaseModel):
    source = IntegerField()
    name = CharField(null=True)

on my main.py

...
from database import Tbitem
item = Tbitem.get(Tbitem.id==id_item)

both "get" and "Tbitem.id" are underlined in red with the error

Undefined variable from import: get

I can continue to work as nothing happens, or I can go back to vim or vscode (slow debugger), but I"d prefer using this since I'm used to eclipse and I like the idea of pydev. What should I do? I did check pythonpath on a shell and it looks the same, other than a directory that doesn't exist anymore.

I read on the FAQ of pydev that it doesn't like softlinks. Should I remove all softlinks? peewee is not softlinked and sqlite3 I don't even know where it finish.

Anyone with similar issues and a solution? I did read most of the questions here on SO, but they don't work for me.


来源: stackexchange

问:
xCode doesn't allow to name an image with special letters
I want to name images in Assets.xcassets like "a", "á", "â", "ã", "à", but when I try to name an image with "á" and hit 'enter', the name turns into "a-1", "â" - into "a-2" and so on. How can I set image name with this symbols?

SOLVED

Check right answer in comments

答:
As I was answered on apple forums

For XCode, if you name images a and à, it considers that it's the same name ; would be the same with a and A.

So I was forced to name my images as

a -> a1

á -> a2

â -> a3

and so on

Check it out here

ContentLicense: CC BY-SA 3.0


问:
drop event on textareas / WYSIHTML5 editor
Any idea how to listen to/hook drop event to the WYSIHTML5 editor?

The thing I want is... I have wysihtml5 and under it images uploaded by the user(as seen in the attachment), when I drag and drop one of the imags to the wysihtml5, it inserts it(which I suppose is just a default feature of the browser, just as when you drag any link to any textarea/text input), but with the same src as the source image was, and that's the thumbnail resolution, and I'd rather want something bigger. So I thought I'd hook up a drop event and get the image source from, say, data-big-src attribute of the thumbnail.

I tried

```<code>editor.on("drop", function() {
  console.log("fsdf");
});
</code>```

where editor was instance of wysihtml5, tried to add listener to the original textarea as well, none of it worked/fired, any tips?

// edit
paste / paste:composer

is probably what I'm looking for, but it doesn't return the dropped object....

答:
Try this

```<code>$($('.wysihtml5-sandbox').contents().find('body')).on("drop", function(event) {
              event.preventDefault();
              event.stopPropagation();
               var dt = event.originalEvent.dataTransfer;
                        var files = dt.files;

              var reader = new FileReader();
              reader.onload = function (e) {
                    debugger;
                  var data = this.result;
                  vm.composer.commands.exec('insertImage',e.target.result);
              }
              reader.readAsDataURL( files[0] );
          });
</code>```

https://jsfiddle.net/surajmahajan007/2yu456nw/

Body:
Any idea how to listen to/hook drop event to the WYSIHTML5 editor?

The thing I want is... I have wysihtml5 and under it images uploaded by the user(as seen in the attachment), when I drag and drop one of the imags to the wysihtml5, it inserts it(which I suppose is just a default feature of the browser, just as when you drag any link to any textarea/text input), but with the same src as the source image was, and that's the thumbnail resolution, and I'd rather want something bigger. So I thought I'd hook up a drop event and get the image source from, say, data-big-src attribute of the thumbnail.

I tried

editor.on("drop", function() {
  console.log("fsdf");
});

where editor was instance of wysihtml5, tried to add listener to the original textarea as well, none of it worked/fired, any tips?

// edit
paste / paste:composer

is probably what I'm looking for, but it doesn't return the dropped object....

Body:
Try this

$($('.wysihtml5-sandbox').contents().find('body')).on("drop", function(event) {
              event.preventDefault();
              event.stopPropagation();
               var dt = event.originalEvent.dataTransfer;
                        var files = dt.files;

              var reader = new FileReader();
              reader.onload = function (e) {
                    debugger;
                  var data = this.result;
                  vm.composer.commands.exec('insertImage',e.target.result);
              }
              reader.readAsDataURL( files[0] );
          });

https://jsfiddle.net/surajmahajan007/2yu456nw/


问:
Using a JSON script in HTML and show data
Here is the Link to JSON.
http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json

This JSON file give data about weather

And I want to show this data, given by the above link into my HTML file. I am using JSON for the first time. So I need help linking this JSON file into my HTML document.

```<code><html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
</head>

<body>

<div class="wrapper">
<span id="temp"></span>
<span id="high"></span>
<span id="low"></span>
<span id="windspeed"></span>
<span id="description"></span>
<span id="city"></span>
<span id="iconorimage"></span>
<span id="time"></span>
<span id="any thing else"></span>
</div>
</body>
</html>
</code>```

I am ok, If I can show only temperature, city, weather icon [rain,sunny], a text description about weather, high/low, wind speed and time.

答:
you can send ajax request to this url

```<code>    $.ajax({url: "http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json", success: function(result){
            var data=JSON.Parse(result);
//and then you can access each of the property of json object for example
            data.current_observation.observation_location.city;

//but yes you might need to loop through to access like periods in forecast
        }});
</code>```

let me know if i am directing you in the correct direction?
That is what you want? please let me know if you need further clarification.
Thanks

Body:
Here is the Link to JSON.
http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json

This JSON file give data about weather

And I want to show this data, given by the above link into my HTML file. I am using JSON for the first time. So I need help linking this JSON file into my HTML document.

I am ok, If I can show only temperature, city, weather icon [rain,sunny], a text description about weather, high/low, wind speed and time.

Body:
you can send ajax request to this url

    $.ajax({url: "http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json", success: function(result){
            var data=JSON.Parse(result);
//and then you can access each of the property of json object for example
            data.current_observation.observation_location.city;

//but yes you might need to loop through to access like periods in forecast
        }});

let me know if i am directing you in the correct direction?
That is what you want? please let me know if you need further clarification.
Thanks


问:
Numpy vectorize, using lists as arguments
The numpy vectorize function is useful, but it doesn't behave well when the function arguments are lists rather then scalars. As an example:

```<code>import numpy as np

def f(x, A):
    print "type(A)=%s, A=%s"%(type(A),A)
    return sum(A)/x

X = np.linspace(1,2,10)
P = [1,2,3]

f2 = np.vectorize(f)

f(X,P)
f2(X,P)
</code>```

Gives:

```<code>type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'numpy.int64'>, A=1

Traceback (most recent call last):
  File "vectorize.py", line 14, in <module>
    f2(X,P)
  File "/usr/local/lib/python2.6/dist-packages/numpy/lib/function_base.py", line 1824, in __call__
    theout = self.thefunc(*newargs)
  File "vectorize.py", line 5, in f
    return sum(A)/x
TypeError: 'numpy.int64' object is not iterable
</code>```

I understand that the function f works just fine without vectorizeing it, but I'd like to know how to (in general) vectorize a function whose arguments take in lists rather than a scalar.

答:
Your question doesn't make clear precisely what output you would like to see from the vectorized function, but I'm going to assume you would like the same list (A) applied as an argument to every invocation of f() (ie once for each element in the X array)

The vectorized version of a function ensures all arguments are arrays, and then applies numpy's broadcasting rules to determine how these arguments should be combined.

As with np.array's wrapping of np.ndarray, the coercion of the arguments to arrays tries to be helpful, by automatically converting a list to an array containing the same elements, rather than making an array with dtype=object that contains the list as its sole element. Most of the time this is what we want, but in your case, this "smart" behaviour is coming back to bite you.

While there may be a way to instruct numpy to only treat certain inputs as vectors, there are two straightforward ways to get the behaviour you're after:

Manually create an array with dtype=object to work within the broadcasting rules

Curry the value prior to vectorizing the function

1. dtype=object

Numpy arrays derive their efficiency from only storing one type of item, but they can still contain arbitrary python objects by specifying that the stored data type be python objects:

```<code>list_obj_array = np.ndarray((1,), dtype=object)
list_obj_array[0] = [1,2,3]
f2(X,list_obj_array)  # using your definition from above
</code>```

prints:

```<code>type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
</code>```

and returns:

```<code>array([ 6.        ,  5.4       ,  4.90909091,  4.5       ,  4.15384615,
        3.85714286,  3.6       ,  3.375     ,  3.17647059,  3.        ])
</code>```

2. Currying

Since you are passing the same list to the function call for each item in the array, you can store the list directly with the function by currying before applying vectorization:

```<code>def curry_f(A):
    def f_curried(x):
        return f(x, A)  # using your definition from above
    return f_curried

f2 = np.vectorize(curry_f(P))
f2(X)
</code>```

prints:

```<code>type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
</code>```

and returns:

```<code>array([ 6.        ,  5.4       ,  4.90909091,  4.5       ,  4.15384615,
        3.85714286,  3.6       ,  3.375     ,  3.17647059,  3.        ])
</code>```

P.S. you may also wish to have a look at np.frompyfunc -- it is similar to vectorize(), but works at a slightly lower level.

ContentLicense: CC BY-SA 2.5

Body:
The numpy vectorize function is useful, but it doesn't behave well when the function arguments are lists rather then scalars. As an example:

import numpy as np

def f(x, A):
    print "type(A)=%s, A=%s"%(type(A),A)
    return sum(A)/x

X = np.linspace(1,2,10)
P = [1,2,3]

f2 = np.vectorize(f)

f(X,P)
f2(X,P)

Gives:

type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'numpy.int64'>, A=1

Traceback (most recent call last):
  File "vectorize.py", line 14, in <module>
    f2(X,P)
  File "/usr/local/lib/python2.6/dist-packages/numpy/lib/function_base.py", line 1824, in __call__
    theout = self.thefunc(*newargs)
  File "vectorize.py", line 5, in f
    return sum(A)/x
TypeError: 'numpy.int64' object is not iterable

I understand that the function f works just fine without vectorizeing it, but I'd like to know how to (in general) vectorize a function whose arguments take in lists rather than a scalar.

Body:
Your question doesn't make clear precisely what output you would like to see from the vectorized function, but I'm going to assume you would like the same list (A) applied as an argument to every invocation of f() (ie once for each element in the X array)

The vectorized version of a function ensures all arguments are arrays, and then applies numpy's broadcasting rules to determine how these arguments should be combined.

As with np.array's wrapping of np.ndarray, the coercion of the arguments to arrays tries to be helpful, by automatically converting a list to an array containing the same elements, rather than making an array with dtype=object that contains the list as its sole element. Most of the time this is what we want, but in your case, this "smart" behaviour is coming back to bite you.

While there may be a way to instruct numpy to only treat certain inputs as vectors, there are two straightforward ways to get the behaviour you're after:

Manually create an array with dtype=object to work within the broadcasting rules

Curry the value prior to vectorizing the function

1. dtype=object

Numpy arrays derive their efficiency from only storing one type of item, but they can still contain arbitrary python objects by specifying that the stored data type be python objects:

list_obj_array = np.ndarray((1,), dtype=object)
list_obj_array[0] = [1,2,3]
f2(X,list_obj_array)  # using your definition from above

prints:

type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]

and returns:

array([ 6.        ,  5.4       ,  4.90909091,  4.5       ,  4.15384615,
        3.85714286,  3.6       ,  3.375     ,  3.17647059,  3.        ])

2. Currying

Since you are passing the same list to the function call for each item in the array, you can store the list directly with the function by currying before applying vectorization:

def curry_f(A):
    def f_curried(x):
        return f(x, A)  # using your definition from above
    return f_curried

f2 = np.vectorize(curry_f(P))
f2(X)

prints:

type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]
type(A)=<type 'list'>, A=[1, 2, 3]

and returns:

array([ 6.        ,  5.4       ,  4.90909091,  4.5       ,  4.15384615,
        3.85714286,  3.6       ,  3.375     ,  3.17647059,  3.        ])

P.S. you may also wish to have a look at np.frompyfunc -- it is similar to vectorize(), but works at a slightly lower level.


问:
Change every single element in Numpy object
I have a Numpy object with random N*M elements, and I also have two numbers A and B.

Now I want to access every element in this N*M array and make a change, i.e., if the element > 0, replace this element to A (i.e., element <- A), and if this element < 0, replace this element to B (i.e., element <- B).

I know there is a naive way to implement this method, that is accessing every single element using for loop, but it is very slow.

Can we use more fancy code to implement this ?

答:
Because you mentioned that you're interested in the speed of the computation, I made a speed comparision of several different approaches for your problem.

test.py:

```<code>import numpy as np

A = 100
B = 50

def createArray():
  array = np.random.randint(-100,100,(500,500))
  return array

def replace(x):
    return A if x > 0 else B

def replace_ForLoop():
    """Simple for-loop."""
    array = createArray()
    for i in range(array.shape[0]):
        for j in range(array.shape[1]):
            array[i][j] = replace(array[i][j])

def replace_nditer():
    """Use numpy.nditer to iterate over values."""
    array = createArray()
    for elem in np.nditer(array, op_flags=['readwrite']):
        elem[...] = replace(elem)

def replace_masks():
    """Use boolean masks."""
    array = createArray()
    array[array>0] = A
    array[array<0] = B

def replace_vectorize():
    """Use numpy.vectorize"""
    array = createArray()
    vectorfunc = np.vectorize(replace)
    array = vectorfunc(array)

def replace_where():
    """Use numpy.where"""
    array = createArray()
    array = np.where(array > 0, A, np.where(array < 0, B , array))
</code>```

Note: The variants using nested for-loops, np.nditer and boolean masks work inplace, the last two do not.

Timing comparision:

```<code>> python -mtimeit -s'import test' 'test.replace_ForLoop()'
10 loops, best of 3: 185 msec per loop
> python -mtimeit -s'import test' 'test.replace_nditer()'
10 loops, best of 3: 294 msec per loop
> python -mtimeit -s'import test' 'test.replace_masks()'
100 loops, best of 3: 5.8 msec per loop
> python -mtimeit -s'import test' 'test.replace_vectorize()'
10 loops, best of 3: 55.3 msec per loop
> python -mtimeit -s'import test' 'test.replace_where()'
100 loops, best of 3: 5.42 msec per loop
</code>```

Using loops is indeed quite slow. numpy.nditer is even slower, which comes as a surprise to me, because the doc calls it an efficient multi-dimensional iterator object to iterate over arrays. numpy.vectorize is essentially a for-loop, but still manages to be thrice as fast as the naive implementation.
The np.where variant proposed by Scott Boston is slightly faster than using boolean masks as per hpaulj's answer. However, it does need more memory because it does not modify inplace.

Body:
Because you mentioned that you're interested in the speed of the computation, I made a speed comparision of several different approaches for your problem.

test.py:

import numpy as np

A = 100
B = 50

def createArray():
  array = np.random.randint(-100,100,(500,500))
  return array

def replace(x):
    return A if x > 0 else B

def replace_ForLoop():
    """Simple for-loop."""
    array = createArray()
    for i in range(array.shape[0]):
        for j in range(array.shape[1]):
            array[i][j] = replace(array[i][j])

def replace_nditer():
    """Use numpy.nditer to iterate over values."""
    array = createArray()
    for elem in np.nditer(array, op_flags=['readwrite']):
        elem[...] = replace(elem)

def replace_masks():
    """Use boolean masks."""
    array = createArray()
    array[array>0] = A
    array[array<0] = B

def replace_vectorize():
    """Use numpy.vectorize"""
    array = createArray()
    vectorfunc = np.vectorize(replace)
    array = vectorfunc(array)

def replace_where():
    """Use numpy.where"""
    array = createArray()
    array = np.where(array > 0, A, np.where(array < 0, B , array))

Note: The variants using nested for-loops, np.nditer and boolean masks work inplace, the last two do not.

Timing comparision:

> python -mtimeit -s'import test' 'test.replace_ForLoop()'
10 loops, best of 3: 185 msec per loop
> python -mtimeit -s'import test' 'test.replace_nditer()'
10 loops, best of 3: 294 msec per loop
> python -mtimeit -s'import test' 'test.replace_masks()'
100 loops, best of 3: 5.8 msec per loop
> python -mtimeit -s'import test' 'test.replace_vectorize()'
10 loops, best of 3: 55.3 msec per loop
> python -mtimeit -s'import test' 'test.replace_where()'
100 loops, best of 3: 5.42 msec per loop

Using loops is indeed quite slow. numpy.nditer is even slower, which comes as a surprise to me, because the doc calls it an efficient multi-dimensional iterator object to iterate over arrays. numpy.vectorize is essentially a for-loop, but still manages to be thrice as fast as the naive implementation.
The np.where variant proposed by Scott Boston is slightly faster than using boolean masks as per hpaulj's answer. However, it does need more memory because it does not modify inplace.


问:
How to extend Bootstrap-wysihtml5 editor with image upload from URL?
I'm currently using Bootstrap-wysihtml5 text editor on my editable areas. Now I want to add image upload feature to my editor. But image's source should be URL only.

When I insert new image link to editor's image insert area;

It should download image to my server

It should check downloaded image for size, mime type etc

If everything ok, then I will upload it to my S3 bucket

I already coded number 2 and 3 but I can't handle number 1. How to trigger wysihtml5 editor for URL image upload when I click to insert?

Someone here did it: https://github.com/bassjobsen/wysihtml5-image-upload but it use traditional upload. Not from any url.

See demo: http://www.w3masters.nl/bootstrap-wysihtml5/

I want to implement upload feature but from URL only. What should I do before start scripting? Does it take days, weeks for beginner javascript coder?

For example stackoverflow's Image feature support Link from the web. Do you have any idea or source about it?

On above image you can insert new image but you can't store that image on your server. Image source should be my own domain after I insert image from URL

Here you can see insert image from URL feature without upload capability: http://jhollingworth.github.io/bootstrap-wysihtml5/


问:
How can I read input from the console using the Scanner class in Java?
How could I read input from the console using the Scanner class? Something like this:

```<code>System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
</code>```

Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.

答:
You can use the Scanner class in Java </p>

```<code>Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);
</code>```

Body:
How could I read input from the console using the Scanner class? Something like this:

System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code

Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.

Body:
You can use the Scanner class in Java

Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);


问:
How to rotate 4 (or more) images, fading between each one?
I have 4 images, which I want to fade between each other in a loop. I have something like the following:

```<code><img src="/images/image-1.jpg" id="featureImg1" />
<img src="/images/image-2.jpg" id="featureImg2" style="display:none;" />
<img src="/images/image-3.jpg" id="featureImg3" style="display:none;" />
<img src="/images/image-4.jpg" id="featureImg4" style="display:none;" />
</code>```

I am up for revisions to the HTML, although I cannot use absolute positioning in this case. I am using jQuery else where on the site, so it's available. I also need to deal with an image not being loaded right away as the images are larger.

答:
I have also found this extension to jQuery: http://www.linein.org/blog/2008/01/10/roate-image-using-jquery-with-plugin/

It seems to do it quite nicely, although a lot of code for not too much.

Edit: I also found the Nivo Slider which I've used quite often and has been working quite well. It also has the ability to have "navigation" and prev/next buttons. Quite handy.

OwnerDisplayName: Darryl Hein

Body:
I have 4 images, which I want to fade between each other in a loop. I have something like the following:

I am up for revisions to the HTML, although I cannot use absolute positioning in this case. I am using jQuery else where on the site, so it's available. I also need to deal with an image not being loaded right away as the images are larger.


问:
wx.App (wxPython) crash when calling
Recently I installed wxPython to do some works under Windows. Most of the time I work in Linux so I have a little experience here.

with python.exe interpreter, I just do 2 line of code
import wx
tmp=wx.App(False)

Then the interpreter crashed with Windows error reporting.

I tried both python 2.7.1 and 2.6.6  with wxPython 2.8.11, all come from their main website, still no luck.

Is there something I must do after install Python in Windows ? I can see that python install just fine and can do some basic job, wxPython library can be load, but can't call wx.App

答: I searched for a while and found that this is the problem with wxPython and Python >2.5. Tried many fix with manyfest file but no luck, so I think switch to PyQt is the only solution now.</p>

Title: wx.App (wxPython) crash when calling


问:
How to remove content between two tags on several files
i want to know how to delete all the content between two tags on several files.

Example:
I have 3 files that have the  and  tags, but they have different content on them, so i want to remove all the content between that two tags with some kind of tool, plugin, etc.

Is there any program, application or plugin that can do that?

Thank you.

答:
In Notepad++

Use RegExp search and

search for

```<code><head>[^<>]+</head>
</code>```

replace all with

```<code><head></head>
</code>```

As @domdom mentioned, you can search through all opened documents.

Body:
In Notepad++

Use RegExp search and

search for

<head>[^<>]+</head>

replace all with

<head></head>

As @domdom mentioned, you can search through all opened documents.


问:
Surface plot for multivariate 5 degree polynomial regression in Python
I am implementing a paper in Python, which was originally implemented in MATLAB. The paper says that a five degree polynomial was found using curve fitting from a set of sampling data points. I did not want to use their polynomial, so I started using the sample data points (given in paper) and tried to find a 5 degree polynomial using sklearn Polynomial Features and linear_model. As it is a multivariate equation f(x,y) where x and y are the length and width of a certain pond and f is the initial concentration of pollutant.

So my problem is that sklearn Polynomial Features transforms the test and train data points into n-polynomial points (I think as far as I understood it). However when I need the clf.predict function (where clf is the trained model) to take only the x and y values because when I am drawing the surface graph from Matplotlib, it requires meshgrid, so when I meshgrid my sklean-transformed test points, it's shape becomes like NxN whereas the predict function requires Nxn (where n is the number of degrees of polynomial in which it transformed  the data) and N is the number of rows.

Is there any possible way to draw the mesh points for this polynomial?

Paper Link: http://www.ajer.org/papers/v5(11)/A05110105.pdf
Paper title: Mathematical Model of Biological Oxygen Demand in Facultative Wastewater Stabilization Pond Based on Two-Dimensional
Advection-Dispersion Model

If possible, please look at the figure 5 and 6 in the paper (link above). This is what I am trying to achieve.

Thank you
enter code here

```<code>from math import exp
import numpy as np
from operator import itemgetter
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter

fig = plt.figure()
ax = fig.gca(projection='3d')

def model_BOD (cn):
    cnp1 = []
    n = len(cn)
    # variables:
    dmx = 1e-5
    dmy = 1e-5
    u = 2.10e-4
    v = 2.10e-4
    obs_time = 100
    dt = 0.1

    for t in np.arange(0.1,obs_time,dt):
        for i in range(N):
            for j in range(N):
                d = j + (i-1)*N
                dxp1 = d  + N
                dyp1 = d + 1
                dxm1 = d - N
                dym1 = d - 1

                cnp1.append(t*(((-2*dmx/dx**2)+(-2*dmy/dy**2)+(1/t))*cn[dxp1] + (dmx/dx**2)*cn[dyp1] \
                                + (dmy/dy**2)*cn[dym1] - (u/(2*dx))*cn[dxp1] + (u/(2*dx))*cn[dxm1] \
                                - (v/(2*dy))*cn[dyp1] + (v/(2*dy))*cn[dym1]))
        cn = cnp1
        cnp1 = []
    return cn

N = 20
Length = 70
Width = 77
dx = Length/N
dy = Width/N

deg_of_poly = 5

datapoints = np.array([
    [12.5,70,81.32],[25,70,88.54],[37.5,70,67.58],[50,70,55.32],[62.5,70,56.84],[77,70,49.52],
    [0,11.5,71.32],[77,57.5,67.20],
    [0,23,58.54],[25,46,51.32],[37.5,46,49.52],
    [0,34.5,63.22],[25,34.5,48.32],[37.5,34.5,82.30],[50,34.5,56.42],[77,34.5,48.32],[37.5,23,67.32],
    [0,46,64.20],[77,11.5,41.89],[77,46,55.54],[77,23,52.22],
    [0,57.5,93.72],
    [0,70,98.20],[77,0,42.32]
    ])

X = datapoints[:,0:2]
Y = datapoints[:,-1]

predict_x = []
predict_y = []
for i in np.linspace(0,Width,N):
    for j in np.linspace(0,Length,N):
        predict_x.append([i,j])

predict = np.array(predict_x)

poly = PolynomialFeatures(degree=deg_of_poly)
X_ = poly.fit_transform(X)

predict_ = poly.fit_transform(predict)
clf = linear_model.LinearRegression()
clf.fit(X_, Y)
prediction = []

for k,i in enumerate(predict_):
    prediction.append(clf.predict(np.array([i]))[0])

prediction_ = model_BOD(prediction)
print prediction_
XX = []
XX = predict[:,0]
YY = []
YY = predict[:,-1]
XX,YY = np.meshgrid(X,Y)
Z = prediction
##R = np.sqrt(XX**2+YY**2)
##Z = np.tan(R)

surf = ax.plot_surface(XX,YY,Z)
plt.show()
</code>```

答:
If I understand correctly, the key logic here is to generate polynomial features from your meshgrid, make the prediction and plot the prediction with the original meshgrid. Hope the following gives what you want:

```<code>import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model

# The training set
datapoints = np.array([
    [12.5,70,81.32], [25,70,88.54], [37.5,70,67.58], [50,70,55.32],
    [62.5,70,56.84], [77,70,49.52], [0,11.5,71.32], [77,57.5,67.20],
    [0,23,58.54], [25,46,51.32], [37.5,46,49.52], [0,34.5,63.22],
    [25,34.5,48.32], [37.5,34.5,82.30], [50,34.5,56.42], [77,34.5,48.32],
    [37.5,23,67.32], [0,46,64.20], [77,11.5,41.89], [77,46,55.54],
    [77,23,52.22], [0,57.5,93.72], [0,70,98.20], [77,0,42.32]
    ])
X = datapoints[:,0:2]
Y = datapoints[:,-1]
# 5 degree polynomial features
deg_of_poly = 5
poly = PolynomialFeatures(degree=deg_of_poly)
X_ = poly.fit_transform(X)
# Fit linear model
clf = linear_model.LinearRegression()
clf.fit(X_, Y)

# The test set, or plotting set
N = 20
Length = 70
predict_x0, predict_x1 = np.meshgrid(np.linspace(0, Length, N),
                                     np.linspace(0, Length, N))
predict_x = np.concatenate((predict_x0.reshape(-1, 1),
                            predict_x1.reshape(-1, 1)),
                           axis=1)
predict_x_ = poly.fit_transform(predict_x)
predict_y = clf.predict(predict_x_)

# Plot
fig = plt.figure(figsize=(16, 6))
ax1 = fig.add_subplot(121, projection='3d')
surf = ax1.plot_surface(predict_x0, predict_x1, predict_y.reshape(predict_x0.shape),
                        rstride=1, cstride=1, cmap=cm.jet, alpha=0.5)
ax1.scatter(datapoints[:, 0], datapoints[:, 1], datapoints[:, 2], c='b', marker='o')

ax1.set_xlim((70, 0))
ax1.set_ylim((0, 70))
fig.colorbar(surf, ax=ax1)
ax2 = fig.add_subplot(122)
cs = ax2.contourf(predict_x0, predict_x1, predict_y.reshape(predict_x0.shape))
ax2.contour(cs, colors='k')
fig.colorbar(cs, ax=ax2)
plt.show()
</code>```

Body:
I am implementing a paper in Python, which was originally implemented in MATLAB. The paper says that a five degree polynomial was found using curve fitting from a set of sampling data points. I did not want to use their polynomial, so I started using the sample data points (given in paper) and tried to find a 5 degree polynomial using sklearn Polynomial Features and linear_model. As it is a multivariate equation f(x,y) where x and y are the length and width of a certain pond and f is the initial concentration of pollutant.

So my problem is that sklearn Polynomial Features transforms the test and train data points into n-polynomial points (I think as far as I understood it). However when I need the clf.predict function (where clf is the trained model) to take only the x and y values because when I am drawing the surface graph from Matplotlib, it requires meshgrid, so when I meshgrid my sklean-transformed test points, it's shape becomes like NxN whereas the predict function requires Nxn (where n is the number of degrees of polynomial in which it transformed  the data) and N is the number of rows.

Is there any possible way to draw the mesh points for this polynomial?

Paper Link: http://www.ajer.org/papers/v5(11)/A05110105.pdf
Paper title: Mathematical Model of Biological Oxygen Demand in Facultative Wastewater Stabilization Pond Based on Two-Dimensional
Advection-Dispersion Model

If possible, please look at the figure 5 and 6 in the paper (link above). This is what I am trying to achieve.

Thank you
enter code here

from math import exp
import numpy as np
from operator import itemgetter
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter

fig = plt.figure()
ax = fig.gca(projection='3d')

def model_BOD (cn):
    cnp1 = []
    n = len(cn)
    # variables:
    dmx = 1e-5
    dmy = 1e-5
    u = 2.10e-4
    v = 2.10e-4
    obs_time = 100
    dt = 0.1

    for t in np.arange(0.1,obs_time,dt):
        for i in range(N):
            for j in range(N):
                d = j + (i-1)*N
                dxp1 = d  + N
                dyp1 = d + 1
                dxm1 = d - N
                dym1 = d - 1

                cnp1.append(t*(((-2*dmx/dx**2)+(-2*dmy/dy**2)+(1/t))*cn[dxp1] + (dmx/dx**2)*cn[dyp1] \
                                + (dmy/dy**2)*cn[dym1] - (u/(2*dx))*cn[dxp1] + (u/(2*dx))*cn[dxm1] \
                                - (v/(2*dy))*cn[dyp1] + (v/(2*dy))*cn[dym1]))
        cn = cnp1
        cnp1 = []
    return cn

N = 20
Length = 70
Width = 77
dx = Length/N
dy = Width/N

deg_of_poly = 5

datapoints = np.array([
    [12.5,70,81.32],[25,70,88.54],[37.5,70,67.58],[50,70,55.32],[62.5,70,56.84],[77,70,49.52],
    [0,11.5,71.32],[77,57.5,67.20],
    [0,23,58.54],[25,46,51.32],[37.5,46,49.52],
    [0,34.5,63.22],[25,34.5,48.32],[37.5,34.5,82.30],[50,34.5,56.42],[77,34.5,48.32],[37.5,23,67.32],
    [0,46,64.20],[77,11.5,41.89],[77,46,55.54],[77,23,52.22],
    [0,57.5,93.72],
    [0,70,98.20],[77,0,42.32]
    ])

X = datapoints[:,0:2]
Y = datapoints[:,-1]

predict_x = []
predict_y = []
for i in np.linspace(0,Width,N):
    for j in np.linspace(0,Length,N):
        predict_x.append([i,j])

predict = np.array(predict_x)

poly = PolynomialFeatures(degree=deg_of_poly)
X_ = poly.fit_transform(X)

predict_ = poly.fit_transform(predict)
clf = linear_model.LinearRegression()
clf.fit(X_, Y)
prediction = []

for k,i in enumerate(predict_):
    prediction.append(clf.predict(np.array([i]))[0])

prediction_ = model_BOD(prediction)
print prediction_
XX = []
XX = predict[:,0]
YY = []
YY = predict[:,-1]
XX,YY = np.meshgrid(X,Y)
Z = prediction
##R = np.sqrt(XX**2+YY**2)
##Z = np.tan(R)

surf = ax.plot_surface(XX,YY,Z)
plt.show()

Body:
If I understand correctly, the key logic here is to generate polynomial features from your meshgrid, make the prediction and plot the prediction with the original meshgrid. Hope the following gives what you want:

import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model

# The training set
datapoints = np.array([
    [12.5,70,81.32], [25,70,88.54], [37.5,70,67.58], [50,70,55.32],
    [62.5,70,56.84], [77,70,49.52], [0,11.5,71.32], [77,57.5,67.20],
    [0,23,58.54], [25,46,51.32], [37.5,46,49.52], [0,34.5,63.22],
    [25,34.5,48.32], [37.5,34.5,82.30], [50,34.5,56.42], [77,34.5,48.32],
    [37.5,23,67.32], [0,46,64.20], [77,11.5,41.89], [77,46,55.54],
    [77,23,52.22], [0,57.5,93.72], [0,70,98.20], [77,0,42.32]
    ])
X = datapoints[:,0:2]
Y = datapoints[:,-1]
# 5 degree polynomial features
deg_of_poly = 5
poly = PolynomialFeatures(degree=deg_of_poly)
X_ = poly.fit_transform(X)
# Fit linear model
clf = linear_model.LinearRegression()
clf.fit(X_, Y)

# The test set, or plotting set
N = 20
Length = 70
predict_x0, predict_x1 = np.meshgrid(np.linspace(0, Length, N),
                                     np.linspace(0, Length, N))
predict_x = np.concatenate((predict_x0.reshape(-1, 1),
                            predict_x1.reshape(-1, 1)),
                           axis=1)
predict_x_ = poly.fit_transform(predict_x)
predict_y = clf.predict(predict_x_)

# Plot
fig = plt.figure(figsize=(16, 6))
ax1 = fig.add_subplot(121, projection='3d')
surf = ax1.plot_surface(predict_x0, predict_x1, predict_y.reshape(predict_x0.shape),
                        rstride=1, cstride=1, cmap=cm.jet, alpha=0.5)
ax1.scatter(datapoints[:, 0], datapoints[:, 1], datapoints[:, 2], c='b', marker='o')

ax1.set_xlim((70, 0))
ax1.set_ylim((0, 70))
fig.colorbar(surf, ax=ax1)
ax2 = fig.add_subplot(122)
cs = ax2.contourf(predict_x0, predict_x1, predict_y.reshape(predict_x0.shape))
ax2.contour(cs, colors='k')
fig.colorbar(cs, ax=ax2)
plt.show()


问:
What is the correct way in reactjs?
I am new to react. In my project, I have a Home Component.

```<code>class Home extends Component {

        logOut(){
            console.log('log out in side home js');
            this.props.LogOutAction();
            localStorage.setItem('loginFlag', null);
        }

        render(){

                return(
                        <div>
                            <Header />
                            <br/>
                            <div className="col-md-12 ">
                                <div className="col-md-3 home-border">
                                        a
                                </div>
                                <div className="col-md-6 home-border">
                                    <User/>

                                </div>
                                <div className="col-md-3 home-border">
                                        c
                                </div>
                            </div>
                        </div>
                )
        }
}
</code>```

And my User component is

```<code>class User extends React.Component {

        viewProfile(id){

        }

        render() {
                var userdetails     =   [   {"id":"1", "name":"Abraham", "country": "USA", "age":"29", "image":""},
                                            {"id":"2", "name":"Gregory", "country": "Canada", "age":"23", "image":""},
                                            {"id":"3", "name":"Mathews", "country": "Newzeland", "age":"24", "image":""},
                                            {"id":"4", "name":"Williamson", "country": "China", "age":"27", "image":""},
                                            {"id":"5", "name":"Edwerd", "country": "Germany", "age":"22", "image":""}
                                ];
                 var myStyle = {
                                      border:"1px solid black",
                                      height:"170px",
                                }

                return(
                        <div>
                            <div>
                                {userdetails.map((data, i) => <div className="col-md-12 div-bottom" style={myStyle} key={i}>

                                        <div  className="col-md-12">
                                            <div className="col-md-12">
                                                <img className="img-thumbnail img-margin" width="150" height="236" src = {'profile.jpg'} />
                                            </div>
                                            <div className="col-md-12 div-bottom"><label>{data.name}</label></div>
                                            <div className="col-md-12 div-bottom">
                                                <div className="col-md-6"><label>age:</label>  {data.age}</div>
                                                <div className="col-md-3"><label>Country:</label> {data.country}</div>
                                            </div>
                                            <div className="col-md-4 .div-bottom"><button className="btn btn-primary" onClick={  () => { this.viewProfile(data.id) } }>view Profile</button></div>
                                        </div>
                                    </div>)
                                }
                            </div>
                        </div>
                )
        }

}
</code>```

I want to show the more user details in place of 'c' in the Home Component on the button click in the User Component.What is the correct method and how it can done?. Thanks in advance..

答:
you can send an event as props and call it from other component.

Say you have a class

```<code>Class Home {

    handleChange(evt) {
        this.setState({ username: evt.target.value });
    }

    render {
        return (
            <div>
                <Users name={this.state.username} onChange={this.handleChange}/>
                <div> {this.state.username} </div>
            </div>
        );
    }
}
</code>```

Child Component

```<code>Class Users {

    handleChange() {
        //logic
    }

    render {
        return (
            <div>
                <input type="text" onChange={this.props.onChange}/>
                {this.props.name}
            </div>
        );
    }
}
</code>```

Here in Component Users when you change the input it will call the
method of class Home and update state of Home .

Now getting the updated state as props in component Users will give
you the changed text that you just entered

Title: What is the correct way in reactjs?

Body:
I am new to react. In my project, I have a Home Component.

class Home extends Component {

        logOut(){
            console.log('log out in side home js');
            this.props.LogOutAction();
            localStorage.setItem('loginFlag', null);
        }

        render(){

                return(

                                        a

                                    <User/>

                                        c

                )
        }
}

And my User component is

class User extends React.Component {

        viewProfile(id){

        }

        render() {
                var userdetails     =   [   {"id":"1", "name":"Abraham", "country": "USA", "age":"29", "image":""},
                                            {"id":"2", "name":"Gregory", "country": "Canada", "age":"23", "image":""},
                                            {"id":"3", "name":"Mathews", "country": "Newzeland", "age":"24", "image":""},
                                            {"id":"4", "name":"Williamson", "country": "China", "age":"27", "image":""},
                                            {"id":"5", "name":"Edwerd", "country": "Germany", "age":"22", "image":""}
                                ];
                 var myStyle = {
                                      border:"1px solid black",
                                      height:"170px",
                                }

                return(

                                {userdetails.map((data, i) =>

{data.name}

age:  {data.age}

Country: {data.country}

<button className="btn btn-primary" onClick={  () => { this.viewProfile(data.id) } }>view Profile</button>

)
                                }

                )
        }

}

I want to show the more user details in place of 'c' in the Home Component on the button click in the User Component.What is the correct method and how it can done?. Thanks in advance..

Body:
you can send an event as props and call it from other component.

Say you have a class

Class Home {

    handleChange(evt) {
        this.setState({ username: evt.target.value });
    }

    render {
        return (
            <div>
                <Users name={this.state.username} onChange={this.handleChange}/>
                <div> {this.state.username} </div>
            </div>
        );
    }
}

Child Component

Class Users {

    handleChange() {
        //logic
    }

    render {
        return (
            <div>
                <input type="text" onChange={this.props.onChange}/>
                {this.props.name}
            </div>
        );
    }
}

Here in Component Users when you change the input it will call the
method of class Home and update state of Home .

Now getting the updated state as props in component Users will give
you the changed text that you just entered


问:
Is GetHashCode of Protobuf the same everywhere?
I noticed I have GetHashCode() in my generated C# class from .proto file. To make tampering with data more difficult I want to calculate the hash code send it together with the data. Then I can compute the hash again at the destination.

My approach is to have a hash field in the proto definition, but prior to computing the hash I will left it 0, compute it, put it in and serialize. At the destination the hash will be remembered, make it 0, and then compute the new hash to check the integrity.

On the receiving end is JavaScript :

Will the hash generation function at the destination produces the same result?

If .proto file got updated with new fields, new class generated everywhere, will the old message hash to the same result?

I know about MD5, but I think it needs to be generated after the binary file is complete, and I cannot include the MD5 together with the data if I do that.

I will still have an encryption on top of this, but just in case someone manages to decrypt the data he could not easily change some part of it to fool the receiver.

答:
No, you can't use GetHashCode() like that. It isn't a protobuf concept, but rather exists for all .NET managed types. Firstly, it is not the case that every object overrides this method, and if it doesn't, then for a class it represents the reference/instance, not the contents (just like Equals does by default). If it is overridden, then it is expected to produce the same value each time in the same app-domain, but there is no requirement for it to produce the same value in different runs. Whether it does depends on the implementation and the exact framework you are using (assuming things like string.GetHashCode are used).

But the other problem is that the code in the target framework would have no matching method, and even if it did: would not have access to the same implementations of things like string.GetHashCode.

So no: don't use this for that purpose. It doesn't do that.

As a specific example: things like string.GetHashCode produce different values for the same string depending on the OS and .NET version. It wouldn't even do what you want purely on .NET endpoints.

As a trivial example, consider:

```<code>static void Main()
{
    Console.WriteLine("abc".GetHashCode());
    Console.WriteLine("abc".GetHashCode());
    Console.WriteLine("abc".GetHashCode());
}
</code>```

If I run this once, I get:

```<code>518228267
518228267
518228267
</code>```

So you might think "ah, yes, GetHashCode() gives the same value each time". However, it is more subtle than that. On recent versions of .NET, this is seeded at app-startup, so if I run it again I get:

```<code>-177712234
-177712234
-177712234
</code>```

then

```<code>-59760352
-59760352
-59760352
</code>```

etc. This was done in part to avoid people depending on GetHashCode() being the same between runs, and in part to prevent people being able to use sets of strings known to have the same hash-code as an attack vector to put stress on dictionaries (forcing them to use fallback behaviour) - for example as DDOS attacks against web-servers. If the hash can't be predicted by static external code, this attack vector goes away.

Body:
No, you can't use GetHashCode() like that. It isn't a protobuf concept, but rather exists for all .NET managed types. Firstly, it is not the case that every object overrides this method, and if it doesn't, then for a class it represents the reference/instance, not the contents (just like Equals does by default). If it is overridden, then it is expected to produce the same value each time in the same app-domain, but there is no requirement for it to produce the same value in different runs. Whether it does depends on the implementation and the exact framework you are using (assuming things like string.GetHashCode are used).

But the other problem is that the code in the target framework would have no matching method, and even if it did: would not have access to the same implementations of things like string.GetHashCode.

So no: don't use this for that purpose. It doesn't do that.

As a specific example: things like string.GetHashCode produce different values for the same string depending on the OS and .NET version. It wouldn't even do what you want purely on .NET endpoints.

As a trivial example, consider:

static void Main()
{
    Console.WriteLine("abc".GetHashCode());
    Console.WriteLine("abc".GetHashCode());
    Console.WriteLine("abc".GetHashCode());
}

If I run this once, I get:

518228267
518228267
518228267

So you might think "ah, yes, GetHashCode() gives the same value each time". However, it is more subtle than that. On recent versions of .NET, this is seeded at app-startup, so if I run it again I get:

-177712234
-177712234
-177712234

then

-59760352
-59760352
-59760352

etc. This was done in part to avoid people depending on GetHashCode() being the same between runs, and in part to prevent people being able to use sets of strings known to have the same hash-code as an attack vector to put stress on dictionaries (forcing them to use fallback behaviour) - for example as DDOS attacks against web-servers. If the hash can't be predicted by static external code, this attack vector goes away.


答:
You can access json object similar to the way one access the object property in javascript.

$.ajax({
  dataType: "json",
  url:"//api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json",
  success: function(data){
    $('#city').text("City : " + data["current_observation"]["display_location"]["city"]);
    $('#high').text("High : " + "");//Insert data for high here
    $('#low').text("Low : " +""); //Insert data for low here
    $('#temp').text("Tempearature : " + data["current_observation"]["temperature_string"]);
    $('#description').text("Description : " + data["current_observation"]["icon"]);
    $('').attr('src',data["current_observation"]["icon_url"]).appendTo($("#iconorimage"));
  $('#windspeed').text('WindSpeed : ' + data["current_observation"]["wind_kph"]);
  $('#time').text('Time : ' + data["current_observation"]["observation_time"]);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="wrapper">
<span id="temp"></span><br/>
<span id="high"></span><br/>
<span id="low"></span><br/>
<span id="windspeed"></span><br/>
<span id="description"></span><br/>
<span id="city"></span><br/>
<span id="iconorimage"></span><br/>
<span id="time"></span><br/>
<span id="any thing else"></span><br/>
</div>
</body>
</html></code>```

Title: Using a JSON script in HTML and show data

Body:
You can access json object similar to the way one access the object property in javascript.

$.ajax({
  dataType: "json",
  url:"//api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json",
  success: function(data){
    $('#city').text("City : " + data["current_observation"]["display_location"]["city"]);
    $('#high').text("High : " + "");//Insert data for high here
    $('#low').text("Low : " +""); //Insert data for low here
    $('#temp').text("Tempearature : " + data["current_observation"]["temperature_string"]);
    $('#description').text("Description : " + data["current_observation"]["icon"]);
    $('<img />').attr('src',data["current_observation"]["icon_url"]).appendTo($("#iconorimage"));
  $('#windspeed').text('WindSpeed : ' + data["current_observation"]["wind_kph"]);
  $('#time').text('Time : ' + data["current_observation"]["observation_time"]);
  }
});

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="wrapper">
<span id="temp"></span><br/>
<span id="high"></span><br/>
<span id="low"></span><br/>
<span id="windspeed"></span><br/>
<span id="description"></span><br/>
<span id="city"></span><br/>
<span id="iconorimage"></span><br/>
<span id="time"></span><br/>
<span id="any thing else"></span><br/>
</div>
</body>
</html>


问:
Ranking in PHP and MySQL
```<code>  `id` int(11) NOT NULL,
  `ip` text NOT NULL,
  `song` text NOT NULL,
  `vote` int(11) NOT NULL
</code>```

I have created a voting system and I would like to print the songs with more votes ... how do I do it? Thank you

答:
I think you need to try for counting total votes for the song</p>

```<code>SELECT SUM(vote)as VOTECOUNT, song FROM votes GROUP BY song ORDER BY SUM(vote) DESC LIMIT 10
</code>```

Title: Ranking in PHP and MySQL

Body:
  `id` int(11) NOT NULL,
  `ip` text NOT NULL,
  `song` text NOT NULL,
  `vote` int(11) NOT NULL

I have created a voting system and I would like to print the songs with more votes ... how do I do it? Thank you

Body:
I think you need to try for counting total votes for the song

SELECT SUM(vote)as VOTECOUNT, song FROM votes GROUP BY song ORDER BY SUM(vote) DESC LIMIT 10


问:
Could not read from remote repository in IntellIJ
I'm working on a school project via an IDE that is new for me: IntellIJ.

In order to submit my project (via git) I created a Git repository, added the correct remote with its password and tried to push my work on the master branch (after adding / committing said work with success).

At first I received the following error message:

Push failed: Failed with error: fatal: Could not read from remote repository.

I then went into my settings and set my SSH executable to Native to try and solve this problem. But it did not work, and I can't seem to push my project on this remote even though the password I inputed was correct.

Here is my .git/config file:

```<code>[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = git@git.epitech.eu:/kade_c/Java_jcoinche_2016
    fetch = +refs/heads/*:refs/remotes/origin/*
</code>```

Where did I go wrong?

答:
From my experience this seems to be most often caused by SSH Keys with a passphrase, JetBrains IDEs have no mechanism to prompt for the passphrase and therefore fail to authenticate properly. The only solutions I have found that resolve this issue are to either use a key without a passphrase or use to HTTPS remotes.

Note: Another issue you might face is with hashed known_hosts compatibility with Intellij. See this answer to fix it: https://stackoverflow.com/a/28294279/1311745

Body:
I'm working on a school project via an IDE that is new for me: IntellIJ.

In order to submit my project (via git) I created a Git repository, added the correct remote with its password and tried to push my work on the master branch (after adding / committing said work with success).

At first I received the following error message:

Push failed: Failed with error: fatal: Could not read from remote repository.

I then went into my settings and set my SSH executable to Native to try and solve this problem. But it did not work, and I can't seem to push my project on this remote even though the password I inputed was correct.

Here is my .git/config file:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = git@git.epitech.eu:/kade_c/Java_jcoinche_2016
    fetch = +refs/heads/*:refs/remotes/origin/*

Where did I go wrong?


问:
Compile dll as earlier build
When I try to run the dll I compiled in Visual Studio 2010, I get the following message: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.  I'm guessing this means that I am a too recent version of Visual Studio.  Is there a way I can build the dll as an earlier version?

答:
All assemblies in your final solution, be they dlls or exes, in different solutions or in the same one, must target the same version of the CLR.  You can ensure they do by configuring targeting in your 2010 solution.

Most likely you're targeting 4.0 in your dll's project.  Crank it back to 3.5 or earlier and see if that fixes the problem.

Title: Compile dll as earlier build


问:
How to dump from file in server
I have Rails App with two model

post.rb

```<code> class Post < ActiveRecord::Base
    #  id                  :integer(11)    not null, primary key
    #  title            :text
    #  body          :text
 end
</code>```

and post_dumps.rb

```<code>   class PostDump < ActiveRecord::Base
      #  id                  :integer(11)    not null, primary key
      #  dupm_file
      mount_uploader :dupm_file, DumpUploader # sql file was uploaded
    end
</code>```

How to create method like this in  PostDumpsController

```<code>class PostDumpsController < ApplicationController
  def update_posts_from_dump
    @dump = PostDump.find(params[:id])
    Post.destroy_all
    # run from root user in server
    mysql -uroot -ppasswrord production_bd < @dump.dupm_file_url
  end
end
</code>```

答:
Why don't you use rake task for anything like this. Use a location on
  your server where from where you can dump data into the database. You
  can even schedule it using cronjob.

Note: I am unaware of the exact requirement, why you want to do this but if something of this sort is to be done then above mentioned is a better approach.

Title: How to dump from file in server

Body:
I have Rails App with two model

post.rb

 class Post < ActiveRecord::Base
    #  id                  :integer(11)    not null, primary key
    #  title            :text
    #  body          :text
 end

and post_dumps.rb

   class PostDump < ActiveRecord::Base
      #  id                  :integer(11)    not null, primary key
      #  dupm_file
      mount_uploader :dupm_file, DumpUploader # sql file was uploaded
    end

How to create method like this in  PostDumpsController

class PostDumpsController < ApplicationController
  def update_posts_from_dump
    @dump = PostDump.find(params[:id])
    Post.destroy_all
    # run from root user in server
    mysql -uroot -ppasswrord production_bd < @dump.dupm_file_url
  end
end


问:
how to set equal margin between recyclerview items

See this Image

I achieved the current margin from xml layout but its not same through all four sides.

How to get equal margin

My current xml layout

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp">

<ImageView
    android:id="@+id/iv_photo"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_marginEnd="6dp"
    android:layout_marginTop="6dp"
    android:adjustViewBounds="true"
    android:background="@color/colorPrimary"
    android:foreground="?android:attr/selectableItemBackground"
    android:scaleType="fitXY" />

</RelativeLayout>
</code>```

答:
You can use ItemDecoration for this purpose

```<code>public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
  private int space;

  public SpacesItemDecoration(int space) {
    this.space = space;
  }

  @Override
  public void getItemOffsets(Rect outRect, View view,
      RecyclerView parent, RecyclerView.State state) {
    outRect.left = space;
    outRect.right = space;
    outRect.bottom = space;

    // Add top margin only for the first item to avoid double space between items
    if (parent.getChildLayoutPosition(view) == 0) {
        outRect.top = space;
    } else {
        outRect.top = 0;
    }
  }
}
</code>```

This is how you will use it in java code

```<code>mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
</code>```

This solution was provided by @ianhanniballake. Hope this will help you.

Body:
See this Image

I achieved the current margin from xml layout but its not same through all four sides.

How to get equal margin

My current xml layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp">

<ImageView
    android:id="@+id/iv_photo"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_marginEnd="6dp"
    android:layout_marginTop="6dp"
    android:adjustViewBounds="true"
    android:background="@color/colorPrimary"
    android:foreground="?android:attr/selectableItemBackground"
    android:scaleType="fitXY" />

</RelativeLayout>

Body:
You can use ItemDecoration for this purpose

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
  private int space;

  public SpacesItemDecoration(int space) {
    this.space = space;
  }

  @Override
  public void getItemOffsets(Rect outRect, View view,
      RecyclerView parent, RecyclerView.State state) {
    outRect.left = space;
    outRect.right = space;
    outRect.bottom = space;

    // Add top margin only for the first item to avoid double space between items
    if (parent.getChildLayoutPosition(view) == 0) {
        outRect.top = space;
    } else {
        outRect.top = 0;
    }
  }
}

This is how you will use it in java code

mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));

This solution was provided by @ianhanniballake. Hope this will help you.


问:
cout value without touching variable C++
When I run the program, it prints the value of variable a. But when I comment the line 'cout<<&b<<endl<<&a<<endl;' it prints a garbage value.
What can be the explanation behind it?

```<code>#include<iostream>
using namespace std;

int main()
{
    int a = 9;
    int b = 10;
    int *pb = &b;
    cout<<&b<<endl<<&a<<endl;
    cout<<*(pb+1);
}
</code>```

答:
The garbage value on your screen is the address of a and b . and you should try this :</p>

```<code>int *pb = &b;
</code>```

Body:
When I run the program, it prints the value of variable a. But when I comment the line 'cout<<&b<<endl<<&a<<endl;' it prints a garbage value.
What can be the explanation behind it?

#include<iostream>
using namespace std;

int main()
{
    int a = 9;
    int b = 10;
    int *pb = &b;
    cout<<&b<<endl<<&a<<endl;
    cout<<*(pb+1);
}

Body:
The garbage value on your screen is the address of a and b . and you should try this :

int *pb = &b;


问:
How to swap value in SQL Server?
I want to swap the value between the row but I don't have an idea how to make it as I create a script to do it but the answer still not correct. I get the data raw in from the pdf then convert it into excel 'xls'.

Please see the sample below.

```<code>DECLARE @MyTable TABLE(Id INT, RoomNo INT, Class VARCHAR(10), Price VARCHAR(255))

INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 1,    21,     'A',        '43,028,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 2,    NULL,   NULL,       '43,896,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 3,    20,     'A',        '42,681,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 4,    NULL,   NULL,       '43,549,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 5,    19,     'A',        '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 6,    NULL,   NULL,       '43,202,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 7,    18,     'A',        '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 8,    NULL,   NULL,       '42,855,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 9,    17,     'A',        '41,467,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 10,   NULL,   NULL,       '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 11,   16,     'A',        '41,120,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 12,   NULL,   NULL,       '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 13,   NULL,   'A',        '39,211,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 14,   9,      NULL,       '40,079,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 15,   NULL,   NULL,       '38,691,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 16,   6,      NULL,       '39,385,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 17,   NULL,   'A',        '44,756,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 18,   5,      NULL,       '45,591,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 19,   21,     'B',        '26,598,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 20,   20,     'B',        '26,393,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 21,   NULL,   NULL,       '26,905,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 22,   19,     'B',        '26,189,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 23,   NULL,   NULL,       '26,700,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 24,   18,     'B',        '25,984,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 25,   NULL,   NULL,       '26,496,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 26,   17,     'B',        '25,677,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 27,   NULL,   'B',        '24,041,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 28,   6,      NULL,       '24,552,000'
</code>```

what i tried

```<code>SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)),
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)),
        Price
    FROM @MyTable as MyTable
</code>```

Result is wrong:

```<code>Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  21          A           43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  20          A           42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  19          A           42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  18          A           41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  17          A           41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  16          A           41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  16          A           39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  9           A           38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  6           A           44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  20          B           26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  19          B           26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  18          B           25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  17          B           24,041,000
28  6       NULL    24,552,000  6           B           24,552,000
</code>```

I want to achieve:

```<code>Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  NULL        NULL        43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  NULL        NULL        42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  NULL        NULL        42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  NULL        NULL        41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  NULL        NULL        41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  NULL        NULL        41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  NULL        NULL        39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  NULL        NULL        38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  NULL        NULL        44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  NULL        NULL        26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  NULL        NULL        26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  NULL        NULL        25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  NULL        NULL        24,041,000
28  6       NULL    24,552,000  6           B           24,552,000
</code>```

答:
Can you try the following,</p>

```<code>    select  a.Id, a.RoomNo, a.Class, a.Price,
        b.Id Idb,
        case when a.RoomNo IS NULL THEN b.RoomNo
             else NULL
        end [swap roomno],
        case when a.Class IS NULL THEN b.Class
             else NULL
        end [swap class]
from @mytable a
    left join @mytable b on a.Id - 1 = b.Id
</code>```

Title: How to swap value in SQL Server?

Body:
I want to swap the value between the row but I don't have an idea how to make it as I create a script to do it but the answer still not correct. I get the data raw in from the pdf then convert it into excel 'xls'.

Please see the sample below.

DECLARE @MyTable TABLE(Id INT, RoomNo INT, Class VARCHAR(10), Price VARCHAR(255))

INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 1,    21,     'A',        '43,028,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 2,    NULL,   NULL,       '43,896,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 3,    20,     'A',        '42,681,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 4,    NULL,   NULL,       '43,549,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 5,    19,     'A',        '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 6,    NULL,   NULL,       '43,202,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 7,    18,     'A',        '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 8,    NULL,   NULL,       '42,855,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 9,    17,     'A',        '41,467,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 10,   NULL,   NULL,       '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 11,   16,     'A',        '41,120,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 12,   NULL,   NULL,       '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 13,   NULL,   'A',        '39,211,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 14,   9,      NULL,       '40,079,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 15,   NULL,   NULL,       '38,691,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 16,   6,      NULL,       '39,385,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 17,   NULL,   'A',        '44,756,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 18,   5,      NULL,       '45,591,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 19,   21,     'B',        '26,598,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 20,   20,     'B',        '26,393,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 21,   NULL,   NULL,       '26,905,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 22,   19,     'B',        '26,189,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 23,   NULL,   NULL,       '26,700,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 24,   18,     'B',        '25,984,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 25,   NULL,   NULL,       '26,496,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 26,   17,     'B',        '25,677,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 27,   NULL,   'B',        '24,041,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 28,   6,      NULL,       '24,552,000'

what i tried

SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)),
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)),
        Price
    FROM @MyTable as MyTable

Result is wrong:

Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  21          A           43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  20          A           42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  19          A           42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  18          A           41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  17          A           41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  16          A           41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  16          A           39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  9           A           38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  6           A           44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  20          B           26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  19          B           26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  18          B           25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  17          B           24,041,000
28  6       NULL    24,552,000  6           B           24,552,000

I want to achieve:

Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  NULL        NULL        43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  NULL        NULL        42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  NULL        NULL        42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  NULL        NULL        41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  NULL        NULL        41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  NULL        NULL        41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  NULL        NULL        39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  NULL        NULL        38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  NULL        NULL        44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  NULL        NULL        26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  NULL        NULL        26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  NULL        NULL        25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  NULL        NULL        24,041,000
28  6       NULL    24,552,000  6           B           24,552,000

Body:
Can you try the following,

    select  a.Id, a.RoomNo, a.Class, a.Price,
        b.Id Idb,
        case when a.RoomNo IS NULL THEN b.RoomNo
             else NULL
        end [swap roomno],
        case when a.Class IS NULL THEN b.Class
             else NULL
        end [swap class]
from @mytable a
    left join @mytable b on a.Id - 1 = b.Id


问:
How to parse date string to Date?
How do I parse the date string below into a Date object?

```<code>String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result =  df.parse(target);
</code>```

Throws exception...

```<code>java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
        at java.text.DateFormat.parse(DateFormat.java:337)
</code>```

答:
```<code>new SimpleDateFormat("EEE MMM dd kk:mm:ss ZZZ yyyy");
</code>```

and

```<code>new SimpleDateFormat("EEE MMM dd kk:mm:ss Z yyyy");
</code>```

still runs. However, if your code throws an exception it is because your tool or jdk or any other reason. Because I got same error in my IDE but please check these http://ideone.com/Y2cRr (online ide) with ZZZ and with Z

output is : Thu Sep 28 11:29:30 GMT 2000

Title: How to parse date string to Date?

Body:
How do I parse the date string below into a Date object?

String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result =  df.parse(target);

Throws exception...

java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
        at java.text.DateFormat.parse(DateFormat.java:337)

Body:
new SimpleDateFormat("EEE MMM dd kk:mm:ss ZZZ yyyy");

and

new SimpleDateFormat("EEE MMM dd kk:mm:ss Z yyyy");

still runs. However, if your code throws an exception it is because your tool or jdk or any other reason. Because I got same error in my IDE but please check these http://ideone.com/Y2cRr (online ide) with ZZZ and with Z

output is : Thu Sep 28 11:29:30 GMT 2000


问:
How to instruct Spring to Autowire a field in a chain of tightly coupled objects
It's kinda hard to explain... Hope the question isn't vague...

you can look at the code to get the idea...

ClassA.java

```<code>public class ClassA {
    @Autowired
    InterA abcd;
    public void dododo() {
        abcd.doit();
    }
}
</code>```

ClassB.java

```<code>@Component
public class ClassB implements InterA {
    @Override
    public void doit() {
        System.out.println("hoo hoo");
    }
}
</code>```

ClassC.java

```<code>@Component("classc")
public class ClassC {
    public void doFromAbove() {
        ClassA cls = new ClassA();
        cls.dododo();
    }
}
</code>```

Interface InterA.java

```<code>public interface InterA {
    public void doit();
}
</code>```

Configuration ClassConfig.java (on the same package of other java class files)

```<code>@Configuration
@ComponentScan
public class ClassConfig {
}
</code>```

Main Method

```<code>public static void main(String[] args) {
    try(AbstractApplicationContext appctx = new AnnotationConfigApplicationContext(ClassConfig.class)) {
        ClassC obj = (ClassC) appctx.getBean("classc");
        obj.doFromAbove();
    }
}
</code>```

When I execute the main method, the Autowired field "abcd" in ClassA didn't get injected and results in a NullPointerException

It works only when I declare ClassA as a @Component and get it's bean... indirect autowiring is not happening

Should I decouple ClassA from ClassC and make everything loosely coupled?

Is there any simple annotation that I can use to tell Spring auto inject the @Autowired field even when the object is created in a tight coupled fashion?

Note
please don't tell me to use ApplicationContext in ClassC to create the bean of ClassA .

Any Spring Geek who could find an answer?

答:
The beans declared within Spring container (either through XML or annotations like @Component) are Spring-managed - Spring will take care of them, will make sure they exist when you request them via ApplicationContext.getBean() and that their dependencies are injected as well.

When you create an instance yourself (cls = new ClassA()), that instance is not Spring-managed and Spring will not do anything to it. In fact, Spring won't (and cannot) even know the object exists.

Some confusion may stem from that you annotate the class with the Spring annotations - but it's really objects (instances) that are actually used in Java; even if the class is annotated, the annotations will only apply on instances that are created and managed by Spring.

Body:
It's kinda hard to explain... Hope the question isn't vague...

you can look at the code to get the idea...

ClassA.java

public class ClassA {
    @Autowired
    InterA abcd;
    public void dododo() {
        abcd.doit();
    }
}

ClassB.java

@Component
public class ClassB implements InterA {
    @Override
    public void doit() {
        System.out.println("hoo hoo");
    }
}

ClassC.java

@Component("classc")
public class ClassC {
    public void doFromAbove() {
        ClassA cls = new ClassA();
        cls.dododo();
    }
}

Interface InterA.java

public interface InterA {
    public void doit();
}

Configuration ClassConfig.java (on the same package of other java class files)

@Configuration
@ComponentScan
public class ClassConfig {
}

Main Method

public static void main(String[] args) {
    try(AbstractApplicationContext appctx = new AnnotationConfigApplicationContext(ClassConfig.class)) {
        ClassC obj = (ClassC) appctx.getBean("classc");
        obj.doFromAbove();
    }
}

When I execute the main method, the Autowired field "abcd" in ClassA didn't get injected and results in a NullPointerException

It works only when I declare ClassA as a @Component and get it's bean... indirect autowiring is not happening

Should I decouple ClassA from ClassC and make everything loosely coupled?

Is there any simple annotation that I can use to tell Spring auto inject the @Autowired field even when the object is created in a tight coupled fashion?

Note
please don't tell me to use ApplicationContext in ClassC to create the bean of ClassA .

Any Spring Geek who could find an answer?