问:
Pod file not being initialized?
When i try to initialize pod file to use cocoapods via terminal, it gives me this error. How to fix it.

```<code>/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command.rb:128:in `verify_minimum_git_version!': [!] You need at least git version 1.8.5 to use CocoaPods (Pod::Informative)
</code>```

答:
If you have upgraded your MAC from the App Store, then you need to run: xcode-select --install

When I ran git --version before running the command above, it didn't find git at all. It displayed this error: missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun. So, I'm guessing when I upgraded my machine somehow I lost git. Regardless, running the above command worked.

I then ran git --version and it showed the git version that was installed.

Reference: http://tips.tutorialhorizon.com/2015/10/01/xcrun-error-invalid-active-developer-path-library-developer-commandline-tools-missing-xcrun/

Title: Pod file not being initialized?

Body:
When i try to initialize pod file to use cocoapods via terminal, it gives me this error. How to fix it.

/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command.rb:128:in `verify_minimum_git_version!': [!] You need at least git version 1.8.5 to use CocoaPods (Pod::Informative)


来源: stackexchange

问:
lxml etree parse failure (IOError)
I am trying to run this program.  It was working fine until today.  Nothing was changed on my end in the code.

```<code>import lxml.etree
import urlparse
import re

def parse_url(url):
    return lxml.etree.parse(url, lxml.etree.HTMLParser())

urlivv = "http://finance.yahoo.com/q?s=IVV"
docivv = parse_url(urlivv)
</code>```

This is my error message:

IOError: Error reading file 'http://finance.yahoo.com/q?s=IVV': failed to load external entity "http://finance.yahoo.com/q?s=IVV"

There was some documentation on the site about adding StringIO to the argument (see below).  But I find it odd I never had to do this before.

```<code>tree = etree.parse(StringIO(myString))
</code>```

Edit: More complete stack trace.

```<code>>>> import lxml.etree
>>> tree = lxml.etree.parse('http://finance.yahoo.com/q?s=IVV', parser=lxml.etree.HTMLParser())
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "src\lxml\lxml.etree.pyx", line 3427, in lxml.etree.parse (src\lxml\lxml.etree.c:81100)
  File "src\lxml\parser.pxi", line 1811, in lxml.etree._parseDocument (src\lxml\lxml.etree.c:117831)
  File "src\lxml\parser.pxi", line 1837, in lxml.etree._parseDocumentFromURL (src\lxml\lxml.etree.c:118178)
  File "src\lxml\parser.pxi", line 1741, in lxml.etree._parseDocFromFile (src\lxml\lxml.etree.c:117090)
  File "src\lxml\parser.pxi", line 1138, in lxml.etree._BaseParser._parseDocFromFile (src\lxml\lxml.etree.c:111636)
  File "src\lxml\parser.pxi", line 595, in lxml.etree._ParserContext._handleParseResultDoc (src\lxml\lxml.etree.c:105092)
  File "src\lxml\parser.pxi", line 706, in lxml.etree._handleParseResult (src\lxml\lxml.etree.c:106800)
  File "src\lxml\parser.pxi", line 633, in lxml.etree._raiseParseError (src\lxml\lxml.etree.c:105611)
OSError: Error reading file 'http://finance.yahoo.com/q?s=IVV': failed to load external entity "http://finance.yahoo.com/q?s=IVV"
</code>```

答:
If you're looking for an explanation you can stop reading now. On the other hand, if you seek a remedy then this might be it.

```<code>>>> page = requests.get('http://finance.yahoo.com/q?s=IVV').text
>>> lxml.etree.fromstring(page) #fails
>>> tree = lxml.etree.fromstring(page, parser=lxml.etree.HTMLParser())
>>> tree.xpath('.//table[@class="W(100%)"]')
[<Element table at 0x607dc08>]
</code>```

In short, use requests to fetch the page as a string, parse that string with lxml and continue as usual.

Edit: Before this code will run you will need import requests and import lxml.etree.

ContentLicense: CC BY-SA 3.0

Title: lxml etree parse failure (IOError)

Body:
I am trying to run this program.  It was working fine until today.  Nothing was changed on my end in the code.

import lxml.etree
import urlparse
import re

def parse_url(url):
    return lxml.etree.parse(url, lxml.etree.HTMLParser())

urlivv = "http://finance.yahoo.com/q?s=IVV"
docivv = parse_url(urlivv)

This is my error message:

IOError: Error reading file 'http://finance.yahoo.com/q?s=IVV': failed to load external entity "http://finance.yahoo.com/q?s=IVV"

There was some documentation on the site about adding StringIO to the argument (see below).  But I find it odd I never had to do this before.

tree = etree.parse(StringIO(myString))

Edit: More complete stack trace.

>>> import lxml.etree
>>> tree = lxml.etree.parse('http://finance.yahoo.com/q?s=IVV', parser=lxml.etree.HTMLParser())
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "src\lxml\lxml.etree.pyx", line 3427, in lxml.etree.parse (src\lxml\lxml.etree.c:81100)
  File "src\lxml\parser.pxi", line 1811, in lxml.etree._parseDocument (src\lxml\lxml.etree.c:117831)
  File "src\lxml\parser.pxi", line 1837, in lxml.etree._parseDocumentFromURL (src\lxml\lxml.etree.c:118178)
  File "src\lxml\parser.pxi", line 1741, in lxml.etree._parseDocFromFile (src\lxml\lxml.etree.c:117090)
  File "src\lxml\parser.pxi", line 1138, in lxml.etree._BaseParser._parseDocFromFile (src\lxml\lxml.etree.c:111636)
  File "src\lxml\parser.pxi", line 595, in lxml.etree._ParserContext._handleParseResultDoc (src\lxml\lxml.etree.c:105092)
  File "src\lxml\parser.pxi", line 706, in lxml.etree._handleParseResult (src\lxml\lxml.etree.c:106800)
  File "src\lxml\parser.pxi", line 633, in lxml.etree._raiseParseError (src\lxml\lxml.etree.c:105611)
OSError: Error reading file 'http://finance.yahoo.com/q?s=IVV': failed to load external entity "http://finance.yahoo.com/q?s=IVV"

Body:
If you're looking for an explanation you can stop reading now. On the other hand, if you seek a remedy then this might be it.

>>> page = requests.get('http://finance.yahoo.com/q?s=IVV').text
>>> lxml.etree.fromstring(page) #fails
>>> tree = lxml.etree.fromstring(page, parser=lxml.etree.HTMLParser())
>>> tree.xpath('.//table[@class="W(100%)"]')
[<Element table at 0x607dc08>]

In short, use requests to fetch the page as a string, parse that string with lxml and continue as usual.

Edit: Before this code will run you will need import requests and import lxml.etree.


问:
Get field values using reflection
I am not able to get the field value.What I am trying to do is get the Object at runtime. Please let me know where I am going wrong.

Test.class

```<code>import java.lang.reflect.Field;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {

    final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
    field.setAccessible(true);
    field.get(Class.forName("com.logging.EX"));
}
</code>```

}

EX.class

```<code>public class EX {

private String value;

public EX(){
    value="data";
}
/**
 * @return the value
 */
public String getValue() {
    return value;
}

/**
 * @param value
 *            the value to set
 */
public void setValue(String value) {
    this.value = value;
}
</code>```

}

答:
You need the EX isntance on field.get().</p>

```<code>final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
field.setAccessible(true);
field.get(new EX());
</code>```

Title: Get field values using reflection

Body:
I am not able to get the field value.What I am trying to do is get the Object at runtime. Please let me know where I am going wrong.

Test.class

import java.lang.reflect.Field;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {

    final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
    field.setAccessible(true);
    field.get(Class.forName("com.logging.EX"));
}

}

EX.class

public class EX {

private String value;

public EX(){
    value="data";
}
/**
 * @return the value
 */
public String getValue() {
    return value;
}

/**
 * @param value
 *            the value to set
 */
public void setValue(String value) {
    this.value = value;
}

}

Body:
You need the EX isntance on field.get().

final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
field.setAccessible(true);
field.get(new EX());


问:
How do I save a list in a .py file?
I am reading the contents of a normal text file and then trying to save it in  a .py file as a list variable.

Initially what I tried was reading the contents of the file and then storing them in a list. Then I wrote them to a .py file by myself.

```<code>>>> f = open("word.txt","r+")
>>> string = f.read()
>>> string = (string.split("\n")) #checkpoint
>>> string = "\',\' ".join(string)
>>> len(string)
147636
>>> f.close()
>>> f = open("word.py","w")
>>> f.write("word = [\'")
>>> f.write(string)
>>> f.write("\']")
>>> f.close()
</code>```

However when I try to use import word
I get the following error

SyntaxError: EOF while scanning triple-quoted string literal

Is there any way I can save the list string at the checkpoint shown into .py file?

答:
The immediate problem is that you used import on a file that is not a Python module.  You cannot write out a list value as a text and simply regain it as a list value through a trivial input operation.

When you import your value, Python tries to parse it as a code file.  Somewhere in the file you wrote is a triple-quote (opening) without a closing triple-quote.  Python hit end of file and finally realized that there's no end to the string.  This is where it gets mad: you lied to Python.  You told it this would be a legal module, and gave it something that's not even legal tokens.  :-)

You need to find a viable way to transfer that list value.  I can't suggest anything here, because you haven't described the higher-level problem.

Title: How do I save a list in a .py file?

Body:
I am reading the contents of a normal text file and then trying to save it in  a .py file as a list variable.

Initially what I tried was reading the contents of the file and then storing them in a list. Then I wrote them to a .py file by myself.

>>> f = open("word.txt","r+")
>>> string = f.read()
>>> string = (string.split("\n")) #checkpoint
>>> string = "\',\' ".join(string)
>>> len(string)
147636
>>> f.close()
>>> f = open("word.py","w")
>>> f.write("word = [\'")
>>> f.write(string)
>>> f.write("\']")
>>> f.close()

However when I try to use import word
I get the following error

SyntaxError: EOF while scanning triple-quoted string literal

Is there any way I can save the list string at the checkpoint shown into .py file?


问:
Compare two variables in an SQL WHILE loop
I am getting the error

Msg 102, Level 15, State 1, Line 16

  Incorrect syntax near '@PacketCode'.

when I try to execute. Something is wrong with my WHILE loop but I can't see what. Any suggestions?

```<code>DECLARE @PacketCode as varchar(255)
SET @PacketCode = 'ZZZ_Archive_TEST'

DECLARE @Value as varchar(255)
SET @Value = ''

DECLARE @i int
SET @i = 1

SELECT
    @Value = (SELECT packetcode
              FROM tblScriptReports
              WHERE packetcode = @PacketCode)

WHILE (@PacketCode = @Value)
BEGIN
    @PacketCode = @PacketCode + ' (' + @i + ')'

    SELECT @Value = (SELECT packetcode
                    FROM tblScriptReports
                    WHERE packetcode = @PacketCode)

    SET @i = @i + 1
END

SELECT @PacketCode
</code>```

答:
Try to add a SET in front of the @PacketCode in the BEGIN:</p>

```<code>DECLARE @PacketCode as varchar(255)
set @PacketCode = 'ZZZ_Archive_TEST'

DECLARE @Value as varchar(255)
set @Value = ''

DECLARE @i int
set @i = 1

SELECT @Value = (SELECT packetcode
             FROM tblScriptReports
             WHERE packetcode = @PacketCode)

WHILE (@PacketCode = @Value)

BEGIN

SET @PacketCode = @PacketCode + ' (' + @i + ')'

    SELECT @Value = (SELECT packetcode
                    FROM tblScriptReports
                    WHERE packetcode = @PacketCode)

    set @i = @i + 1
END

select @PacketCode
</code>```

Body:
I am getting the error

Msg 102, Level 15, State 1, Line 16

  Incorrect syntax near '@PacketCode'.

when I try to execute. Something is wrong with my WHILE loop but I can't see what. Any suggestions?

DECLARE @PacketCode as varchar(255)
SET @PacketCode = 'ZZZ_Archive_TEST'

DECLARE @Value as varchar(255)
SET @Value = ''

DECLARE @i int
SET @i = 1

SELECT
    @Value = (SELECT packetcode
              FROM tblScriptReports
              WHERE packetcode = @PacketCode)

WHILE (@PacketCode = @Value)
BEGIN
    @PacketCode = @PacketCode + ' (' + @i + ')'

    SELECT @Value = (SELECT packetcode
                    FROM tblScriptReports
                    WHERE packetcode = @PacketCode)

    SET @i = @i + 1
END

SELECT @PacketCode

Body:
Try to add a SET in front of the @PacketCode in the BEGIN:

DECLARE @PacketCode as varchar(255)
set @PacketCode = 'ZZZ_Archive_TEST'

DECLARE @Value as varchar(255)
set @Value = ''

DECLARE @i int
set @i = 1

SELECT @Value = (SELECT packetcode
             FROM tblScriptReports
             WHERE packetcode = @PacketCode)

WHILE (@PacketCode = @Value)

BEGIN

SET @PacketCode = @PacketCode + ' (' + @i + ')'

    SELECT @Value = (SELECT packetcode
                    FROM tblScriptReports
                    WHERE packetcode = @PacketCode)

    set @i = @i + 1
END

select @PacketCode


问:
How do I turn a single column table into multiple columns based solely on row number?
So, I have this data that exists in a single column. Odd rows are ID, even rows are city. Is there a way to split this into two columns?

```<code>    DECLARE @Data TABLE (
          DataRow       NVARCHAR(50)
          )

    INSERT INTO @Data VALUES

          ('1'              )
        , ('Albuquerque'    )
        , ('2'              )
        , ('Boston'         )
        , ('3'              )
        , ('Chicago'        )
        , ('4'              )
        , ('Dayton'         )
        , ('5'              )
        , ('Eumenclaw'      )
        , ('6'              )
        , ('Fresno'         )
</code>```

Right now I'm using the following code, but it seems like there should be a more efficient way using a pivot table.

```<code>    DECLARE @DataID TABLE (
            ID          INT IDENTITY
          , DataRow     NVARCHAR(50)
          )

    INSERT INTO @DataID
        SELECT * FROM @Data

    DECLARE @CityData TABLE (
          ID            INT
        , City          NVARCHAR(100)
        )

    DECLARE   @Counter      INT = 0
            , @ID           INT
            , @City         NVARCHAR(50)

    WHILE @Counter < (SELECT MAX(ID) / 2 FROM @DataID WHERE ID%2 = 0)
        BEGIN
            SET @Counter += 1
            SET @ID = (SELECT CAST(DataRow AS INT) FROM @DataID WHERE ID = @Counter * 2 - 1)
            SET @City = (SELECT DataRow FROM @DataID WHERE ID = @Counter * 2)
            INSERT INTO @CityData
                SELECT @ID, @City

        END

    SELECT * FROM @CityData
</code>```

Results:

Oh, and apologies to those of you from Washington for the misspelling. And hopefully not New Mexico.

答:
This will work with your small table variable, however, if coming from a table, there is no inherent row order, and results can not be gtd.

Example

```<code>Select ID   = max(case when DataRow Like     '[0-9]%' then DataRow end)
      ,City = max(case when DataRow Not Like '[0-9]%' then DataRow end)
 From (
        Select *
              ,Grp = (Row_Number() over (Order by (Select NULL)) -1) / 2
         From @Data
      ) A
 Group By Grp
</code>```

Returns

```<code>ID  City
1   Albuquerque
2   Boston
3   Chicago
4   Dayton
5   Eumenclaw
6   Fresno
</code>```

Body:
So, I have this data that exists in a single column. Odd rows are ID, even rows are city. Is there a way to split this into two columns?

    DECLARE @Data TABLE (
          DataRow       NVARCHAR(50)
          )

    INSERT INTO @Data VALUES

          ('1'              )
        , ('Albuquerque'    )
        , ('2'              )
        , ('Boston'         )
        , ('3'              )
        , ('Chicago'        )
        , ('4'              )
        , ('Dayton'         )
        , ('5'              )
        , ('Eumenclaw'      )
        , ('6'              )
        , ('Fresno'         )

Right now I'm using the following code, but it seems like there should be a more efficient way using a pivot table.

    DECLARE @DataID TABLE (
            ID          INT IDENTITY
          , DataRow     NVARCHAR(50)
          )

    INSERT INTO @DataID
        SELECT * FROM @Data

    DECLARE @CityData TABLE (
          ID            INT
        , City          NVARCHAR(100)
        )

    DECLARE   @Counter      INT = 0
            , @ID           INT
            , @City         NVARCHAR(50)

    WHILE @Counter < (SELECT MAX(ID) / 2 FROM @DataID WHERE ID%2 = 0)
        BEGIN
            SET @Counter += 1
            SET @ID = (SELECT CAST(DataRow AS INT) FROM @DataID WHERE ID = @Counter * 2 - 1)
            SET @City = (SELECT DataRow FROM @DataID WHERE ID = @Counter * 2)
            INSERT INTO @CityData
                SELECT @ID, @City

        END

    SELECT * FROM @CityData

Results:

Oh, and apologies to those of you from Washington for the misspelling. And hopefully not New Mexico.

Body:
This will work with your small table variable, however, if coming from a table, there is no inherent row order, and results can not be gtd.

Example

Select ID   = max(case when DataRow Like     '[0-9]%' then DataRow end)
      ,City = max(case when DataRow Not Like '[0-9]%' then DataRow end)
 From (
        Select *
              ,Grp = (Row_Number() over (Order by (Select NULL)) -1) / 2
         From @Data
      ) A
 Group By Grp

Returns

ID  City
1   Albuquerque
2   Boston
3   Chicago
4   Dayton
5   Eumenclaw
6   Fresno


问:
Unable to scroll image using scroll view in swift
I am facing this weird problem with scroll view in swift, The image does not scroll even after defining scroll view in the file, I have also added zooming and it worked fine. Please help me with this
https://pastebin.com/1uC3fqHG</p>

```<code>import UIKit

class ImageViewController: UIViewController
{
    var imageURL: URL? {
        didSet {
            image = nil
            if view.window != nil {
                fetchImage()
            }
        }
    }

    private func fetchImage() {
        if let url = imageURL {
            let urlContents = try? Data(contentsOf: url)
            if let imageData = urlContents {
                image = UIImage(data: imageData)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(imageView)
        imageURL = URL(string: "http://www.lamborghini.com/en-en/sites/en-en/files/DAM/lamborghini/share%20img/huracan-coupe-facebook-og.jpg")
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if image == nil {
            fetchImage()
        }

    }

    @IBOutlet weak var scrollView: UIScrollView! {
        didSet {

            scrollView.delegate = self
            scrollView.minimumZoomScale = 0.03
            scrollView.maximumZoomScale = 2.0
            scrollView.contentSize = imageView.frame.size
            scrollView.addSubview(imageView)
        }
    }

    fileprivate var imageView = UIImageView()

    private var image: UIImage? {
        get{
            return imageView.image
        }
        set{
            imageView.image = newValue
            imageView.sizeToFit()
            scrollView?.contentSize = imageView.frame.size
        }
    }
}

extension ImageViewController: UIScrollViewDelegate
{
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
}
</code>```

答:
the problem is that you are adding the image to the view in viewDidLoad(). Remove view.addSubview(imageView) from the viewDidLoad() and all will be working perfectly.
Code will become as follows

```<code>import UIKit

class ImageViewController: UIViewController
{
    var imageURL: URL? {
        didSet {
            image = nil
            if view.window != nil {
                fetchImage()
            }
        }
    }

    private func fetchImage() {
        if let url = imageURL {
            let urlContents = try? Data(contentsOf: url)
            if let imageData = urlContents {
                image = UIImage(data: imageData)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        imageURL = URL(string: "http://www.lamborghini.com/en-en/sites/en-en/files/DAM/lamborghini/share%20img/huracan-coupe-facebook-og.jpg")
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if image == nil {
            fetchImage()
        }

    }

    @IBOutlet weak var scrollView: UIScrollView! {
        didSet {

            scrollView.delegate = self
            scrollView.minimumZoomScale = 0.03
            scrollView.maximumZoomScale = 2.0
            scrollView.contentSize = imageView.frame.size
            scrollView.addSubview(imageView)
        }
    }

    fileprivate var imageView = UIImageView()

    private var image: UIImage? {
        get{
            return imageView.image
        }
        set{
            imageView.image = newValue
            imageView.sizeToFit()
            scrollView?.contentSize = imageView.frame.size
        }
    }
}

extension ImageViewController: UIScrollViewDelegate
{
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
}
</code>```

Body:
I am facing this weird problem with scroll view in swift, The image does not scroll even after defining scroll view in the file, I have also added zooming and it worked fine. Please help me with this
https://pastebin.com/1uC3fqHG

import UIKit

class ImageViewController: UIViewController
{
    var imageURL: URL? {
        didSet {
            image = nil
            if view.window != nil {
                fetchImage()
            }
        }
    }

    private func fetchImage() {
        if let url = imageURL {
            let urlContents = try? Data(contentsOf: url)
            if let imageData = urlContents {
                image = UIImage(data: imageData)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(imageView)
        imageURL = URL(string: "http://www.lamborghini.com/en-en/sites/en-en/files/DAM/lamborghini/share%20img/huracan-coupe-facebook-og.jpg")
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if image == nil {
            fetchImage()
        }

    }

    @IBOutlet weak var scrollView: UIScrollView! {
        didSet {

            scrollView.delegate = self
            scrollView.minimumZoomScale = 0.03
            scrollView.maximumZoomScale = 2.0
            scrollView.contentSize = imageView.frame.size
            scrollView.addSubview(imageView)
        }
    }

    fileprivate var imageView = UIImageView()

    private var image: UIImage? {
        get{
            return imageView.image
        }
        set{
            imageView.image = newValue
            imageView.sizeToFit()
            scrollView?.contentSize = imageView.frame.size
        }
    }
}

extension ImageViewController: UIScrollViewDelegate
{
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
}

Body:
the problem is that you are adding the image to the view in viewDidLoad(). Remove view.addSubview(imageView) from the viewDidLoad() and all will be working perfectly.
Code will become as follows

import UIKit

class ImageViewController: UIViewController
{
    var imageURL: URL? {
        didSet {
            image = nil
            if view.window != nil {
                fetchImage()
            }
        }
    }

    private func fetchImage() {
        if let url = imageURL {
            let urlContents = try? Data(contentsOf: url)
            if let imageData = urlContents {
                image = UIImage(data: imageData)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        imageURL = URL(string: "http://www.lamborghini.com/en-en/sites/en-en/files/DAM/lamborghini/share%20img/huracan-coupe-facebook-og.jpg")
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if image == nil {
            fetchImage()
        }

    }

    @IBOutlet weak var scrollView: UIScrollView! {
        didSet {

            scrollView.delegate = self
            scrollView.minimumZoomScale = 0.03
            scrollView.maximumZoomScale = 2.0
            scrollView.contentSize = imageView.frame.size
            scrollView.addSubview(imageView)
        }
    }

    fileprivate var imageView = UIImageView()

    private var image: UIImage? {
        get{
            return imageView.image
        }
        set{
            imageView.image = newValue
            imageView.sizeToFit()
            scrollView?.contentSize = imageView.frame.size
        }
    }
}

extension ImageViewController: UIScrollViewDelegate
{
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
}


答:
In TSQL you assign variable values with the SET command.

So instead of this:

```<code>@PacketCode = @PacketCode + ' (' + @i + ')'
</code>```

You must do this:

```<code>SET @PacketCode = @PacketCode + ' (' + @i + ')'
</code>```

Funny that you did this correctly everywhere else in the code.

Title: Compare two variables in an SQL WHILE loop

Body:
In TSQL you assign variable values with the SET command.

So instead of this:

@PacketCode = @PacketCode + ' (' + @i + ')'

You must do this:

SET @PacketCode = @PacketCode + ' (' + @i + ')'

Funny that you did this correctly everywhere else in the code.


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
Having such a long if statement is most likely bad coding.

It makes it very hard to test, and is most likely a code smell.

If possible you should refactor to take advantage of polymorphism.

ContentLicense: CC BY-SA 2.5

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?


问:
Spring Boot SSL Client
I am new to Spring Boot.  So far I am enjoying it.  I have developed a demo SSL rest web server that correctly handles mutual X.509 certificate authentication.  Using an IE browser with self signed client & server certificates, I have tested that the demo rest web server is working correctly -- both the server and browser are successfully exchanging and validating each others certificates.

I am having trouble finding an SSL client example that shows how to include the client certificate and issue the https.  Anybody have a simple rest client example that shows how to consume my ssl server?

Best Regards,
Steve Mansfield

答:
I know its too late, but here is the code that works for me.

```<code>@SpringBootApplication
public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String args[]) {
            makeWebServiceCall();
    }

    public static void makeWebServiceCall() {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        SSLContext sslContext;
        ResponseEntity<String> response = null;
        try {
            sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();

            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

            requestFactory.setHttpClient(httpClient);

            RestTemplate restTemplate = new RestTemplate(requestFactory);

            StringBuffer plainCreds = new StringBuffer();
            plainCreds.append("username");
            plainCreds.append(":");
            plainCreds.append("password");
            byte[] plainCredsBytes = plainCreds.toString().getBytes();
            byte[] base64CredsBytes = Base64.getEncoder().encode(plainCredsBytes);
            String userBase64Credentials = new String(base64CredsBytes);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Basic " + userBase64Credentials);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity entity = new HttpEntity<>(headers);

            String url = "https:restUrl";

            response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

            if(response.getStatusCodeValue() == 200) {
                log.info("Success! Further processing based on the need");
            } else {
                log.info("****************Status code received: " + response.getStatusCodeValue() + ".************************");
            }

        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            log.error("Exception occured. Here are the exception details: ", e);
        } catch(HttpClientErrorException e) {
            if(e.getRawStatusCode() == 403) {
                log.info("****************Status code received: " + e.getRawStatusCode() + ". You do not have access to the requested resource.************************");

            } else if(e.getRawStatusCode() == 404) {
                log.info("****************Status code received: " + e.getRawStatusCode() + ". Resource does not exist(or) the service is not up.************************");

            } else if(e.getRawStatusCode() == 400) {
                log.info("****************Status code received: " + e.getRawStatusCode() + ". Bad Request.************************");

            } else {
                log.info("****************Status code received: " + e.getRawStatusCode() + ".************************");

            }

           log.info("****************Response body: " + e.getResponseBodyAsString() + "************************");
        }
    }
 }
</code>```

Here is the maven filed

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework</groupId>
<artifactId>gs-consuming-rest</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.6</version>
</dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

Title: Spring Boot SSL Client

Body:
I know its too late, but here is the code that works for me.

@SpringBootApplication
public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String args[]) {
            makeWebServiceCall();
    }

    public static void makeWebServiceCall() {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        SSLContext sslContext;
        ResponseEntity<String> response = null;
        try {
            sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();

            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

            requestFactory.setHttpClient(httpClient);

            RestTemplate restTemplate = new RestTemplate(requestFactory);

            StringBuffer plainCreds = new StringBuffer();
            plainCreds.append("username");
            plainCreds.append(":");
            plainCreds.append("password");
            byte[] plainCredsBytes = plainCreds.toString().getBytes();
            byte[] base64CredsBytes = Base64.getEncoder().encode(plainCredsBytes);
            String userBase64Credentials = new String(base64CredsBytes);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Basic " + userBase64Credentials);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity entity = new HttpEntity<>(headers);

            String url = "https:restUrl";

            response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

            if(response.getStatusCodeValue() == 200) {
                log.info("Success! Further processing based on the need");
            } else {
                log.info("****************Status code received: " + response.getStatusCodeValue() + ".************************");
            }

        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            log.error("Exception occured. Here are the exception details: ", e);
        } catch(HttpClientErrorException e) {
            if(e.getRawStatusCode() == 403) {
                log.info("****************Status code received: " + e.getRawStatusCode() + ". You do not have access to the requested resource.************************");

            } else if(e.getRawStatusCode() == 404) {
                log.info("****************Status code received: " + e.getRawStatusCode() + ". Resource does not exist(or) the service is not up.************************");

            } else if(e.getRawStatusCode() == 400) {
                log.info("****************Status code received: " + e.getRawStatusCode() + ". Bad Request.************************");

            } else {
                log.info("****************Status code received: " + e.getRawStatusCode() + ".************************");

            }

           log.info("****************Response body: " + e.getResponseBodyAsString() + "************************");
        }
    }
 }

Here is the maven filed

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework</groupId>
<artifactId>gs-consuming-rest</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.6</version>
</dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

ContentLicense: CC BY-SA 4.0


问:
Clearing the text from the python shell
OK, so I am currently messing around coding hangman in python and was wondering if I can clear what it says in the python shell as I don't just wan't the person to read the word.

```<code>import time
keyword = input(" Please enter the word you want the person to guess")
lives = int(input("How many lives would you like to have?"))
print ("There are ", len(keyword), "letters in the word")

time.sleep(2)

guess = input("please enter your guess")
</code>```

I would like to remove all the text  in the shell.

答:
if you are a windows user use this:

```<code>import os
os.system("cls")
</code>```

Mac/linux then :

```<code>import os
os.system("clear")
</code>```

Title: Clearing the text from the python shell

Body:
OK, so I am currently messing around coding hangman in python and was wondering if I can clear what it says in the python shell as I don't just wan't the person to read the word.

import time
keyword = input(" Please enter the word you want the person to guess")
lives = int(input("How many lives would you like to have?"))
print ("There are ", len(keyword), "letters in the word")

time.sleep(2)

guess = input("please enter your guess")

I would like to remove all the text  in the shell.

Body:
if you are a windows user use this:

import os
os.system("cls")

Mac/linux then :

import os
os.system("clear")


问:
C++ using exceptions
I have a simple question

If I have a code with try and catch, like this

```<code>try
{
...
}
catch(exception& ex)
{
   AfxMessageBox(ex.what());
}
</code>```

Will this catch all the exceptions, even exceptions like bad pointer, etc? And also, if this code is there and for example, the code has a pointer, or memory problem, will it still crash? Or do I have to use

```<code>catch(...)
</code>```

But how can I exactly pinpoint what was the reason of an enentual crash then?

答:
It seems like there is a confusion about different kinds of errors so here is an explanation about different errors and what to do about them. There are three kinds of errors that can happen

Compile error

Runtime error due to triggering undefined behaviour

Runtime error due to system limitations

Here is a list what you need to do about these three

Compile error Your compiler is your friend. Fix your code, but try to avoid circumventing the type system.

Triggering undefined behaviour It looks like you have this kind of problem somewhere in your code. In this case, you have a runtime bug. What you may have done

Dereferenced an invalid pointer

Performed integer division with zero

Used an unsupported assembly-level instruction

Passed an already freed pointer to free

To find problems like solve 1-3, you use the debugger. Also the assert macro is useful. Notice that problems of type 1 can be introduced by failing to check whether or not some functions allocating system resources failed. If so, see Runtime error due to system limitations.

Problems of type 4 are harder to find, since you will notice the problem upon the next malloc. On GNU/Linux, running your program through valgrind is your safest bet. I do not know anything about Windows tools for this.

Runtime error due to system limitations This is where you use exceptions. You could not foresee that a user specified file did not exist, or was encoded in a non-decodable way. Or you try to bring up OpenGL, but the user has not up-to-date graphics drivers, or you are on a remote X11 connection. To "solve" these problems you check the system level return values, and bail out through an exception, that will be caught by your nearest catch statement.

Title: C++ using exceptions

Body:
I have a simple question

If I have a code with try and catch, like this

try
{
...
}
catch(exception& ex)
{
   AfxMessageBox(ex.what());
}

Will this catch all the exceptions, even exceptions like bad pointer, etc? And also, if this code is there and for example, the code has a pointer, or memory problem, will it still crash? Or do I have to use

catch(...)

But how can I exactly pinpoint what was the reason of an enentual crash then?


问:
How to add some jquery in SPA?
I'm using SPA with Angular and trying to use some jquery in my page after rendering the a particular page.
But the problem is that the jquery code doesn't work and no errors on the console either.

Hope you can help me out, here is my code:

app.js:

var app = angular.module('app', ['ngRoute', 'angularCSS']);

app.config(function($routeProvider){

    $routeProvider

    .when('/', {
        templateUrl: 'pages/main.html',
        controller: 'mainController',
        css: 'styles/main.css'
    })

    .when('/second', {
        templateUrl: 'pages/second.html',
        controller: 'secondController',
        css: ['styles/second.css', 'styles/second_2.css']
    });
});

app.controller('mainController', ['$scope', function($scope){

}]);

app.controller('secondController', ['$scope', function($scope){

}]);

the main page, index.html:```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="app">
    <head>
        <title>Untitled Document</title>
        <meta charset="UTF-8">
        <meta name="description" content="">
        <meta name="keywords" content="">
        <link rel="stylesheet" href="styles/viewbox.css">
        <script src="https://code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
        <script src="https://code.angularjs.org/1.3.0-rc.1/angular-route.min.js"></script>
        <script src="angular-css.js"></script>
        <script src="app.js"></script>
    </head>
    <body>
        <div>
            <h3>Main</h3>
            <h3>Second</h3>
        </div>

            <ng-view></ng-view>

    </body>
</html></code>```

and here is the template, second.html:

Hello, this is Second Page

```

答:
Here, I would agree with @War10ck that you should stick to AngularJS to avoid complexity in future. You need to put that function into controller like this:

```<code>app.controller('mainController', ['$scope','$window', function($scope, $window){

$scope.myFunction = function(){
window.alert("my img");
};

}]);
</code>```

HTML code:

```<code><img src="pic1.jpg" ng-click="myFunction()" alt="" width="250" height="250">
</code>```

You should not use jQuery on the top of the AngularJS, because AngularJS digest cycle wont run if we do any angular DOM manipulation or scope variable manipulation using JQuery.

As you migrate you jQuery component to AngularJS you need to follow below things:

You need first search angular-ui-bootstrap site because they had covered most of the UI component which has already converted to angular. I'm sure you will not found every plugin Angular version, at that you should wrap that plugin to directive. Which will give you controller over the DOM element where ever directive has placed.(Example here for Datepicker using directive)

Don't try to bind event from outside angular context that will create a digest cycle, that will leads to affect in binding updation on UI.

Ensure while making any ajax call that should be using $http rather than using $.ajax

There are many places you can find in jquery code that would be replace by ng-class directive, like if you are doing only adding & removing class, or showing some element on basis of any condtion, so that sort of jquery code can be replace by use ng-class directive

Look for the places where you are only removing a DOM or adding DOM that could be easily replaced by the the ng-if directive, or only show hide of element can be done by using either ng-show/ng-hide

Also find such a part in UI in which you are creating same DOM using for loop that can be convert to angular native directive ng-repeat

If you have any case where you wanted to show and hide multiple element, so that part of code would be implemented using ng-switch directive

(Sorry for adding this here as i do not have enough reputation to comment on your post)
Hello, I just read your comment there as you want to use jQuery viewbox in your code. My suggestion would be to use Angular UI-bootstrap Modal (click here). I have used Modal in many of my projects and it works great! I hope this helps

Title: How to add some jquery in SPA?

Body:
I'm using SPA with Angular and trying to use some jquery in my page after rendering the a particular page.
But the problem is that the jquery code doesn't work and no errors on the console either.

Hope you can help me out, here is my code:

app.js:

var app = angular.module('app', ['ngRoute', 'angularCSS']);

app.config(function($routeProvider){

    $routeProvider

    .when('/', {
        templateUrl: 'pages/main.html',
        controller: 'mainController',
        css: 'styles/main.css'
    })

    .when('/second', {
        templateUrl: 'pages/second.html',
        controller: 'secondController',
        css: ['styles/second.css', 'styles/second_2.css']
    });
});

app.controller('mainController', ['$scope', function($scope){

}]);

app.controller('secondController', ['$scope', function($scope){

}]);

the main page, index.html:

<!DOCTYPE html>

        <title>Untitled Document</title>
        <meta charset="UTF-8">
        <meta name="description" content="">
        <meta name="keywords" content="">
        <link rel="stylesheet" href="styles/viewbox.css">

Main

Second

            <ng-view></ng-view>

and here is the template, second.html:

Hello, this is Second Page

Body:
Here, I would agree with @War10ck that you should stick to AngularJS to avoid complexity in future. You need to put that function into controller like this:

app.controller('mainController', ['$scope','$window', function($scope, $window){

$scope.myFunction = function(){
window.alert("my img");
};

}]);

HTML code:

<img src="pic1.jpg" ng-click="myFunction()" alt="" width="250" height="250">

You should not use jQuery on the top of the AngularJS, because AngularJS digest cycle wont run if we do any angular DOM manipulation or scope variable manipulation using JQuery.

As you migrate you jQuery component to AngularJS you need to follow below things:

You need first search angular-ui-bootstrap site because they had covered most of the UI component which has already converted to angular. I'm sure you will not found every plugin Angular version, at that you should wrap that plugin to directive. Which will give you controller over the DOM element where ever directive has placed.(Example here for Datepicker using directive)

Don't try to bind event from outside angular context that will create a digest cycle, that will leads to affect in binding updation on UI.

Ensure while making any ajax call that should be using $http rather than using $.ajax

There are many places you can find in jquery code that would be replace by ng-class directive, like if you are doing only adding & removing class, or showing some element on basis of any condtion, so that sort of jquery code can be replace by use ng-class directive

Look for the places where you are only removing a DOM or adding DOM that could be easily replaced by the the ng-if directive, or only show hide of element can be done by using either ng-show/ng-hide

Also find such a part in UI in which you are creating same DOM using for loop that can be convert to angular native directive ng-repeat

If you have any case where you wanted to show and hide multiple element, so that part of code would be implemented using ng-switch directive

(Sorry for adding this here as i do not have enough reputation to comment on your post)
Hello, I just read your comment there as you want to use jQuery viewbox in your code. My suggestion would be to use Angular UI-bootstrap Modal (click here). I have used Modal in many of my projects and it works great! I hope this helps


问:
constructor initialization function member instantation
MCVE

```<code>#include <map>
class A{
public:
    A(int){

    }
};

class B : public A{
public:
    B()
     : A(filter()){}
    int filter(){
        std::map<int,int> aStuff;
        //new(&m_aStuff)std::map<int,int>;
        m_aStuff = aStuff;
        return 0;
    }
private:
    std::map<int,int> m_aStuff;
};

int main(){
    B b;
    return 0;
}
</code>```

This fails at compile time because m_aStuff is not initialized.
Using answer I added

```<code>new(&m_aStuff)std::map<int,int>;
</code>```

If you uncomment that line it runs at compile time but m_aStuff gets re-initialized anyway when you leave the filter class.

答:
I would strongly recommend you to reconsider the design, but here is my solution:

```<code>class A {
public:
  A(int) {}
};

class B : public A {
public:
  struct Dirty {
    std::map<int, int> map;
  };

  B(Dirty dirt = Dirty()) : A(filter(dirt)), m_aStuff(std::move(dirt.map)) {}
  int filter(Dirty& dirt) {
    std::map<int, int> aStuff;
    //new(&m_aStuff)std::map<int,int>;
    dirt.map = aStuff;
    return 0;
  }

private:
  std::map<int, int> m_aStuff;
};

int main() {
  B b;
  return 0;
}
</code>```

Nicer solution:

```<code>class B : public A {
public:
  B() : B(filter()) {}

private:
  B(std::tuple<int, std::map<int, int>> t)
    : A(std::get<0>(t)), m_aStuff(std::move(std::get<1>(t))) {}

  static std::tuple<int, std::map<int, int>> filter() {
    std::map<int, int> aStuff;
    //new(&m_aStuff)std::map<int,int>;
    return make_tuple(0, aStuff);
  }

  std::map<int, int> m_aStuff;
};
</code>```

Body:
MCVE

#include <map>
class A{
public:
    A(int){

    }
};

class B : public A{
public:
    B()
     : A(filter()){}
    int filter(){
        std::map<int,int> aStuff;
        //new(&m_aStuff)std::map<int,int>;
        m_aStuff = aStuff;
        return 0;
    }
private:
    std::map<int,int> m_aStuff;
};

int main(){
    B b;
    return 0;
}

This fails at compile time because m_aStuff is not initialized.
Using answer I added

new(&m_aStuff)std::map<int,int>;

If you uncomment that line it runs at compile time but m_aStuff gets re-initialized anyway when you leave the filter class.

Body:
I would strongly recommend you to reconsider the design, but here is my solution:

class A {
public:
  A(int) {}
};

class B : public A {
public:
  struct Dirty {
    std::map<int, int> map;
  };

  B(Dirty dirt = Dirty()) : A(filter(dirt)), m_aStuff(std::move(dirt.map)) {}
  int filter(Dirty& dirt) {
    std::map<int, int> aStuff;
    //new(&m_aStuff)std::map<int,int>;
    dirt.map = aStuff;
    return 0;
  }

private:
  std::map<int, int> m_aStuff;
};

int main() {
  B b;
  return 0;
}

Nicer solution:

class B : public A {
public:
  B() : B(filter()) {}

private:
  B(std::tuple<int, std::map<int, int>> t)
    : A(std::get<0>(t)), m_aStuff(std::move(std::get<1>(t))) {}

  static std::tuple<int, std::map<int, int>> filter() {
    std::map<int, int> aStuff;
    //new(&m_aStuff)std::map<int,int>;
    return make_tuple(0, aStuff);
  }

  std::map<int, int> m_aStuff;
};


问:
Using own React npm component - appropriate loader issues
I have made a component in my React app that I would like to publish to NPM. It's consists of just one file index.js

```<code>import React from 'react'
import PropTypes from 'prop-types';

export default class Test extends React.Component {
    //I seem to be getting a specific issue with the lines below
    //Do I need a special loader for these?
    static displayName = 'Test'
    static defaultProps = {
      live: true,
    }
}
</code>```

Originally the component was in a components directory of my main app and I include it using:

```<code>import Test from './components/Test'
</code>```

Since then I have created a new folder (not part of my main app) and added a package.json file and the index.js file. I have also published it to NPM which worked fine but when I try to use it after installing...

```<code>npm i -S package-name
import Test from 'package-name'
</code>```

I get an error: You may need an appropriate loader to handle this file type...

My package.json file doesn't have any dependencies or devDependencies at the moment. Do I need to do something with Webpack and Babel?

答:
Do I need to do something with Webpack and Babel?

Most likely. If you are using ES6 syntax in package-name then babel needs to transcode that library as well. When I have encountered that error this has always been the case. I suggest updating your Webpack / Babel configuration to include that library.

Body:
I have made a component in my React app that I would like to publish to NPM. It's consists of just one file index.js

import React from 'react'
import PropTypes from 'prop-types';

export default class Test extends React.Component {
    //I seem to be getting a specific issue with the lines below
    //Do I need a special loader for these?
    static displayName = 'Test'
    static defaultProps = {
      live: true,
    }
}

Originally the component was in a components directory of my main app and I include it using:

import Test from './components/Test'

Since then I have created a new folder (not part of my main app) and added a package.json file and the index.js file. I have also published it to NPM which worked fine but when I try to use it after installing...

npm i -S package-name
import Test from 'package-name'

I get an error: You may need an appropriate loader to handle this file type...

My package.json file doesn't have any dependencies or devDependencies at the moment. Do I need to do something with Webpack and Babel?


问:
EF Core Add a Related Entity (generic repository)
I have the an EF Core Db with the following models and one to many relationship

```<code>public class AttributeType
{
    public int AttributeTypeId { get; set; }
    public string Name { get; set; }

    public List<Attribute> AttributeList { get; set; }
}

public class Attribute
{
    public int AttributeId { get; set; }
    public string Name { get; set; }

    public int AttributeTypeId { get; set; }
    public AttributeType AttributeType { get; set; }
}
</code>```

If I'll try to add an attribute in this way it works:

```<code>using (var db = new SampleDbContext())
            {
                var attributeType = db.AttributeTypes.FirstOrDefault();

                Attribute attribute = new Attribute
                {
                    Name = "bbb",
                    AttributeTypeId = attributeType.AttributeTypeId,
                    AttributeType = attributeType
                };
                var item = db.Attributes.Add(attribute);
                db.SaveChanges();
            }
</code>```

(in the real the attributeType will come from a combobox and the name from a textbox, but now let's jus keep the code simple)

but when I try to use a generic method, like the following code, doesn't work

```<code>     AttributeType attributeType;

                using (var db = new SampleDbContext())
                {
                    attributeType = db.AttributeTypes.FirstOrDefault();
                }

                Attribute attribute = new Attribute
                {
                    Name = "eee",
                    AttributeType = attributeType,
                    AttributeTypeId = attributeType.AttributeTypeId
                };

                DbService.Insert(attribute);

 public static bool Insert<T>(T item) where T : class
        {
            try
            {
                using (var db = new SampleDbContext())
                {
                    db.Add(item);
                    db.SaveChanges();
                }
                return true;
            }
            catch (Exception exception)
            {
                Debug.WriteLine($"DbService Insert Exception: {exception}");
                return false;
            }
</code>```

and I get the following exception

Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in Microsoft.EntityFrameworkCore.dll
  DbService Insert Exception: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.Data.Sqlite.SqliteException: SQLite Error 19: 'UNIQUE constraint failed: AttributeTypes.AttributeTypeId'.
  at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db)
  at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
  at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary2 parameterValues, Boolean closeConnection)
  at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
  at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
  --- End of inner exception stack trace ---
  at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
  at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 parameters)
  at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave)
  at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
  at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
  at UwpSamples.Services.DbService.Insert[T](T item)

but if I don't pass the AttributeType or I set it to null, like the following code, it works:

```<code>AttributeType attributeType;

        using (var db = new SampleDbContext())
        {
            attributeType = db.AttributeTypes.FirstOrDefault();
        }

        Attribute attribute = new Attribute
        {
            Name = "ddd",
            AttributeType = null,
            AttributeTypeId = attributeType.AttributeTypeId
        };

        DbService.Insert(attribute);
</code>```

-

```<code>AttributeType attributeType;

        using (var db = new SampleDbContext())
        {
            attributeType = db.AttributeTypes.FirstOrDefault();
        }

        Attribute attribute = new Attribute
        {
            Name = "ddd",
            AttributeTypeId = attributeType.AttributeTypeId
        };

        DbService.Insert(attribute);
</code>```

Thanks

答:
You are instantiating two separate contexts.  One where you retrieve the AttributeType, and the second context inside the repository performing the insert will traverse the entity and believes the AttributeType is new and attempts to insert it. I recommend using a single Context per request(assuming this is behind a web request).  There are workarounds that would involve flagging the entity as unchanged but you'd have to repeat the workaround each time and it'd be very specific to each model.

Usually you either use a Container or IoC framework to retrieve a Context per request, or you'd pass the context in the constructor of the repository.  This way you can make multiple calls across different repositories and change tracking will work between the calls.  It also simplifies scenarios where you have a transaction scope open across calls to different repositories.

Body:
I have the an EF Core Db with the following models and one to many relationship

public class AttributeType
{
    public int AttributeTypeId { get; set; }
    public string Name { get; set; }

    public List<Attribute> AttributeList { get; set; }
}

public class Attribute
{
    public int AttributeId { get; set; }
    public string Name { get; set; }

    public int AttributeTypeId { get; set; }
    public AttributeType AttributeType { get; set; }
}

If I'll try to add an attribute in this way it works:

using (var db = new SampleDbContext())
            {
                var attributeType = db.AttributeTypes.FirstOrDefault();

                Attribute attribute = new Attribute
                {
                    Name = "bbb",
                    AttributeTypeId = attributeType.AttributeTypeId,
                    AttributeType = attributeType
                };
                var item = db.Attributes.Add(attribute);
                db.SaveChanges();
            }

(in the real the attributeType will come from a combobox and the name from a textbox, but now let's jus keep the code simple)

but when I try to use a generic method, like the following code, doesn't work

     AttributeType attributeType;

                using (var db = new SampleDbContext())
                {
                    attributeType = db.AttributeTypes.FirstOrDefault();
                }

                Attribute attribute = new Attribute
                {
                    Name = "eee",
                    AttributeType = attributeType,
                    AttributeTypeId = attributeType.AttributeTypeId
                };

                DbService.Insert(attribute);

 public static bool Insert<T>(T item) where T : class
        {
            try
            {
                using (var db = new SampleDbContext())
                {
                    db.Add(item);
                    db.SaveChanges();
                }
                return true;
            }
            catch (Exception exception)
            {
                Debug.WriteLine($"DbService Insert Exception: {exception}");
                return false;
            }

and I get the following exception

Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in Microsoft.EntityFrameworkCore.dll
  DbService Insert Exception: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.Data.Sqlite.SqliteException: SQLite Error 19: 'UNIQUE constraint failed: AttributeTypes.AttributeTypeId'.
  at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db)
  at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
  at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary2 parameterValues, Boolean closeConnection)
  at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
  at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
  --- End of inner exception stack trace ---
  at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
  at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 parameters)
  at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave)
  at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
  at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
  at UwpSamples.Services.DbService.Insert[T](T item)

but if I don't pass the AttributeType or I set it to null, like the following code, it works:

AttributeType attributeType;

        using (var db = new SampleDbContext())
        {
            attributeType = db.AttributeTypes.FirstOrDefault();
        }

        Attribute attribute = new Attribute
        {
            Name = "ddd",
            AttributeType = null,
            AttributeTypeId = attributeType.AttributeTypeId
        };

        DbService.Insert(attribute);

-

AttributeType attributeType;

        using (var db = new SampleDbContext())
        {
            attributeType = db.AttributeTypes.FirstOrDefault();
        }

        Attribute attribute = new Attribute
        {
            Name = "ddd",
            AttributeTypeId = attributeType.AttributeTypeId
        };

        DbService.Insert(attribute);

Thanks


问:
Django forms - rendering form and redirecting
I am trying to create an 'add user' feature which will simply add the user you've selected from a dropdown as your connection. I am using ModelChoiceField from Django Forms so that I may get the existing users from my User model in the dropdown.

forms.py

```<code>from django import forms
from django.contrib.auth.models import User

class NetworkForm(forms.Form):
    user_id = forms.ModelChoiceField(queryset=User.objects.all(), label='',
                                       widget=forms.Select(attrs={'class': 'all_users'}))
</code>```

views.py

```<code>@login_required
def index(request):
    user_list = User.objects.exclude(username=request.user)
    return render(request, 'chat/index.html', {'user_list': user_list})
</code>```

For now I am just printing the form to see output

```<code>@login_required
def add_user(request):
    form = NetworkForm()
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            print form
            return redirect(request.META['HTTP_REFERER'])

    errors = form.errors or None

    return render(request, 'chat/index.html', {
        'form': form,
        'errors': errors,
    })
</code>```

index.html

<form action="{% url 'chat:add_user' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>

```
</div>
</div>
</p>

<p><strong>urls.py</strong></p>

```urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^add_user/$', views.add_user, name='add_user'),]
```

<p>The way it is being rendered currently is: I have my main index page where I don't see any dropdown, i.e.,
<img src="https://i.stack.imgur.com/Idroe.png" alt="enter image description here"></p>

<p>When I click on the submit button, it moves me to index/add_user, where I get a dropdown with user (with a warning "this field is required) and a submit button again.
<img src="https://i.stack.imgur.com/iXJRp.png" alt="enter image description here"></p>

<p>Finally, when I choose a user in this new page and hit submit, finally the form is printed, which I want ultimately.<img src="https://i.stack.imgur.com/Wtjf4.png" alt="enter image description here"></p>

<p><strong><em>What I would want it, have the complete form with dropdown in the index page itself and remain there when I submit the form.</em></strong> I will then hook that to show user the users they have added beneath that form itself ('print' is just for debugging purpose - not a good way I've heard though).
I understand the post request will have to go to add_user page and I can redirect back from that. I have tried various alternatives for the past 6 hours, nothing works yet. Apologies for a long one, giving out information as much as possible. Thanks very much guys. You are awesome. </p>

<p><strong>Edit</strong>
Have been now rendering the form in index page (suggestion from @fazil-zaid ), but the issue remains as in only 'submit' button appears on index initially, unless when I hit submit after which the dropdown and submit appears. Again, on clicking the second time, the form is submitted. </p>

<p><strong>Edit-2</strong>
I am thinking that:</p>

```<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
{{ form.as_p }}
    <button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
```

<p>this might be where the problem is, as per current logic unless user takes form's action, i.e., clicks the button {{ form.as_p }} will not appear. Then I tried:</p>

```{{ form.as_p }}
<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
    <button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
```

Doesn't work still. POST request doesn't send any data (understandably so).

答:
If you want the form to be in the index page, then you could include it in the index view itself.

```<code>def index(request):
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            #do what you wanna do
            #with the form data.
    else:
        form = NetworkForm()
    render(request, 'chat/index.html', { 'form': form})
</code>```

In the template,

```<code><div class="row">
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
</div>
</code>```

You are not rendering another template, but the same 'index.html'. Then, multiple view for that is just redundant. Index page could contain the form and render itself. From what I understand, there's no need of redirections.

There's no need of add_user view if you're showing the form in the index page itself.

For your issue, try changing the "class" attribute of the form fields, maybe something like this,

```<code>class NetworkForm(forms.Form):
    user_id = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))
</code>```

Body:
I am trying to create an 'add user' feature which will simply add the user you've selected from a dropdown as your connection. I am using ModelChoiceField from Django Forms so that I may get the existing users from my User model in the dropdown.

forms.py

from django import forms
from django.contrib.auth.models import User

class NetworkForm(forms.Form):
    user_id = forms.ModelChoiceField(queryset=User.objects.all(), label='',
                                       widget=forms.Select(attrs={'class': 'all_users'}))

views.py

@login_required
def index(request):
    user_list = User.objects.exclude(username=request.user)
    return render(request, 'chat/index.html', {'user_list': user_list})

For now I am just printing the form to see output

@login_required
def add_user(request):
    form = NetworkForm()
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            print form
            return redirect(request.META['HTTP_REFERER'])

    errors = form.errors or None

    return render(request, 'chat/index.html', {
        'form': form,
        'errors': errors,
    })

index.html

<form action="{% url 'chat:add_user' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>

urls.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^add_user/$', views.add_user, name='add_user'),]

The way it is being rendered currently is: I have my main index page where I don't see any dropdown, i.e.,

When I click on the submit button, it moves me to index/add_user, where I get a dropdown with user (with a warning "this field is required) and a submit button again.

Finally, when I choose a user in this new page and hit submit, finally the form is printed, which I want ultimately.

What I would want it, have the complete form with dropdown in the index page itself and remain there when I submit the form. I will then hook that to show user the users they have added beneath that form itself ('print' is just for debugging purpose - not a good way I've heard though).
I understand the post request will have to go to add_user page and I can redirect back from that. I have tried various alternatives for the past 6 hours, nothing works yet. Apologies for a long one, giving out information as much as possible. Thanks very much guys. You are awesome.

Edit
Have been now rendering the form in index page (suggestion from @fazil-zaid ), but the issue remains as in only 'submit' button appears on index initially, unless when I hit submit after which the dropdown and submit appears. Again, on clicking the second time, the form is submitted.

Edit-2
I am thinking that:

<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
{{ form.as_p }}
    <button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>

this might be where the problem is, as per current logic unless user takes form's action, i.e., clicks the button {{ form.as_p }} will not appear. Then I tried:

{{ form.as_p }}
<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
    <button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>

Doesn't work still. POST request doesn't send any data (understandably so).

Body:
If you want the form to be in the index page, then you could include it in the index view itself.

def index(request):
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            #do what you wanna do
            #with the form data.
    else:
        form = NetworkForm()
    render(request, 'chat/index.html', { 'form': form})

In the template,

<div class="row">
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
</div>

You are not rendering another template, but the same 'index.html'. Then, multiple view for that is just redundant. Index page could contain the form and render itself. From what I understand, there's no need of redirections.

There's no need of add_user view if you're showing the form in the index page itself.

For your issue, try changing the "class" attribute of the form fields, maybe something like this,

class NetworkForm(forms.Form):
    user_id = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))


问:
CKEditor contextmenu positions incorrectly in modal
Made a plugin that utilizes CKEditor contextmenu. When used inside a bootstrap modal, the first right-click results in an incorrect positioning of the menu. Subsequent attempts work fine.

Tough to debug:

CKEditor exists in one iframe and the contextmenu exists in its own separate iframe that gets generated at first use. That new iframe appears completely outside the modal, with a div wrapper, one level in from the outermost  tag on the page.

normal CKEditor iframe which exists inside the modal looks like this:

```<code><iframe src="" frameborder="0"
    class="cke_wysiwyg_frame cke_reset"
    title="Rich Text Editor, ControlLabel" tabindex="0" ...
</code>```

contextmenu wrapper looks like this:

```<code><div lang="en" id="cke_28" dir="ltr" class="cke cke_reset_all ...
    <iframe id="cke_28_frame" class="cke_panel_frame" ...
</code>```

The contextmenu wrapper is getting inline position styles calculated against the  tag. It gets it wrong the first time you right-click to bring up the contextmenu.

```<code>z-index: 10001;
position: absolute;
top: 177px;                // wrong. too small.
left: 932.5px;
opacity: 1;
width: 130px;
height: 203px
</code>```

Second time is correct. Click away, then right-click to bring the contextmenu back and you get a proper rendering:

```<code>z-index: 10001;
position: absolute;
top: 487px;       // correct. proper distance
left: 719.5px;
opacity: 1;
height: 203px;
width: 130px;
</code>```

What gives? This has been a herculean debug effort since I've had to creep into iframes, one of which is dynamically generated (gotta use javascript tricks beyond what's offered by Chrome devtools).

There's an open() method in the contextmenu source code here, which starts like this:

```<code>open: function( offsetParent, corner, offsetX, offsetY ) {
                this.editor.focus();
                // ...
</code>```

Having spent so much time already, before I start stepping through a mountain of code, I'm wondering if I'm even on the right track here. Any help is greatly appreciated.

答:
Fix was an incredibly simple bootstrap css override.

```<code>body.modal-open {
    position: fixed;
}
</code>```

Background scrolling was confusing the contextmenu coordinate calculations. It is my suspicion that by default a bootstrap modal will not prevent the background from being scrolled programmatically in all cases.

Bootstrap attaches the .modal-open class onto the  tag when there's an open modal.

Body:
Made a plugin that utilizes CKEditor contextmenu. When used inside a bootstrap modal, the first right-click results in an incorrect positioning of the menu. Subsequent attempts work fine.

Tough to debug:

CKEditor exists in one iframe and the contextmenu exists in its own separate iframe that gets generated at first use. That new iframe appears completely outside the modal, with a div wrapper, one level in from the outermost  tag on the page.

normal CKEditor iframe which exists inside the modal looks like this:

<iframe src="" frameborder="0"
    class="cke_wysiwyg_frame cke_reset"
    title="Rich Text Editor, ControlLabel" tabindex="0" ...

contextmenu wrapper looks like this:

<div lang="en" id="cke_28" dir="ltr" class="cke cke_reset_all ...
    <iframe id="cke_28_frame" class="cke_panel_frame" ...

The contextmenu wrapper is getting inline position styles calculated against the  tag. It gets it wrong the first time you right-click to bring up the contextmenu.

z-index: 10001;
position: absolute;
top: 177px;                // wrong. too small.
left: 932.5px;
opacity: 1;
width: 130px;
height: 203px

Second time is correct. Click away, then right-click to bring the contextmenu back and you get a proper rendering:

z-index: 10001;
position: absolute;
top: 487px;       // correct. proper distance
left: 719.5px;
opacity: 1;
height: 203px;
width: 130px;

What gives? This has been a herculean debug effort since I've had to creep into iframes, one of which is dynamically generated (gotta use javascript tricks beyond what's offered by Chrome devtools).

There's an open() method in the contextmenu source code here, which starts like this:

open: function( offsetParent, corner, offsetX, offsetY ) {
                this.editor.focus();
                // ...

Having spent so much time already, before I start stepping through a mountain of code, I'm wondering if I'm even on the right track here. Any help is greatly appreciated.

Body:
Fix was an incredibly simple bootstrap css override.

body.modal-open {
    position: fixed;
}

Background scrolling was confusing the contextmenu coordinate calculations. It is my suspicion that by default a bootstrap modal will not prevent the background from being scrolled programmatically in all cases.

Bootstrap attaches the .modal-open class onto the <body> tag when there's an open modal.


问:
How can I get the exit code or exit status after finish a robotium test on the command line
Now I wrote a batch script to run the command like:

```<code>adb -s emulator-5556 shell am instrument -e class com.example.test.locationListTest -w com.example.test/android.test.InstrumentationTestRun
</code>```

Then at the console I get results like FAILURE!!! Tests run: 5 fail:4 or OK.

I use if errorlevel 0 to determine the upper command, but it gives me 0 no matter the upper command gives me,  OK or FAILURE.

I need to do this in batch script like this:

```<code>if(adb -s emulator-5556 shell ..... test.InstrumentationTestRun == SUCCESS )
do (.........)
else (.........)
</code>```

答:
What about something simple, like:</p>

```<code>adb -s emulator-5556 shell am instrument -e class com.example.test.locationListTest -w com.example.test/android.test.InstrumentationTestRun | grep "Failures"
if [ $? -eq 0 ]; then
    echo "## TEST FAILED ##"
    exit 1
fi
</code>```

Body:
Now I wrote a batch script to run the command like:

adb -s emulator-5556 shell am instrument -e class com.example.test.locationListTest -w com.example.test/android.test.InstrumentationTestRun

Then at the console I get results like FAILURE!!! Tests run: 5 fail:4 or OK.

I use if errorlevel 0 to determine the upper command, but it gives me 0 no matter the upper command gives me,  OK or FAILURE.

I need to do this in batch script like this:

if(adb -s emulator-5556 shell ..... test.InstrumentationTestRun == SUCCESS )
do (.........)
else (.........)

Body:
What about something simple, like:

adb -s emulator-5556 shell am instrument -e class com.example.test.locationListTest -w com.example.test/android.test.InstrumentationTestRun | grep "Failures"
if [ $? -eq 0 ]; then
    echo "## TEST FAILED ##"
    exit 1
fi


问:
Python Plotting a shapefile on a basemap
I am using python 3.6 to plot a shapefile containing large watersheds in the U.S. The problem that I am running into is that this shapefile has many components, such as a .dbf file, a .prj file... and others. I am not sure if I have to read all the files in individually and then plot or if there is one command that will allow me to read them all at once and then plot.

Here is my code so far:

```<code>from mpl_toolkits.basemap import Basemap

import matplotlib.pyplot as plt

mydbf =('filename.dbf')
myprj =('filename.prj')
myqpj =('filename.qpj')
myshp =('filename.shp')
myshx =('filename.shx')

map= Basemap(projection='cyl',
            lon_0=180,
            lat_0=0,
            resolution='l')
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#ddaa66',lake_color='aqua')
map.drawcoastlines()

map.readshapefile(mydbf,myprj,myqpj,myshp,myshx,'Watersheds')
plt.show()
</code>```

The error message I am getting when I run this code is:
OSError: cannot locate filename.dbf.shp

答:
In the basemap tutorial on readthedocs it clearly says about the readshapefile function

The first parameter shapefile name must go without the shp extension. The library assumes that all shp, sbf and shx files will exist with this given name

Your call should therefore be

```<code>map.readshapefile("filename",'Watersheds')
</code>```

Body:
I am using python 3.6 to plot a shapefile containing large watersheds in the U.S. The problem that I am running into is that this shapefile has many components, such as a .dbf file, a .prj file... and others. I am not sure if I have to read all the files in individually and then plot or if there is one command that will allow me to read them all at once and then plot.

Here is my code so far:

from mpl_toolkits.basemap import Basemap

import matplotlib.pyplot as plt

mydbf =('filename.dbf')
myprj =('filename.prj')
myqpj =('filename.qpj')
myshp =('filename.shp')
myshx =('filename.shx')

map= Basemap(projection='cyl',
            lon_0=180,
            lat_0=0,
            resolution='l')
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#ddaa66',lake_color='aqua')
map.drawcoastlines()

map.readshapefile(mydbf,myprj,myqpj,myshp,myshx,'Watersheds')
plt.show()

The error message I am getting when I run this code is:
OSError: cannot locate filename.dbf.shp

Body:
In the basemap tutorial on readthedocs it clearly says about the readshapefile function

The first parameter shapefile name must go without the shp extension. The library assumes that all shp, sbf and shx files will exist with this given name

Your call should therefore be

map.readshapefile("filename",'Watersheds')


答:
Try this:

```<code>import subprocess
import time

tmp=subprocess.call('clear', shell=True) # 'cls' in windows
keyword = input(" Please enter the word you want the person to guess")
lives = int(input("How many lives would you like to have?"))
print ("There are ", len(keyword), "letters in the word")

time.sleep(2)
</code>```

Save the code in a python file. Then execute it from shell.

Title: Clearing the text from the python shell

Body:
OK, so I am currently messing around coding hangman in python and was wondering if I can clear what it says in the python shell as I don't just wan't the person to read the word.

import time
keyword = input(" Please enter the word you want the person to guess")
lives = int(input("How many lives would you like to have?"))
print ("There are ", len(keyword), "letters in the word")

time.sleep(2)

guess = input("please enter your guess")

I would like to remove all the text  in the shell.

Body:
Try this:

import subprocess
import time

tmp=subprocess.call('clear', shell=True) # 'cls' in windows
keyword = input(" Please enter the word you want the person to guess")
lives = int(input("How many lives would you like to have?"))
print ("There are ", len(keyword), "letters in the word")

time.sleep(2)

Save the code in a python file. Then execute it from shell.


问:
How to middle all text using "inline-block" with CSS
I am using span elements and would display in a line by inline-block. I tried to make all text(s) Test 1, Test 2... Test 5 to middle of each square with margin-top or padding-top, but it didn't work.

Besides that, whenever the height of the square has been changed, the text is still stay at the middle of its square. Please let me know how to do it.

Fiddle link: http://jsfiddle.net/xVnQ6/150/

HTML:

```<code><div id="legend">
  <span class="legendTest1"></span><span class="legendText">Test 1</span>
  <span class="legendTest2"></span><span class="legendText">Test 2</span>
  <span class="legendTest3"></span><span class="legendText">Test 3</span>
  <span class="legendTest4"></span><span class="legendText">Test 4</span>
  <span class="legendTest5"></span><span class="legendText">Test 5</span>
</div>
</code>```

CSS:

```<code>.legendTest1 {
  background-color: #DCDEE0;
}

.legendTest2 {
  background-color: #FF4739;
}

.legendTest3 {
  background-color: #FFCA4C;
}

.legendTest4 {
  background-color: #00AEEF;
}

.legendTest5 {
  background-color: #27AF8F;
}

#legend {
  float: left;
  margin-top: 20px;
}

#legend span {
  display: inline-block;
}

#legend .legendText {
  margin-left: 5px;
}

.legendTest1,
.legendTest2,
.legendTest3,
.legendTest4,
.legendTest5 {
  width: 80px;
  height: 80px;
  margin: 0 0 0 10px;
}
</code>```

答:
.legendTest1 {
  background-color: #DCDEE0;
}

.legendTest2 {
  background-color: #FF4739;
}

.legendTest3 {
  background-color: #FFCA4C;
}

.legendTest4 {
  background-color: #00AEEF;
}

.legendTest5 {
  background-color: #27AF8F;
}

#legend {
  float: left;
  margin-top: 20px;
}

#legend span {
  display: inline-block;
  vertical-align:middle;
}

#legend .legendText {
  margin-left: 5px;
}

.legendTest1,
.legendTest2,
.legendTest3,
.legendTest4,
.legendTest5 {
  width: 80px;
  height: 80px;
  margin: 0 0 0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="legend">
  <span class="legendTest1"></span><span class="legendText">Test 1</span>
  <span class="legendTest2"></span><span class="legendText">Test 2</span>
  <span class="legendTest3"></span><span class="legendText">Test 3</span>
  <span class="legendTest4"></span><span class="legendText">Test 4</span>
  <span class="legendTest5"></span><span class="legendText">Test 5</span>
</div></code>```

Add vertical-align:middle; to your span.

Here is working Demo

Hope this helps.

Body:
I am using span elements and would display in a line by inline-block. I tried to make all text(s) Test 1, Test 2... Test 5 to middle of each square with margin-top or padding-top, but it didn't work.

Besides that, whenever the height of the square has been changed, the text is still stay at the middle of its square. Please let me know how to do it.

Fiddle link: http://jsfiddle.net/xVnQ6/150/

HTML:

  Test 1
  Test 2
  Test 3
  Test 4
  Test 5

CSS:

.legendTest1 {
  background-color: #DCDEE0;
}

.legendTest2 {
  background-color: #FF4739;
}

.legendTest3 {
  background-color: #FFCA4C;
}

.legendTest4 {
  background-color: #00AEEF;
}

.legendTest5 {
  background-color: #27AF8F;
}

#legend {
  float: left;
  margin-top: 20px;
}

#legend span {
  display: inline-block;
}

#legend .legendText {
  margin-left: 5px;
}

.legendTest1,
.legendTest2,
.legendTest3,
.legendTest4,
.legendTest5 {
  width: 80px;
  height: 80px;
  margin: 0 0 0 10px;
}

Body:
.legendTest1 {
  background-color: #DCDEE0;
}

.legendTest2 {
  background-color: #FF4739;
}

.legendTest3 {
  background-color: #FFCA4C;
}

.legendTest4 {
  background-color: #00AEEF;
}

.legendTest5 {
  background-color: #27AF8F;
}

#legend {
  float: left;
  margin-top: 20px;
}

#legend span {
  display: inline-block;
  vertical-align:middle;
}

#legend .legendText {
  margin-left: 5px;
}

.legendTest1,
.legendTest2,
.legendTest3,
.legendTest4,
.legendTest5 {
  width: 80px;
  height: 80px;
  margin: 0 0 0 10px;
}

<div id="legend">
  <span class="legendTest1"></span><span class="legendText">Test 1</span>
  <span class="legendTest2"></span><span class="legendText">Test 2</span>
  <span class="legendTest3"></span><span class="legendText">Test 3</span>
  <span class="legendTest4"></span><span class="legendText">Test 4</span>
  <span class="legendTest5"></span><span class="legendText">Test 5</span>
</div>

Add vertical-align:middle; to your span.

Here is working Demo

Hope this helps.


问:
Copy all but one field with Lodash, without using Object.assign()
If I have an object like so:

```<code>const obj  = { A: 1, B: 2, C: 3, D: 4 };
</code>```

How can I copy all key/values except for C to a new object?

Underscore has the _.pick() functionality, but I am looking to do the opposite.

答:
You can do this with the ES object rest/spread proposal. Since it's a stage 4 proposal, and not supported by all browser, you might need to transpile the code using babel with the Object rest spread transform.

const obj  = { A: 1, B: 2, C: 3, D: 4 };

const { C, ...objWithoutC } = obj;

console.log(objWithoutC);```

Body:
If I have an object like so:

const obj  = { A: 1, B: 2, C: 3, D: 4 };

How can I copy all key/values except for C to a new object?

Underscore has the _.pick() functionality, but I am looking to do the opposite.


问:
In Ruby on Rails, what does "resource" mean?
I see the word resource in many different places like: resource Routing, resourceful controller, and resources: photos. What does resource actually mean?

One more question: What does RESTful route mean?

答:
That's a big question!

I'd start here to better understand what 'resource' or 'resources' does as it relates to routing: http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default

The short of it is that that it formalizes a set of actions (for a specific controller) invoked by URL/HTTP Verb pairs that are responsible for modifying the state of a given resource. Think of resources as nouns: Order, LineItem, Offer and think about what you might want to do with those nouns: typically create them, delete them, modify them, retrieve some set of them, etc. As such, resources are often (but certainly don't have to be) your core model objects and/or some composite representation of those core models.

Again - the Rails Guides summarize what resourceful routes Rails very succinctly in Section 2.1 of the above link: 'In Rails, a resourceful route provides a mapping between HTTP verbs and URLs and controller actions'

If you're unfamiliar with REST, Wikipedia has some decent - but not exhaustive - coverage on the architecture: http://en.wikipedia.org/wiki/Representational_State_Transfer.


问:
Vue.js - Element UI - Form validation regexp
I'd like to validate a form using vue-js 2.3 and element-ui

Apparently, they use async-validator to validate the form.  The documentation is here.

Example

https://jsfiddle.net/skd3nyqh/

Problem

Uncaught Error: Unknown rule type  D*([2-9]d{2})(D*)([2-9]d{2})(D*)(d{4})D*

I do not know how to validate a field with regexp. I find the documentation not explicit enough on that topic.

答:
From the documentation.

Pattern

The pattern rule property indicates a regular expression that the
  value must match to pass validation.

Use

```<code>{required: true, pattern:/\D*([2-9]\d{2})(\D*)([2-9]\d{2})(\D*)(\d{4})\D*/, message: 'Please input phone', trigger: 'blur' }
</code>```

Updated fiddle.

Body:
From the documentation.

Pattern

The pattern rule property indicates a regular expression that the
  value must match to pass validation.

Use

{required: true, pattern:/\D*([2-9]\d{2})(\D*)([2-9]\d{2})(\D*)(\d{4})\D*/, message: 'Please input phone', trigger: 'blur' }

Updated fiddle.