问:
Add random elements to an array (swift)
I have a VC with a tableView inside where i fill manually an array by multiple selecting of items from my tableView's rows. In this VC i have an array

```<code>var list : [QCategoryy] = [QCategoryy]()
list = NearbyPlaces.getCategories()
</code>```

where getCategories() is

```<code>static func getCategories() -> [QCategoryy] {
        let list:[QCategoryy] = [QCategoryy(name: "bar", image: UIImage(named: "bar_button.png")!), QCategoryy(name :"night_club", image: UIImage(named: "nightclub_button.png")!), QCategoryy(name: "movie_theater", image: UIImage(named: "cinema_button.png")!), QCategoryy(name: "restaurant", image: UIImage(named: "restaurant_button.png")!), QCategoryy(name: "gym", image: UIImage(named: "gym_button.png")!), QCategoryy(name: "spa", image: UIImage(named: "spa_button.png")!), QCategoryy(name: "museum", image: UIImage(named: "museum_button.png")!)]
        return list
    }
</code>```

these items (bar, gym, spa etc.) will fill my tableView cells and when i select them i'll create my array selectedCategories how you can see here:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == nearbySearchSegueIdentifier {
            let selectedCategories: [QCategoryy] = tableView.indexPathsForSelectedRows?.map({ (indexPath) -> QCategoryy in
                return list[indexPath.row] }) ?? []

            if let selectedRows = tableView.indexPathsForSelectedRows {

                if let vc : nextClass = segue.destination as? nextClass {

                vc.categories = selectedCategories

            }
        }
    }
}
</code>```

now i would like to know how can i fill this array (selectedCategories) without selecting the cells of the tableView but in random way by pressing a button, so i want to fill the array with random items of my var list : [QCategoryy] = [QCategoryy]() with a button tap, how can i do?

UPDATE

```<code>struct QCategoryy {
    var name: String
    var image: UIImage
    var isSelected = false

    init(name:String, image:UIImage) {
        self.name = name
        self.image = image

    }
}

extension QCategoryy: ExpressibleByStringLiteral {

    init(stringLiteral value: String) {
        self.name = value
        self.image = UIImage()

    }
    init(unicodeScalarLiteral value: String) {
        self.init(name: value, image: UIImage())
    }
    init(extendedGraphemeClusterLiteral value: String) {
        self.init(name: value, image: UIImage())
    }
}
</code>```

答:
The route you likely want to go is to "shuffle" the array of categories, and then take the first n number of elements from the array.

Say you have an array of numbers 1 through 10:

```<code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

and you want to get 6 random elements. If you simply did a Get Random Element type of call 6 times, you would very likely end up with duplicates.

So, if you perform a Shuffle on the array, your new array may look like this:

```<code>[7, 2, 9, 5, 3, 4, 1, 10, 8, 6]
</code>```

and you can get the first 6 elements - which will be random without duplicates.

The elements can be anything... I'm just showing numbers here for explanation.

Edit

For example... add this code to your project:

```<code>extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Iterator.Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}
</code>```

Then, in prepare for segue, you could do:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == nearbySearchSegueIdentifier {
            if let vc : nextClass = segue.destination as? nextClass {

                // use ALL QCategoryy objects, in random order
                vc.categories = NearbyPlaces.getCategories().shuffled()

                // or, use 4 random QCategoryy objects
                //vc.categories = NearbyPlaces.getCategories().shuffled()[0...3]

            }
        }
    }
}
</code>```

This shuffle extension, and others, can be found here: https://stackoverflow.com/a/24029847/6257435

Title: Add random elements to an array (swift)

Body:
I have a VC with a tableView inside where i fill manually an array by multiple selecting of items from my tableView's rows. In this VC i have an array

var list : [QCategoryy] = [QCategoryy]()
list = NearbyPlaces.getCategories()

where getCategories() is

static func getCategories() -> [QCategoryy] {
        let list:[QCategoryy] = [QCategoryy(name: "bar", image: UIImage(named: "bar_button.png")!), QCategoryy(name :"night_club", image: UIImage(named: "nightclub_button.png")!), QCategoryy(name: "movie_theater", image: UIImage(named: "cinema_button.png")!), QCategoryy(name: "restaurant", image: UIImage(named: "restaurant_button.png")!), QCategoryy(name: "gym", image: UIImage(named: "gym_button.png")!), QCategoryy(name: "spa", image: UIImage(named: "spa_button.png")!), QCategoryy(name: "museum", image: UIImage(named: "museum_button.png")!)]
        return list
    }

these items (bar, gym, spa etc.) will fill my tableView cells and when i select them i'll create my array selectedCategories how you can see here:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == nearbySearchSegueIdentifier {
            let selectedCategories: [QCategoryy] = tableView.indexPathsForSelectedRows?.map({ (indexPath) -> QCategoryy in
                return list[indexPath.row] }) ?? []

            if let selectedRows = tableView.indexPathsForSelectedRows {

                if let vc : nextClass = segue.destination as? nextClass {

                vc.categories = selectedCategories

            }
        }
    }
}

now i would like to know how can i fill this array (selectedCategories) without selecting the cells of the tableView but in random way by pressing a button, so i want to fill the array with random items of my var list : [QCategoryy] = [QCategoryy]() with a button tap, how can i do?

UPDATE

struct QCategoryy {
    var name: String
    var image: UIImage
    var isSelected = false

    init(name:String, image:UIImage) {
        self.name = name
        self.image = image

    }
}

extension QCategoryy: ExpressibleByStringLiteral {

    init(stringLiteral value: String) {
        self.name = value
        self.image = UIImage()

    }
    init(unicodeScalarLiteral value: String) {
        self.init(name: value, image: UIImage())
    }
    init(extendedGraphemeClusterLiteral value: String) {
        self.init(name: value, image: UIImage())
    }
}

Body:
The route you likely want to go is to "shuffle" the array of categories, and then take the first n number of elements from the array.

Say you have an array of numbers 1 through 10:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

and you want to get 6 random elements. If you simply did a Get Random Element type of call 6 times, you would very likely end up with duplicates.

So, if you perform a Shuffle on the array, your new array may look like this:

[7, 2, 9, 5, 3, 4, 1, 10, 8, 6]

and you can get the first 6 elements - which will be random without duplicates.

The elements can be anything... I'm just showing numbers here for explanation.

Edit

For example... add this code to your project:

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Iterator.Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}

Then, in prepare for segue, you could do:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == nearbySearchSegueIdentifier {
            if let vc : nextClass = segue.destination as? nextClass {

                // use ALL QCategoryy objects, in random order
                vc.categories = NearbyPlaces.getCategories().shuffled()

                // or, use 4 random QCategoryy objects
                //vc.categories = NearbyPlaces.getCategories().shuffled()[0...3]

            }
        }
    }
}

This shuffle extension, and others, can be found here: https://stackoverflow.com/a/24029847/6257435


来源: stackexchange

问:
I have two panel side by side in content page.when click on button on 1st panel 2nd panel fields are responding
this is my html code

```<code> <div id="page-wrapper" class="gray-bg dashbard-1">
     <div class="content-top">
      <%-- <div class="row"--%>
    <iframe src="http://www.gmail.com" style="width: 1350px; height:650px">
 </iframe>
  </div>
</div>
</code>```

when i load this page it is redirecting to gmail ste.
can tell me what is problem

答: Your whole page is filled with iframe and that iframe s loading gmail.com.</p>

ContentLicense: CC BY-SA 3.0

Body:
this is my html code

      <%--

when i load this page it is redirecting to gmail ste.
can tell me what is problem


问:
Export from HTML to PDF (C#)

Possible Duplicate:

  Convert HTML to PDF in .NET

In our applications we make html documents as reports and exports.
But now our customer wants a button that saves that document on their pc. The problem is that the document includes images.
You can create a word document with the following code:

```<code>private void WriteWordDoc(string docName)
{
    Response.Buffer = true;
    Response.ContentType = "application/msword";
    Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.doc", docName.Replace(" ", "_")));
    Response.Charset = "utf-8";
}
</code>```

But the problem is that the images are just links an thus not embedded in the word document.

Therefore I'm looking for an alternative
PDF seems to be a good alternative, does anyone know a good pdf writer for C#?
One that has some good references and has been tested properly?

答: I like DocRaptor.com for creating pdfs. It's a web app that works in any language, and it uses Prince XML, so the results are high quality. </p>

OwnerDisplayName: Sem Dendoncker

Title: Export from HTML to PDF (C#)

Body:
Possible Duplicate:

  Convert HTML to PDF in .NET

In our applications we make html documents as reports and exports.
But now our customer wants a button that saves that document on their pc. The problem is that the document includes images.
You can create a word document with the following code:

private void WriteWordDoc(string docName)
{
    Response.Buffer = true;
    Response.ContentType = "application/msword";
    Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.doc", docName.Replace(" ", "_")));
    Response.Charset = "utf-8";
}

But the problem is that the images are just links an thus not embedded in the word document.

Therefore I'm looking for an alternative
PDF seems to be a good alternative, does anyone know a good pdf writer for C#?
One that has some good references and has been tested properly?

LastEditorDisplayName: Sem Dendoncker

ContentLicense: CC BY-SA 2.5


问:
Howto get IntelliJ to auto-import when using javadoc {@link}?
This question explains how to enable auto-import settings. I did so, but when I type

```<code>/** some javadoc where I want to {@link SomeClass}
</code>```

it doesn't do what I want. Upon typing SomeClass IntelliJ shows me the potential link targets, all fine. I select one, and press enter. To then look at:

```<code>/** some javadoc where I want to {@link x.y,z.SomeClass}
</code>```

What I would like instead:

```<code>import x.y,z.SomeClass;
...
/** some javadoc where I want to {@link SomeClass}
</code>```

In other words: how do I make IntelliJ to auto-import classes for @linking instead of using the fully qualified class name?

答: In Preferences > Code Style > Java > Imports, uncheck "Use fully qualified class names in javadoc".

Body:
This question explains how to enable auto-import settings. I did so, but when I type

/** some javadoc where I want to {@link SomeClass}

it doesn't do what I want. Upon typing SomeClass IntelliJ shows me the potential link targets, all fine. I select one, and press enter. To then look at:

/** some javadoc where I want to {@link x.y,z.SomeClass}

What I would like instead:

import x.y,z.SomeClass;
...
/** some javadoc where I want to {@link SomeClass}

In other words: how do I make IntelliJ to auto-import classes for @linking instead of using the fully qualified class name?


问:
How to return compound types in Slick's Case-If-Then-Else
I just start dipping my toe into Slick.

In the coffee-supplier example, I try "Case If Then Else" like this:

```<code>val q = coffees.withFilter(_.price > 9.0).flatMap({ c =>
  suppliers.withFilter(_.id == c.supID).map({ s =>
    val t = c.name > s.name
    Case If t Then { (c.name, s.name) } Else { (s.name, c.name) }
  })
})
</code>```

The compiler emits an error:

```<code>could not find implicit value for evidence parameter of type scala.slick.ast.TypedType[(scala.slick.lifted.Column[String], scala.slick.lifted.Column[String])]
        Case If t Then { (c.name, s.name) } Else { (s.name, c.name) }
                         ^
</code>```

Much the same error apears for other compound types like List as well. I guess I'm on my own to define an implicit for the type in question but I'm not sure where to start.

答:
Try:</p>

```<code>    val q = coffees.withFilter(_.price > 9.0).flatMap({ c =>
      suppliers.withFilter(_.id == c.supID).map{ s =>
      (Case If c.name > s.name Then c.name Else s.name,
       Case If c.name > s.name Then s.name Else c.name)}})
</code>```

Body:
I just start dipping my toe into Slick.

In the coffee-supplier example, I try "Case If Then Else" like this:

val q = coffees.withFilter(_.price > 9.0).flatMap({ c =>
  suppliers.withFilter(_.id == c.supID).map({ s =>
    val t = c.name > s.name
    Case If t Then { (c.name, s.name) } Else { (s.name, c.name) }
  })
})

The compiler emits an error:

could not find implicit value for evidence parameter of type scala.slick.ast.TypedType[(scala.slick.lifted.Column[String], scala.slick.lifted.Column[String])]
        Case If t Then { (c.name, s.name) } Else { (s.name, c.name) }
                         ^

Much the same error apears for other compound types like List as well. I guess I'm on my own to define an implicit for the type in question but I'm not sure where to start.

Body:
Try:

    val q = coffees.withFilter(_.price > 9.0).flatMap({ c =>
      suppliers.withFilter(_.id == c.supID).map{ s =>
      (Case If c.name > s.name Then c.name Else s.name,
       Case If c.name > s.name Then s.name Else c.name)}})


问:
Logstash 5.6.2 aborts with "warning: ignoring JAVA_OPTS=-Xmx1024m; pass JVM parameters via LS_JAVA_OPTS"
I just downloaded latest versions of ELK 5.6.2 to upgrade so that I can use X-pack 5.6.2. Elasticsearch and kibana started with no issues but Logstash is aborting with the below message.
"warning: ignoring JAVA_OPTS=-Xmx1024m; pass JVM parameters via LS_JAVA_OPTS"
I tried adding set LS_JAVA_OPTS="-Xms1024m -Xmx1024m" in setup.bat and also -DLS_JAVA_OPTS="-Xms1024m -Xmx1024m" in jvm.options file. Both doesn't seem to work .
I don't see any log file being generated too. What am I doing wrong?</p>

答:
YOURFOLDER\logstash600\bin\setup.bat

find and replace

```<code>rem JAVA_OPTS is not a built-in JVM mechanism but some people think it is so we
rem warn them that we are not observing the value of %JAVA_OPTS%
rem if not "%JAVA_OPTS%" == "" (
rem   echo|set /p="warning: ignoring JAVA_OPTS=%JAVA_OPTS%; "
rem   echo pass JVM parameters via LS_JAVA_OPTS
rem )
set LS_JAVA_OPTS=%JAVA_OPTS%
</code>```

** this is NOT 100% correct

Body:
YOURFOLDER\logstash600\bin\setup.bat

find and replace

rem JAVA_OPTS is not a built-in JVM mechanism but some people think it is so we
rem warn them that we are not observing the value of %JAVA_OPTS%
rem if not "%JAVA_OPTS%" == "" (
rem   echo|set /p="warning: ignoring JAVA_OPTS=%JAVA_OPTS%; "
rem   echo pass JVM parameters via LS_JAVA_OPTS
rem )
set LS_JAVA_OPTS=%JAVA_OPTS%

** this is NOT 100% correct


问:
Get type instance from string in Python
So, I need to cast a value to a given type:

```<code>if 'int' == type_name:
    value = int(value)
elif 'str' == type_name:
    value = str(value)
...
</code>```

Is there a way to do that generically? E.g.:

```<code>type_instance = get_type_instance(type_name)
value = type_instance(value)
</code>```

I'm using Python 2.7, but would be interested in a Python 3.X solution as well.

Update:

Here's the solution I'm using:

```<code>class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe
</code>```

This is just a toy parser. Don't use in production!

答:
Since you specified float64 in an earlier version of the question, I assumed you were also interested in getting numpy types. If so, the following function should solve this:

```<code>def can_typecast(type, value):
    try:
        tp = getattr(__builtins__, type)
    except AttributeError:
        try:
            np = __import__('numpy')
            tp = getattr(np, type)
            if not isinstance(tp, type):
                raise ValueError('type string is not a type')
        except AttributeError:
            raise ValueError('Invalid type specified')
        except ImportError:
            raise ValueError('Numpy not found')
    try:
        tp(value)
    except ValueError:
        return False
    return True
</code>```

What this does is it first looks to see if the given type name can be resolved to a built-in type. If that fails, it looks to see if the type name can be found in numpy and if it is a valid type object and if so, tries the cast operation on that.

Title: Get type instance from string in Python

Body:
So, I need to cast a value to a given type:

if 'int' == type_name:
    value = int(value)
elif 'str' == type_name:
    value = str(value)
...

Is there a way to do that generically? E.g.:

type_instance = get_type_instance(type_name)
value = type_instance(value)

I'm using Python 2.7, but would be interested in a Python 3.X solution as well.

Update:

Here's the solution I'm using:

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe

This is just a toy parser. Don't use in production!

Body:
Since you specified float64 in an earlier version of the question, I assumed you were also interested in getting numpy types. If so, the following function should solve this:

def can_typecast(type, value):
    try:
        tp = getattr(__builtins__, type)
    except AttributeError:
        try:
            np = __import__('numpy')
            tp = getattr(np, type)
            if not isinstance(tp, type):
                raise ValueError('type string is not a type')
        except AttributeError:
            raise ValueError('Invalid type specified')
        except ImportError:
            raise ValueError('Numpy not found')
    try:
        tp(value)
    except ValueError:
        return False
    return True

What this does is it first looks to see if the given type name can be resolved to a built-in type. If that fails, it looks to see if the type name can be found in numpy and if it is a valid type object and if so, tries the cast operation on that.


问:
What is the minimum functionality needed to create Shell Replacement for Windows?
As you know we can change Windows Shell by changing Shell key in
    HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Winlogon

I create simple AutoHotKey script, compile it to cgywin.exe, and implement the basic WIN+R, WIN+E etc. What I targeted is  a windows environment where there is no taskbar, a fullscreen Cygwin Console and emacs inside it. I found that simple AutoHotkey suffice me

Here is the AutoHotKey script (compiled to cygwin.exe)

```<code>
Run C:\Development\Tools\Cygwin\Cygwin.bat,,max
Run C:\Development\Tools\Fun\xeyes.exe
run c:\Program Files\Digsby\digsby.exe
#h::
    run rundll32.exe powrprof.dll,SetSuspendState Hibernate
    return
#w::
    ifWinExist "@Gameloft:)"
    {
        WinActivate
    }else{
        run e:\Data\vs.net\At Gameloft\At Gameloft\At Gameloft\bin\Release\At Gameloft.exe
        WinWait "@Gameloft:)"
        WinActivate
    }
    return
#y::
    run c:\Program Files\Digsby\digsby.exe
    return
#f::
    run firefox
    return
#t::
        run thunderbird
        return
#c::
        Run C:\Development\Tools\Cygwin\Cygwin.bat,,max
    return
#r::
    DllCall(DllCall("GetProcAddress", "Uint", DllCall("GetModuleHandle", "str", "shell32"), "Uint", 61), "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0)
    return
#g::
    run chrome
    return
#e::
    run c:\Program Files\zabkat\xplorer2_lite\xplorer2_lite.exe
    return
#^e::
    run explorer
    return
#d::
    WinSet, Style, -0xC00000, A
    WinMaximize, A
    return
</code>
```

But I realize that certain shell function is missing. Such as when I download using Chrome, I can' use "Open Folder" menu for the downloaded file. It seems like somehow the shell provide those functionality.

What is the most basic stuff that must be implemented to create a suffice Shell Replacement??

Thank you!

答:
Technically, there is no "required" functionality for a shell -- you don't need anything at all (but of course, such a shell wouldn't serve any useful purpose).

In practice, you will sometimes encounter problems (as you did) when you replace the shell entirely. This is due to the fact that the default shell (explorer.exe) is the same process that also manifests itself as Windows Explorer. Depending on what API calls Chrome uses, it might fail to open a folder window because there is no running instance of explorer.exe.

For this reason, most shell replacements today don't really "replace" the default shell, but they run on top of explorer.exe, but hide the desktop and/or taskbar and instead present their own interface.

Body:
As you know we can change Windows Shell by changing Shell key in
    HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Winlogon

I create simple AutoHotKey script, compile it to cgywin.exe, and implement the basic WIN+R, WIN+E etc. What I targeted is  a windows environment where there is no taskbar, a fullscreen Cygwin Console and emacs inside it. I found that simple AutoHotkey suffice me

Here is the AutoHotKey script (compiled to cygwin.exe)

Run C:\Development\Tools\Cygwin\Cygwin.bat,,max
Run C:\Development\Tools\Fun\xeyes.exe
run c:\Program Files\Digsby\digsby.exe
#h::
    run rundll32.exe powrprof.dll,SetSuspendState Hibernate
    return
#w::
    ifWinExist "@Gameloft:)"
    {
        WinActivate
    }else{
        run e:\Data\vs.net\At Gameloft\At Gameloft\At Gameloft\bin\Release\At Gameloft.exe
        WinWait "@Gameloft:)"
        WinActivate
    }
    return
#y::
    run c:\Program Files\Digsby\digsby.exe
    return
#f::
    run firefox
    return
#t::
        run thunderbird
        return
#c::
        Run C:\Development\Tools\Cygwin\Cygwin.bat,,max
    return
#r::
    DllCall(DllCall("GetProcAddress", "Uint", DllCall("GetModuleHandle", "str", "shell32"), "Uint", 61), "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0)
    return
#g::
    run chrome
    return
#e::
    run c:\Program Files\zabkat\xplorer2_lite\xplorer2_lite.exe
    return
#^e::
    run explorer
    return
#d::
    WinSet, Style, -0xC00000, A
    WinMaximize, A
    return

But I realize that certain shell function is missing. Such as when I download using Chrome, I can' use "Open Folder" menu for the downloaded file. It seems like somehow the shell provide those functionality.

What is the most basic stuff that must be implemented to create a suffice Shell Replacement??

Thank you!


问:
Override config settings
I have a config file that is used in several projects, general.config, looks like:

```<code><?xml version="1.0" encoding="utf-8" ?>
<appSettings>
   <add key="mykey1" value="myvalue1"/>
   <add key="mykey2" value="myvalue2"/>
</appSettings>
</code>```

In one of the projects, I need to override one of the two settings. So the app.config of this project looks like:

```<code><?xml version="1.0"?>
<configuration>
  <appSettings file="general.config">
    <remove key="mykey1"/>
    <add key="mykey1" value="anothervalue"/>
    <add key="mykey3" value="myvalue3"/>
  </appSettings>
</configuration>
</code>```

But remove is not working here. How can I override mykey1 without breaking mykey2? add works in this case. I can get myvalue3 from ConfigurationManager.

EDIT: general.config is copied to output folder automatically when compiling. Don't worry about the path issue. Currently I got:

```<code>ConfigurationManager.AppSettings["mykey1"]
     //I got "myvalue1", but I want "anothervalue" here
     //that is, this item is "overrided", just like virtual methods in C#
ConfigurationManager.AppSettings["mykey2"]
     //this setting will not be modified, currently it works fine
ConfigurationManager.AppSettings["mykey3"]   //good
</code>```

答:
Your use of the file attribute to load common settings with an expectation that keys added directly to the <appSettings> element would override those common settings is understandable, but unfortunately that is not how it works.

Microsoft's intention was for the file attribute to load common settings that override the individual application's settings.

This is discussed in some detail in the Microsoft Documentation

To overcome this problem, we very occasionally declare base settings in the common file, and then appropriately named overrides in the application configuration. However this does require additional code which is a bit ugly. e.g.

```<code>var config = ConfigurationManager.AppSettings["MSG_QUEUE_PROVIDER_OVERRIDE"]
    ?? ConfigurationManager.AppSettings["MSG_QUEUE_PROVIDER"]
    ?? "ActiveMQ";
</code>```

```<code><appSettings file="common.config">
    <!-- Override the common values -->
    <add key="MSG_QUEUE_PROVIDER_OVERRIDE" value="RabbitMQ"/>
</appSettings>
</code>```

Title: Override config settings

Body:
I have a config file that is used in several projects, general.config, looks like:

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
   <add key="mykey1" value="myvalue1"/>
   <add key="mykey2" value="myvalue2"/>
</appSettings>

In one of the projects, I need to override one of the two settings. So the app.config of this project looks like:

<?xml version="1.0"?>
<configuration>
  <appSettings file="general.config">
    <remove key="mykey1"/>
    <add key="mykey1" value="anothervalue"/>
    <add key="mykey3" value="myvalue3"/>
  </appSettings>
</configuration>

But remove is not working here. How can I override mykey1 without breaking mykey2? add works in this case. I can get myvalue3 from ConfigurationManager.

EDIT: general.config is copied to output folder automatically when compiling. Don't worry about the path issue. Currently I got:

ConfigurationManager.AppSettings["mykey1"]
     //I got "myvalue1", but I want "anothervalue" here
     //that is, this item is "overrided", just like virtual methods in C#
ConfigurationManager.AppSettings["mykey2"]
     //this setting will not be modified, currently it works fine
ConfigurationManager.AppSettings["mykey3"]   //good

Body:
Your use of the file attribute to load common settings with an expectation that keys added directly to the <appSettings> element would override those common settings is understandable, but unfortunately that is not how it works.

Microsoft's intention was for the file attribute to load common settings that override the individual application's settings.

This is discussed in some detail in the Microsoft Documentation

To overcome this problem, we very occasionally declare base settings in the common file, and then appropriately named overrides in the application configuration. However this does require additional code which is a bit ugly. e.g.

var config = ConfigurationManager.AppSettings["MSG_QUEUE_PROVIDER_OVERRIDE"]
    ?? ConfigurationManager.AppSettings["MSG_QUEUE_PROVIDER"]
    ?? "ActiveMQ";

<appSettings file="common.config">
    <!-- Override the common values -->
    <add key="MSG_QUEUE_PROVIDER_OVERRIDE" value="RabbitMQ"/>
</appSettings>


问:
Mule munit-runner artefact nit downloaded
I am experiencing an issue with downloading the munit-runner artefact through maven. For some reason the jar is not downloaded. Not for 1.3.2, 1.3.3 or 1.3.4
I have cleaned the repository cash and rebuild but nothing seems to help.

The POM file looks according to the MuleSoft documentation.

Te specific error is:
Description Resource    Path    Location    Type
Project 'xxx' is missing required library: '/home/xxxx/.m2/repository/com/mulesoft/munit/munit-runner/1.3.3-SNAPSHOT/munit-runner-1.3.3-SNAPSHOT.jar'   xxx     Build path  Build Path Problem

答:
For future references you can find the latests versions of MUnit listed here:
https://docs.mulesoft.com/release-notes/munit-release-notes

Also, while it's cool for you to play with SNAPSHOT versions please notice that they are just SNAPSHOT thus not stable.
FYI our SNAPSHOT repositories are periodically clean so you may be pointing to an artifact that's not longer published


问:
Change input text value in before submitting form
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

```<code><form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));
    if (!isNan(value) && !empty(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});
</script>
</code>```

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

```<code> old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";
</code>```

答:
Here is a slightly different approach, but I believe that it should work.
(1) Create a named function for your logic (I corrected/changed some syntax that was problematic)

```<code><script type="text/javascript" language="javascript">
function prepSubmittal()
{
    var result = false;
    var value = null;

    try
    {
        value = $("#autocompleteform").val();

        if(value.indexOf(" ")>-1) value = value.substring(0, value.indexOf(" "));

        if (!isNaN(value) && value.trim().length>0)
        {
        $("#autocompleteform").val(value);
        result = true;
        }
            else
            {
        alert("Invalid Postcode");
        result = false;
        }
    }
    catch(e)
    {
        result = false;
        alert("prepSubmittal Error:  " + e.Message);
    }
    finally
    {

    }

    return result;
}

</script>
</code>```

(2) Change your form element to the following (note you had actions attribute instead of action and I added onsubmit="return prepSubmittal()")

```<code><form action="http://test.com" method="GET" onsubmit="return prepSubmittal()">
</code>```

Let me know how it goes.

Body:
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

<form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

 old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";

Body:
Here is a slightly different approach, but I believe that it should work.
(1) Create a named function for your logic (I corrected/changed some syntax that was problematic)

<script type="text/javascript" language="javascript">
function prepSubmittal()
{
    var result = false;
    var value = null;

    try
    {
        value = $("#autocompleteform").val();

        if(value.indexOf(" ")>-1) value = value.substring(0, value.indexOf(" "));

        if (!isNaN(value) && value.trim().length>0)
        {
        $("#autocompleteform").val(value);
        result = true;
        }
            else
            {
        alert("Invalid Postcode");
        result = false;
        }
    }
    catch(e)
    {
        result = false;
        alert("prepSubmittal Error:  " + e.Message);
    }
    finally
    {

    }

    return result;
}

</script>

(2) Change your form element to the following (note you had actions attribute instead of action and I added onsubmit="return prepSubmittal()")

<form action="http://test.com" method="GET" onsubmit="return prepSubmittal()">

Let me know how it goes.


问:
Spring Rest Template mocking with Spock
Can anyone show me an example, how to test RestTemplate using Spock.
My classes looks like this:

```<code>@Service
public class SomeService {

    @Autowired
    private EndpointUrlProvider endpointUrlProvider;
    private RestTemplate restTemplate = new RestTemplate();

    public SomeResponse doSomePostRequest(HttpEntity<?> httpEntity) throws Exception {
    ResponseEntity<SomeResponse> response;
            try{
                response = restTemplate.postForEntity(endpointUrlProvider.getSomeUrl(),httpEntity,SomeResponse.class);
            } catch (Exception e){
                throw new Exception("Exception occured during post for:" + httpEntity.getBody().getClass().getSimpleName() + " Cause: " + e.getMessage());
            }
            if(response.getStatusCode() == HttpStatus.OK){
                return response.getBody();
            }
            throw new Exception("Error during " + response.getBody().getClass().getSimpleName() + "Http status is diffrent than 200: " + response.getBody().toString());
        }
    }
</code>```

Tests:

```<code>class SomeTest extends Specification {

    RestTemplate restTemplate = Mock {
        postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
    }

    @Autowired
    SomeService someService

    def "someTest"() {
        when:
        SomeResponse someResponse = someService.doSomePostRequest(new HttpEntity<>(new SomeBody(), new HttpHeaders()))
        then:
        someResponse == new SomeResponse()
    }
}
</code>```

The major problem is mocking behaviour of RestTemplate,I looking for solution how to do it in proper way. I'm dont use spring boot.

答:
The situation is following:

You create new RestTemplate in your service class.

```<code>  private RestTemplate restTemplate = new RestTemplate();
</code>```

Then you create mock in tests and call your service method:

```<code>    RestTemplate restTemplate = Mock {
            postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
        }
                  ....
    someService.doSomePostRequest
</code>```

But your service still has usual rest template inside. You should inject mock object. I would suggest you doing it through constructor. So change your code to:

```<code>@Service
public class SomeService {

private EndpointUrlProvider endpointUrlProvider;
private RestTemplate restTemplate;

@Autowired
public SomeService(EndpointUrlProvider endpointUrlProvider, RestTemplate restTemplate){
  this.endpointUrlProvider = endpointUrlProvider;
  this.restTemplate = restTemplate;
}
</code>```

And your test will be:

```<code>class SomeTest extends Specification {

    RestTemplate restTemplate = Mock {
        postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
    }

    SomeService someService = new SomeService (  null, restTemplate);

    def "someTest"() {
        when:
        SomeResponse someResponse = someService.doSomePostRequest(new HttpEntity<>(new SomeBody(), new HttpHeaders()))
        then:
        someResponse == new SomeResponse()
    }
}
</code>```

Now your service object will call method on injected MOCK, not usual RestTemplate

p.s.

Constructor injection considered to be a good practice by spring.

It's better to create a RestTemplate bean and inject it everywhere, than create new object in all services.

Title: Spring Rest Template mocking with Spock

Body:
Can anyone show me an example, how to test RestTemplate using Spock.
My classes looks like this:

@Service
public class SomeService {

    @Autowired
    private EndpointUrlProvider endpointUrlProvider;
    private RestTemplate restTemplate = new RestTemplate();

    public SomeResponse doSomePostRequest(HttpEntity<?> httpEntity) throws Exception {
    ResponseEntity<SomeResponse> response;
            try{
                response = restTemplate.postForEntity(endpointUrlProvider.getSomeUrl(),httpEntity,SomeResponse.class);
            } catch (Exception e){
                throw new Exception("Exception occured during post for:" + httpEntity.getBody().getClass().getSimpleName() + " Cause: " + e.getMessage());
            }
            if(response.getStatusCode() == HttpStatus.OK){
                return response.getBody();
            }
            throw new Exception("Error during " + response.getBody().getClass().getSimpleName() + "Http status is diffrent than 200: " + response.getBody().toString());
        }
    }

Tests:

class SomeTest extends Specification {

    RestTemplate restTemplate = Mock {
        postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
    }

    @Autowired
    SomeService someService

    def "someTest"() {
        when:
        SomeResponse someResponse = someService.doSomePostRequest(new HttpEntity<>(new SomeBody(), new HttpHeaders()))
        then:
        someResponse == new SomeResponse()
    }
}

The major problem is mocking behaviour of RestTemplate,I looking for solution how to do it in proper way. I'm dont use spring boot.

Body:
The situation is following:

You create new RestTemplate in your service class.

  private RestTemplate restTemplate = new RestTemplate();

Then you create mock in tests and call your service method:

    RestTemplate restTemplate = Mock {
            postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
        }
                  ....
    someService.doSomePostRequest

But your service still has usual rest template inside. You should inject mock object. I would suggest you doing it through constructor. So change your code to:

@Service
public class SomeService {

private EndpointUrlProvider endpointUrlProvider;
private RestTemplate restTemplate;

@Autowired
public SomeService(EndpointUrlProvider endpointUrlProvider, RestTemplate restTemplate){
  this.endpointUrlProvider = endpointUrlProvider;
  this.restTemplate = restTemplate;
}

And your test will be:

class SomeTest extends Specification {

    RestTemplate restTemplate = Mock {
        postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
    }

    SomeService someService = new SomeService (  null, restTemplate);

    def "someTest"() {
        when:
        SomeResponse someResponse = someService.doSomePostRequest(new HttpEntity<>(new SomeBody(), new HttpHeaders()))
        then:
        someResponse == new SomeResponse()
    }
}

Now your service object will call method on injected MOCK, not usual RestTemplate

p.s.

Constructor injection considered to be a good practice by spring.

It's better to create a RestTemplate bean and inject it everywhere, than create new object in all services.


问:
Set onclick function to anchor element in laravel
I'm developing a laravel application, there I want to set a onclick function to Html anchor element.
So I created it as following way.

In my blade view

```<code><a class='compon' id="{{$value[1]}}" href="#" onclick="return myFunction();">
    <div class="mq-friends thumbnail">
       <div class="mq-friends-footer">
          <small>{{$value[0]}}</small>
       </div>
    </div>
</a>
</code>```

my resources/assets/js/app.js

```<code>function myFunction() {
    console.log('whatever');
    return true;
}
</code>```

This is not working, (I also carefully checked that app.js file has built into public/js/app.js using laravel-mix (npm run dev) and the function myFunction() is there.)

What I want to know is why it is not working? is there any problem with blade?

Note: This is clearly working when I insert this script into my same blade view without adding to js file:

```<code><script type='text/javascript'>
     function myFunction()
     {
          console.log('whatever');
          return true;
     }
</script>
</code>```

答:
Im not 100% sure of it, but:

I think when you want to bind the anchor onclick event, you need to bind the function to the window object, like this in your app.js:

```<code>  window.myFunction = function(ev) {
     console.log(ev)
  });
</code>```

In my case it solved.

Another way (seems to be the recommended one) is binding in an unobtrusive way.

Hope it helps o/

Body:
I'm developing a laravel application, there I want to set a onclick function to Html anchor element.
So I created it as following way.

In my blade view

          {{$value[0]}}

my resources/assets/js/app.js

function myFunction() {
    console.log('whatever');
    return true;
}

This is not working, (I also carefully checked that app.js file has built into public/js/app.js using laravel-mix (npm run dev) and the function myFunction() is there.)

What I want to know is why it is not working? is there any problem with blade?

Note: This is clearly working when I insert this script into my same blade view without adding to js file:

Body:
Im not 100% sure of it, but:

I think when you want to bind the anchor onclick event, you need to bind the function to the window object, like this in your app.js:

  window.myFunction = function(ev) {
     console.log(ev)
  });

In my case it solved.

Another way (seems to be the recommended one) is binding in an unobtrusive way.

Hope it helps o/


问:
Is it possible to make this image in CSS?
I was working on something in photoshop. You can see the picture here:

The three triangles in the background refer to 3 different pages on my website. I was wondering if it was possible to put the images like this in CSS because I want them to work like links and put some simple zoom animation on it when you hover on it. I'm actually pretty noob and new to CSS in overall so this will be hard to make without doing a lot of research but I hope you guys can help me out and give me a way to start. Any help is appreciated, thanks a lot!

just to be clear, the 3 triangles should become 3 individual pictures. I'm forced to work with flexbox on school if that matters. Thanks again.

答:
You can create a div container which will contain the image of the background background and then you just add div you position inside thanks to the position: absolute; using the top, bottom, right, left.
Like this :

.container {
  background-image:url("https://i.stack.imgur.com/8bUXt.png");
  width:500px;
  height:500px;
   }
.triangle1 {
  position:absolute;
  top:0px;
  left:0px;
}
.triangle2 {
  position:absolute;
  top:100px;
  left:50px;
}
.triangle3 {
  position:absolute;
  top:300px;
  left:300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="triangle1">
      <img src="https://alexanderssteak.com/wp-content/uploads/2016/05/starfav.png" alt="">
  </div>
  <div class="triangle2">
      <img src="https://alexanderssteak.com/wp-content/uploads/2016/05/starfav.png" alt="">
  </div>
  <div class="triangle3">
      <img src="https://alexanderssteak.com/wp-content/uploads/2016/05/starfav.png" alt="">
  </div>

</div></code>```

Body:
You can create a div container which will contain the image of the background background and then you just add div you position inside thanks to the position: absolute; using the top, bottom, right, left.
Like this :

.container {
  background-image:url("https://i.stack.imgur.com/8bUXt.png");
  width:500px;
  height:500px;
   }
.triangle1 {
  position:absolute;
  top:0px;
  left:0px;
}
.triangle2 {
  position:absolute;
  top:100px;
  left:50px;
}
.triangle3 {
  position:absolute;
  top:300px;
  left:300px;
}

<div class="container">
  <div class="triangle1">
      <img src="https://alexanderssteak.com/wp-content/uploads/2016/05/starfav.png" alt="">
  </div>
  <div class="triangle2">
      <img src="https://alexanderssteak.com/wp-content/uploads/2016/05/starfav.png" alt="">
  </div>
  <div class="triangle3">
      <img src="https://alexanderssteak.com/wp-content/uploads/2016/05/starfav.png" alt="">
  </div>

</div>


问:
Problems with asynchronous methods
I'm working with Flex 4 invoking webservices from JVM 1.6

I'm trying to make asynchronous calls to java to populate three comboboxes that will display country, states and cities, these three are related (master-slave relationship) but sometimes the calls are not met, or they are not completed, and I think this is because they are asynchronous, how can I be sure that I'm making the call to fill the next combobox when the master combobox (country) is filled?

protected function comboCountry_changeHandler(idCombo:String):void
            {

```<code>            selectedComboCountry= idCombo;
            var countryId:String;
            if(selectedComboCountry == comboCountry.id){
                countryId = String(comboCountry.selectedItem.countryId);
            }else if(selectedCombocountry == combocountrySuc.id){
                countryId = String(comboCountrySuc.selectedItem.countryId);
            }

            obtainStatesResult.token = wsfacturas.obtainStates(countryId);

        }
</code>```

protected function obtainStatesResult_resultHandler(event:ResultEvent):void
            {
                var StateListVo:ArrayCollection = obtainStatesResult.token.result as ArrayCollection;

```<code>            if(selectedComboCountry == "comboCountrySuc"){

                StateListsSuc.removeAll();
                CityListsSuc.removeAll();
                for (var d:int = 0; d < StateListVo.length; d++){
                    var estSuc:State = StateListVo[d];
                    StateListsSuc.addItem(estSuc);
                }

                comboStateSuc.dataProvider = StateListsSuc;
            }
            else if(selectedCombocountry == "combocountry"){
                StateListsEmp.removeAll();
                CityListsEmp.removeAll();
                for (var i:int = 0; i < StateListVo.length; i++){
                    var estEmp:State = StateListVo[i];
                    StateListsEmp.addItem(estEmp);
                }
                comboState.dataProvider = StateListsEmp;
            } else {

                for (var f:int = 0; f < StateListVo.length; f++){
                    var est:State = StateListVo[f];
                    StateListsSuc.addItem(est);
                    StateListsEmp.addItem(est);
                }
                comboState.dataProvider = StateListsEmp;
                comboStateSuc.dataProvider = StateListsSuc;

            }
        }
</code>```

答:
You might want to give slightly more details in your question. But I am just playing with whatever details you have provided.

1_ First asynchronous calls never caused me any problem with dynamic data binding. Sometimes
a SOAP call can take reasonable amount of time, in that case, make sure to show  a busy cursor till the web service call returns.

2_Combobox has always had problem with dynamic data binding. You can create a custom combobox that extends a combobox and override the setValue method Or Else you have to iterate over the dataProvider of the combobox and look for a match in the data field and then sets the combo box to that item.

So in summary, the problem mostly have to do with binding of the new data to the rendered combobox not asynchronous calls or any latency.

Title: Problems with asynchronous methods

Body:
I'm working with Flex 4 invoking webservices from JVM 1.6

I'm trying to make asynchronous calls to java to populate three comboboxes that will display country, states and cities, these three are related (master-slave relationship) but sometimes the calls are not met, or they are not completed, and I think this is because they are asynchronous, how can I be sure that I'm making the call to fill the next combobox when the master combobox (country) is filled?

protected function comboCountry_changeHandler(idCombo:String):void
            {

            selectedComboCountry= idCombo;
            var countryId:String;
            if(selectedComboCountry == comboCountry.id){
                countryId = String(comboCountry.selectedItem.countryId);
            }else if(selectedCombocountry == combocountrySuc.id){
                countryId = String(comboCountrySuc.selectedItem.countryId);
            }

            obtainStatesResult.token = wsfacturas.obtainStates(countryId);

        }

protected function obtainStatesResult_resultHandler(event:ResultEvent):void
            {
                var StateListVo:ArrayCollection = obtainStatesResult.token.result as ArrayCollection;

            if(selectedComboCountry == "comboCountrySuc"){

                StateListsSuc.removeAll();
                CityListsSuc.removeAll();
                for (var d:int = 0; d < StateListVo.length; d++){
                    var estSuc:State = StateListVo[d];
                    StateListsSuc.addItem(estSuc);
                }

                comboStateSuc.dataProvider = StateListsSuc;
            }
            else if(selectedCombocountry == "combocountry"){
                StateListsEmp.removeAll();
                CityListsEmp.removeAll();
                for (var i:int = 0; i < StateListVo.length; i++){
                    var estEmp:State = StateListVo[i];
                    StateListsEmp.addItem(estEmp);
                }
                comboState.dataProvider = StateListsEmp;
            } else {

                for (var f:int = 0; f < StateListVo.length; f++){
                    var est:State = StateListVo[f];
                    StateListsSuc.addItem(est);
                    StateListsEmp.addItem(est);
                }
                comboState.dataProvider = StateListsEmp;
                comboStateSuc.dataProvider = StateListsSuc;

            }
        }


问:
C# WPF Gridview will not show data Unless clicked
I am learning WPF/C# and trying to develop a small application that lists the file names in a datagrid (Windows 10, .Net frame 4.5)
So far the code is below

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.IO;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for ProcessFiles.xaml
    /// </summary>
    public partial class ProcessFiles : Window
    {
        List<FileInfo> myFileList = new List<FileInfo>();

        public ProcessFiles()
        {
            InitializeComponent();
            dGrid.AutoGenerateColumns = true;
            dGrid.UpdateLayout();
        }

        private void pButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Task.Factory.StartNew(() => ListMyFiles(myFileList));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error " +ex.Message);
            }
            finally
            {
                MessageBox.Show("Done.");
            }

            dGrid.ItemsSource = myFileList;
        }

        private void ListMyFiles(List<FileInfo> mylist)
        {
            //throw new NotImplementedException();

            foreach (FileInfo f in new DirectoryInfo(@"D:\Dummy2").GetFiles("*.*", SearchOption.TopDirectoryOnly))
            {
                // var currentFile = f;
                System.Threading.Thread.Sleep(10);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.ReadyItem.Content = "Updating..." + f.FullName;
                    mylist.Add(f);
                }), DispatcherPriority.Background);
            }

        }
    }
}
</code>```

I am facing a dilemma with automatically refreshing the datagrid once after the Dispatcher task completes. If I don't activate the GUI thread with a MessageBox.Show() somewhere in the button clicked event, the GridView doesn't show any data, however, maximizing the main window, adding a MessageBox show etc start displaying the columns filled.

What I must be missing?

答:
```<code> public partial class ProcessFiles : Window, INotifyPropertyChanged
{

    public void SetPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private ObservableCollection<FileInfo> myFileList = new ObservableCollection<FileInfo>();

    public ObservableCollection<FileInfo> MyFileList
    {
         get{return myFileList;}
         set
            {
               myFileList = value;
               SetPropertyChanged("MyFileList");
            }
    }

    public ProcessFiles()
    {
        InitializeComponent();
        dGrid.AutoGenerateColumns = true;
        dGrid.UpdateLayout();
    }

    private void pButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            Task.Factory.StartNew(() => ListMyFiles(myFileList));
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error " +ex.Message);
        }
        finally
        {
            MessageBox.Show("Done.");
        }

        dGrid.ItemsSource = MyFileList;
    }

    private void ListMyFiles(ObservableCollection<FileInfo> mylist)
    {
        //throw new NotImplementedException();

        foreach (FileInfo f in new DirectoryInfo(@"D:\Dummy2").GetFiles("*.*", SearchOption.TopDirectoryOnly))
        {
            // var currentFile = f;
            System.Threading.Thread.Sleep(10);
            Dispatcher.BeginInvoke(new Action(() =>
            {
                this.ReadyItem.Content = "Updating..." + f.FullName;
                mylist.Add(f);
            }), DispatcherPriority.Background);
        }

    }
</code>```

This should work

Body:
I am learning WPF/C# and trying to develop a small application that lists the file names in a datagrid (Windows 10, .Net frame 4.5)
So far the code is below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.IO;

namespace WpfApplication1
{
    ///
    /// Interaction logic for ProcessFiles.xaml
    ///
    public partial class ProcessFiles : Window
    {
        List<FileInfo> myFileList = new List<FileInfo>();

        public ProcessFiles()
        {
            InitializeComponent();
            dGrid.AutoGenerateColumns = true;
            dGrid.UpdateLayout();
        }

        private void pButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Task.Factory.StartNew(() => ListMyFiles(myFileList));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error " +ex.Message);
            }
            finally
            {
                MessageBox.Show("Done.");
            }

            dGrid.ItemsSource = myFileList;
        }

        private void ListMyFiles(List<FileInfo> mylist)
        {
            //throw new NotImplementedException();

            foreach (FileInfo f in new DirectoryInfo(@"D:\Dummy2").GetFiles("*.*", SearchOption.TopDirectoryOnly))
            {
                // var currentFile = f;
                System.Threading.Thread.Sleep(10);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.ReadyItem.Content = "Updating..." + f.FullName;
                    mylist.Add(f);
                }), DispatcherPriority.Background);
            }

        }
    }
}

I am facing a dilemma with automatically refreshing the datagrid once after the Dispatcher task completes. If I don't activate the GUI thread with a MessageBox.Show() somewhere in the button clicked event, the GridView doesn't show any data, however, maximizing the main window, adding a MessageBox show etc start displaying the columns filled.

What I must be missing?

Body:
 public partial class ProcessFiles : Window, INotifyPropertyChanged
{

    public void SetPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private ObservableCollection<FileInfo> myFileList = new ObservableCollection<FileInfo>();

    public ObservableCollection<FileInfo> MyFileList
    {
         get{return myFileList;}
         set
            {
               myFileList = value;
               SetPropertyChanged("MyFileList");
            }
    }

    public ProcessFiles()
    {
        InitializeComponent();
        dGrid.AutoGenerateColumns = true;
        dGrid.UpdateLayout();
    }

    private void pButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            Task.Factory.StartNew(() => ListMyFiles(myFileList));
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error " +ex.Message);
        }
        finally
        {
            MessageBox.Show("Done.");
        }

        dGrid.ItemsSource = MyFileList;
    }

    private void ListMyFiles(ObservableCollection<FileInfo> mylist)
    {
        //throw new NotImplementedException();

        foreach (FileInfo f in new DirectoryInfo(@"D:\Dummy2").GetFiles("*.*", SearchOption.TopDirectoryOnly))
        {
            // var currentFile = f;
            System.Threading.Thread.Sleep(10);
            Dispatcher.BeginInvoke(new Action(() =>
            {
                this.ReadyItem.Content = "Updating..." + f.FullName;
                mylist.Add(f);
            }), DispatcherPriority.Background);
        }

    }

This should work


问:
GET request is atomic but POST not in Sails.js DB Transaction
I noticed something in my Sails.js App which I can't explain:

The Client sends a GET request to the UserController, the UserController creates a new record in the TransactionTable for this User if its account is greater than 0 and updates its account to 0:

```<code>User.findOne(currentUser.id, function foundUser(err, foundUser) {
     if(foundUser.account > 0){
         //update the foundUsers account to 0
         User.update(foundUser.id, {account:0}, function updateUser(err, updatedUser) {
              //if error rollback;
             //save the User to the Transactions Table:
             Transactions.create(foundUser, function(){
                //if error rollback;
                return res.json("You will get Money!");

              })
         })
      }else{
         return res.json("Sorry you don't have enough Coins");
      }
})
</code>```

I did a loop(5repeats) on the Clientside for the GET request and it created only 1 Transaction and the other 4 got the log that foundUser.account is 0.
So the output was:

You will get Money!

Sorry you don't have enough Coins

Sorry you don't have enough Coins

Sorry you don't have enough Coins

Sorry you don't have enough Coins

I did the same loop with POST and it created 5 Transactions in the Table.

You will get Money!

You will get Money!

You will get Money!

You will get Money!

You will get Money!

So: Is GET atomic and POST not in a Sail.js Application? And is this way safe for production?

Edit:
GET request is idempotent - I tested the same loop with GET but this time I added a different value for each request for an argument and got 5 Transactions.

You will get Money!

You will get Money!

You will get Money!

You will get Money!

You will get Money!

How does this idempotent work? It has nothing to do with caching right? Because when it would just cache the response for the already known request like in the first GET example, the first example would also return 5 times the same response? But it actually "change" the resource on the server and delivers different responses. strange.

How can I fix this problem? So that in the time one transaction is written no other client can make a request?

答: This is not a Sails specific question, but how HTTP implements some behaviors. Take a look at these: LINK1, LINK2.</p>

Body:
I noticed something in my Sails.js App which I can't explain:

The Client sends a GET request to the UserController, the UserController creates a new record in the TransactionTable for this User if its account is greater than 0 and updates its account to 0:

User.findOne(currentUser.id, function foundUser(err, foundUser) {
     if(foundUser.account > 0){
         //update the foundUsers account to 0
         User.update(foundUser.id, {account:0}, function updateUser(err, updatedUser) {
              //if error rollback;
             //save the User to the Transactions Table:
             Transactions.create(foundUser, function(){
                //if error rollback;
                return res.json("You will get Money!");

              })
         })
      }else{
         return res.json("Sorry you don't have enough Coins");
      }
})

I did a loop(5repeats) on the Clientside for the GET request and it created only 1 Transaction and the other 4 got the log that foundUser.account is 0.
So the output was:

You will get Money!

Sorry you don't have enough Coins

Sorry you don't have enough Coins

Sorry you don't have enough Coins

Sorry you don't have enough Coins

I did the same loop with POST and it created 5 Transactions in the Table.

You will get Money!

You will get Money!

You will get Money!

You will get Money!

You will get Money!

So: Is GET atomic and POST not in a Sail.js Application? And is this way safe for production?

Edit:
GET request is idempotent - I tested the same loop with GET but this time I added a different value for each request for an argument and got 5 Transactions.

You will get Money!

You will get Money!

You will get Money!

You will get Money!

You will get Money!

How does this idempotent work? It has nothing to do with caching right? Because when it would just cache the response for the already known request like in the first GET example, the first example would also return 5 times the same response? But it actually "change" the resource on the server and delivers different responses. strange.

How can I fix this problem? So that in the time one transaction is written no other client can make a request?


问:
Cython's calculations are incorrect
I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version:

```<code>from __future__ import division
pi = 0
l = 1
x = True
while True:
    if x:
        pi += 4/l
    else:
        pi -= 4/l
    x = not x
    l += 2
    print str(pi)
</code>```

The Cython version:

```<code>cdef float pi = 0.0
cdef float l = 1.0
cdef unsigned short x = True
while True:
    if x:
        pi += 4.0/l
    else:
        pi -= 4.0/l
    x = not x
    l += 2
    print str(pi)
</code>```

When I stopped the Python version it had correctly calculated pi to 3.141592. The Cython version eventually ended up at 3.141597 with some more digits that I don't remember (my terminal crashed) but were incorrect. Why are the Cython version's calculations incorrect?

答: How do you know when it's finished? Have you considered that the value for pi would oscillate about the true value, and you would expect that if you stopped the code at some point, you could have a value that is too high (or too low)?

Title: Cython's calculations are incorrect

Body:
I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version:

from __future__ import division
pi = 0
l = 1
x = True
while True:
    if x:
        pi += 4/l
    else:
        pi -= 4/l
    x = not x
    l += 2
    print str(pi)

The Cython version:

cdef float pi = 0.0
cdef float l = 1.0
cdef unsigned short x = True
while True:
    if x:
        pi += 4.0/l
    else:
        pi -= 4.0/l
    x = not x
    l += 2
    print str(pi)

When I stopped the Python version it had correctly calculated pi to 3.141592. The Cython version eventually ended up at 3.141597 with some more digits that I don't remember (my terminal crashed) but were incorrect. Why are the Cython version's calculations incorrect?


问:
BackgroundImage in css
how to put backgound image with help of css.
When an image file is stored locally on a desktop, CSS file and image are in the same folder. \Desktop\New folder\image:- image destination
\Desktop\New folder\css:- css file destination

答: Technically, local files are not accessible from CSS. All the file you want to access should be accessible using URI. </p>

ContentLicense: CC BY-SA 4.0

Title: BackgroundImage in css


问:
Deploy docker windows container from CI to Windows Server 2016
I'm trying to wrap my head around Docker containers, specifically how to deploy them to a Docker container host. I know there are lots of options here and ultimately we'll switch to a more common deployment approach (e.g. to Azure, AWS) but this is a temporary requirement. We're using windows containers.

I have a container image that I've created and will be recreated on each build as part of a Jenkins job (our Jenkins instance is hosted on a container-ready windows server 2016 box). I also have a separate container-ready Windows Server 2016 box which is where we intend to run the containers from.

However, I'm not sure how I can have the containers that our Jenkins box produces automatically pushed to our separate 2016 host. Ideally, I'd like to avoid using a container registry, unless there is a low-friction, on-premise option available.

答:
Container registries are the way to distribute Docker images. Tooling is built around registries, it would be counterproductive to work against the concept.

But docker image save and docker image import could get you started as it saves the image as a tar file that you can transfer between the hosts. Once you copied the image to the other box, you can start it up with the usual docker run command, or docker compose up.

If your case is not trivial though and you start having multiple Docker hosts to run the containers, container orchestrators like Docker Swarm, Kubernetes are the way to go - or the managed versions of those, like Azure ACS. That rabbit hole is deeper though than I can answer in a single SO answer :)


问:
How to build a function which return a list which contains for each value from lst1, its position in list lst2
In Python 3.6 I get two lists from the input, and they are permutations of each other.

For example:

List 1 = [4,2,8,3]

List 2 = [2,4,3,8]

I want to get List 3 =  [1, 0, 3, 2] with the positions of all elements of list 1 in list 2.

I have already built the part that identifies whether the lists are permutations or not, then I have tried running loops of k in list 2, and appending list2[k] into a new list, but all I have got is confused results.

答:
Just try this</p>

```<code>List1 =  [4,2,8,3]
List2 =  [2,4,3,8]

def solve(a, b):
    result = []
    for x in range(0, len(a)):
        result.append(a.index(b[x]))
    return result

print solve(List1, List2)
</code>```

Body:
Just try this

List1 =  [4,2,8,3]
List2 =  [2,4,3,8]

def solve(a, b):
    result = []
    for x in range(0, len(a)):
        result.append(a.index(b[x]))
    return result

print solve(List1, List2)


问:
how to prevent conflict with file sharing between VB.NET windows app and VB.NET web app
I have a VB.NET web app frontend and a VB.NET windows app backend, both running on my Azure Windows 2012 server VM.

The backend runs every 10 seconds, review the data files, and sometimes writes data.

The frontend (web) accesses the data files when a user is using the web.

Sometimes, the web gets an error when it does My.Computer.FileSystem.WriteAllText or My.Computer.FileSystem.ReadAllText.

These two methods are how both backend and frontend access the data files.
Data files are all simple .txt text-based files.

答:
Judging from the fact the failures are intermittent, it's likely that you are experiencing contention issues with your two processes. You might want to manually write to the file and ensure you implement some sharing that will at least mitigate some of the issues:

```<code>Using fs As New FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read),
        sw As New StreamWriter(fs)
    sw.Write("A whole bunch of text to write")
End Using
</code>```

The above code opens the file after placing a read only lock on the it. This allows subsequent processes to open the file to read so even while you are holding this file for instance in your Windows app, your web app can read what's in it without throwing.

```<code>Using fs As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
        sr As New StreamReader(fs)
    Console.WriteLine(sr.ReadToEnd())
End Using
</code>```

This last snippet is what you use for reading the file. It places a read/write share when it opens. Since this process is only reading from the file, you can allow other processes to open it for reading as well without issue. In this case, I allowed other processes to write to the file so that they are not restricted.

You'll have to handle exceptions that may arise when you cannot open it in the mode you specified because of a lock that was set up by another process.

Body:
Judging from the fact the failures are intermittent, it's likely that you are experiencing contention issues with your two processes. You might want to manually write to the file and ensure you implement some sharing that will at least mitigate some of the issues:

Using fs As New FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read),
        sw As New StreamWriter(fs)
    sw.Write("A whole bunch of text to write")
End Using

The above code opens the file after placing a read only lock on the it. This allows subsequent processes to open the file to read so even while you are holding this file for instance in your Windows app, your web app can read what's in it without throwing.

Using fs As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
        sr As New StreamReader(fs)
    Console.WriteLine(sr.ReadToEnd())
End Using

This last snippet is what you use for reading the file. It places a read/write share when it opens. Since this process is only reading from the file, you can allow other processes to open it for reading as well without issue. In this case, I allowed other processes to write to the file so that they are not restricted.

You'll have to handle exceptions that may arise when you cannot open it in the mode you specified because of a lock that was set up by another process.


问:
Fill HTML element with text based on input with JavaScript
The code right now works only to fill another input field. But I need it to fill a regular paragraph and not another input field. How can I do it?

$(".first").on('keydown',function(){
  $(".second").val($(this).val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="first" placeholder="type here">
<input type="text" class="second" placeholder="here it is the reuslt"></code>```

答:
```<code>$(".first").on('keydown',function(){
    $('.selectorOfDOM').text($(this).val());
}
</code>```

You can find similar question at this link.
Fill div with text

Body:
The code right now works only to fill another input field. But I need it to fill a regular paragraph and not another input field. How can I do it?

$(".first").on('keydown',function(){
  $(".second").val($(this).val());
});

<input type="text" class="first" placeholder="type here">
<input type="text" class="second" placeholder="here it is the reuslt">

Body:
$(".first").on('keydown',function(){
    $('.selectorOfDOM').text($(this).val());
}

You can find similar question at this link.
Fill div with text


问:
What are the focal lengths and the principal point in KITTI stereo dataset?
I am using the KITTI stereo dataset 2012 and 2015 in a research.

But I need some values that I didn't find:

focal lengths for x and y direction.

the principal point.

There are some files inside the "calib" folder in dataset. A content example is here (calib/000000.txt):

P0: 7.070912e+02 0.000000e+00 6.018873e+02 0.000000e+00 0.000000e+00 7.070912e+02 1.831104e+02 0.000000e+00 0.000000e+00 0.000000e+00 1.000000e+00 0.000000e+00

P1: 7.070912e+02 0.000000e+00 6.018873e+02 -3.798145e+02 0.000000e+00 7.070912e+02 1.831104e+02 0.000000e+00 0.000000e+00 0.000000e+00 1.000000e+00 0.000000e+00

P2: 7.070912e+02 0.000000e+00 6.018873e+02 4.688783e+01 0.000000e+00 7.070912e+02 1.831104e+02 1.178601e-01 0.000000e+00 0.000000e+00 1.000000e+00 6.203223e-03

P3: 7.070912e+02 0.000000e+00 6.018873e+02 -3.334597e+02 0.000000e+00 7.070912e+02 1.831104e+02 1.930130e+00 0.000000e+00 0.000000e+00 1.000000e+00 3.318498e-03

Following this paper (specifically in section IV, B):
http://www.mrt.kit.edu/z/publ/download/2013/GeigerAl2013IJRR.pdf

I got that P is the projection matrix after retification. And i ∈ {0, 1, 2, 3} is the camera index, where 0 represents the left grayscale, 1 the right grayscale, 2 the left color and 3 the right color camera.

But my problem is that I don't know how to find the focal length and the principal point that I need.

Can someone help me?

Thank you all!

答:
The only values that I have been able to find are this;

```<code>// calibration parameters for sequence 2010_03_09_drive_0019
param.calib.f  = 645.24;    // focal length in pixels
param.calib.cu = 635.96;    // principal point (u-coordinate) in pixels
param.calib.cv = 194.13;    // principal point (v-coordinate) in pixels
param.base = 0.5707;        // baseline in meters
</code>```

From; https://github.com/pangfumin/libviso2/blob/master/src/demo.cpp~

Body:
The only values that I have been able to find are this;

// calibration parameters for sequence 2010_03_09_drive_0019
param.calib.f  = 645.24;    // focal length in pixels
param.calib.cu = 635.96;    // principal point (u-coordinate) in pixels
param.calib.cv = 194.13;    // principal point (v-coordinate) in pixels
param.base = 0.5707;        // baseline in meters

From; https://github.com/pangfumin/libviso2/blob/master/src/demo.cpp~


问:
Instantiating a cxf service causes injection failure for other unrelated service
I am developing a Consumer Service for some Webservice.
The application is already providing Webservices (as a server), but this is the first consumer.

The generation is ok, but I encounter a weird -to me!- problem as soon as I try to instantiate the javax.xml.ws.Service from the constructor of a consumer service : all provider webservices implementor bean become suddenly "undefined" (if I comment the first provider from cxf.xml, the second one is also 'undefined' as well).

Looks like I trigger some unexpected injection that may happen too soon... but I don't understand why, and how to fix it! Any idea is welcome!

The error trace :

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someService' defined in class path resource [spring-core-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.services.impl.com.my.services.impl.SomeServiceImpl]: Constructor threw exception; nested exception is java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:254)

...

Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.services.impl.com.my.services.impl.SomeServiceImpl: Constructor threw exception; nested exception is java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:115)

...

Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.apache.cxf.bus.spring.SpringBusFactory.createBus(SpringBusFactory.java:97)

...

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
    ...
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:387)

...

(last)

the cxf.xml

```<code>  <jaxws:endpoint
      id="someProviderWebService"
      implementor="#someProviderWebServiceImplementor"
      address="/services/SomeProviderWebService"/>
  <jaxws:endpoint
      id="someProviderWebService2"
      implementor="#someProviderWebServiceImplementor2"
      address="/services/SomeProviderWebService2"/>

    <bean id="logInbound" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
    <bean id="logOutbound" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />

    <cxf:bus>
        <cxf:inInterceptors><ref bean="logInbound" /></cxf:inInterceptors>
        <cxf:outInterceptors><ref bean="logOutbound" /></cxf:outInterceptors>
        <cxf:inFaultInterceptors><ref bean="logInbound" /></cxf:inFaultInterceptors>
        <cxf:outFaultInterceptors><ref bean="logOutbound" /></cxf:outFaultInterceptors>
    </cxf:bus>
</code>```

The someServiceImpl:

```<code>    public SomeServiceImpl() throws MalformedURLException {
        SomeConsumerService service= new SomeConsumerService (); // this is the line causing the problem
    }
</code>```

The webService SomeConsumerService :

```<code>public class SomeConsumerService extends javax.xml.ws.Service{

    public final static URL WSDL_LOCATION;
    public final static QName SERVICE = new QName("urn:test.com:anywhere/webservice/T", "SomeService");
    static {
        URL url = null;
        try {
            url = new URL("http://some.wsdl");
        } catch (MalformedURLException e) {
            System.err.println("Ooops! ");
        }
        WSDL_LOCATION = url;
    }

    public SomeConsumerService () {
        super(WSDL_LOCATION, SERVICE);
    }
}
</code>```

The Context :

```<code><bean name="someService" class="com.my.services.impl.SomeServiceImpl">
</bean>

<bean name="someProviderWebServiceImplementor"  class="com.my.services.impl.SomeProviderWebServiceImplementorImpl">
</bean>
</code>```

答:
A workmate managed to find out the problem : looks like the cxf servlet will create its own context based on cxf.xml (only!) when it is present. If it is not, it will look for its configuration in application Context.

Though, it also it is only true when I create a consumer... thus, I am not sure whether it is more of an unexpected side-effect, or a true feature.

Anyway, the solution that works here is :

rename cxf.xml to another_name_for_cxf.xml

import the renamed file from application-context.xml (or whatever name you gave it)

```<code><import resource="classpath:another_name_for_cxf.xml"/>
</code>```

And then, the magic will start to operate!

Body:
I am developing a Consumer Service for some Webservice.
The application is already providing Webservices (as a server), but this is the first consumer.

The generation is ok, but I encounter a weird -to me!- problem as soon as I try to instantiate the javax.xml.ws.Service from the constructor of a consumer service : all provider webservices implementor bean become suddenly "undefined" (if I comment the first provider from cxf.xml, the second one is also 'undefined' as well).

Looks like I trigger some unexpected injection that may happen too soon... but I don't understand why, and how to fix it! Any idea is welcome!

The error trace :

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someService' defined in class path resource [spring-core-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.services.impl.com.my.services.impl.SomeServiceImpl]: Constructor threw exception; nested exception is java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:254)

...

Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.services.impl.com.my.services.impl.SomeServiceImpl: Constructor threw exception; nested exception is java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:115)

...

Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.apache.cxf.bus.spring.SpringBusFactory.createBus(SpringBusFactory.java:97)

...

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someProviderWebService': Cannot resolve reference to bean 'someProviderWebServiceImplementor' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
    ...
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'someProviderWebServiceImplementor' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:387)

...

(last)

the cxf.xml

  <jaxws:endpoint
      id="someProviderWebService"
      implementor="#someProviderWebServiceImplementor"
      address="/services/SomeProviderWebService"/>
  <jaxws:endpoint
      id="someProviderWebService2"
      implementor="#someProviderWebServiceImplementor2"
      address="/services/SomeProviderWebService2"/>

    <bean id="logInbound" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
    <bean id="logOutbound" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />

    <cxf:bus>
        <cxf:inInterceptors><ref bean="logInbound" /></cxf:inInterceptors>
        <cxf:outInterceptors><ref bean="logOutbound" /></cxf:outInterceptors>
        <cxf:inFaultInterceptors><ref bean="logInbound" /></cxf:inFaultInterceptors>
        <cxf:outFaultInterceptors><ref bean="logOutbound" /></cxf:outFaultInterceptors>
    </cxf:bus>

The someServiceImpl:

    public SomeServiceImpl() throws MalformedURLException {
        SomeConsumerService service= new SomeConsumerService (); // this is the line causing the problem
    }

The webService SomeConsumerService :

public class SomeConsumerService extends javax.xml.ws.Service{

    public final static URL WSDL_LOCATION;
    public final static QName SERVICE = new QName("urn:test.com:anywhere/webservice/T", "SomeService");
    static {
        URL url = null;
        try {
            url = new URL("http://some.wsdl");
        } catch (MalformedURLException e) {
            System.err.println("Ooops! ");
        }
        WSDL_LOCATION = url;
    }

    public SomeConsumerService () {
        super(WSDL_LOCATION, SERVICE);
    }
}

The Context :

<bean name="someService" class="com.my.services.impl.SomeServiceImpl">
</bean>

<bean name="someProviderWebServiceImplementor"  class="com.my.services.impl.SomeProviderWebServiceImplementorImpl">
</bean>

Body:
A workmate managed to find out the problem : looks like the cxf servlet will create its own context based on cxf.xml (only!) when it is present. If it is not, it will look for its configuration in application Context.

Though, it also it is only true when I create a consumer... thus, I am not sure whether it is more of an unexpected side-effect, or a true feature.

Anyway, the solution that works here is :

rename cxf.xml to another_name_for_cxf.xml

import the renamed file from application-context.xml (or whatever name you gave it)

<import resource="classpath:another_name_for_cxf.xml"/>

And then, the magic will start to operate!


问:
Making bots that navigate the web
I've always wanted to automate some things like in browser games, such as OGame, or Facebook poking. I could use the java.awt.Robot class, which is the only solution I've found out there, but that isn't necessarily going to pick things up every time and it takes over your computer.

So what I want to do is make a bot that will do things like sign into websites and keep the login cookies, so that it can actually access things, press buttons, fill forms, etc.

So how can this be done?

(I'm not looking for a spider... I've already made something like that that rips Javadocs)

Thanks in advance!
~Somanayr

答:
You are looking for WebHarvest, pretty neat!

It has an autoexecutable JAR with a good interface to create scripts (XML files), once the script is good just put it in the classpath and use the API to execute it whenever you want.

Of course it can fill forms, keep cookies, etc

Title: Making bots that navigate the web


问:
Is this insert possible in function: author meta into a different string?
I need advice. I have been provided with the following code by a plugin developer in order to insert a donation form into the single post template but I need the paypal address to automatically bring in the post author's email address via author meta. Is this possible?</p>

```<code>function multiple_paypal_accounts( $paypal_args, $payment_data ) {
    $form_id = isset( $payment_data['post_data']['the-form-id'] ) ? $payment_data['post_data']['the-form-id'] : '';
    if('3830' === $form_id ) {
        // Here I want to customize the email address to show the post author's paypal email address
        $paypal_args['business'] = 'THIS IS WHERE I NEED TO PULL IN THE PAYPAL ADDRESS FROM AUTHOR META DATA';
    }
    // Always return the paypal args.
    return $paypal_args;
}
add_filter( 'the_form_paypal_redirect_args', 'multiple_paypal_accounts', 10, 2 );
</code>```

答:
If I'm understanding the question, forms accept GET and POST parameters and by the looks of it the variable $payment_data is used like the following: $payment_data['post_data'][?]. This appears to potentially hold this information. $payment_data['post_data']['email'] would be a bold guess but may not be correct.

If it were correct you can left-asign like so: $paypal_args['business'] = $payment_data['post_data']['email'];

If not you can perform a var_dump() of $payment_data['post_data'] to find out what the contents this variable might hold. More on this: http://php.net/manual/en/function.var-dump.php

Body:
I need advice. I have been provided with the following code by a plugin developer in order to insert a donation form into the single post template but I need the paypal address to automatically bring in the post author's email address via author meta. Is this possible?

function multiple_paypal_accounts( $paypal_args, $payment_data ) {
    $form_id = isset( $payment_data['post_data']['the-form-id'] ) ? $payment_data['post_data']['the-form-id'] : '';
    if('3830' === $form_id ) {
        // Here I want to customize the email address to show the post author's paypal email address
        $paypal_args['business'] = 'THIS IS WHERE I NEED TO PULL IN THE PAYPAL ADDRESS FROM AUTHOR META DATA';
    }
    // Always return the paypal args.
    return $paypal_args;
}
add_filter( 'the_form_paypal_redirect_args', 'multiple_paypal_accounts', 10, 2 );


答:
This is how I'd tackle your described problem:

```<code>List1 = [4, 2, 8, 3]
List2 = [2, 4, 3, 8]
List3 = []
for i in List1:
    List3.append(List2.index(i))

print(List3)
</code>```

Explanation

With the for-statement I'm iterating through each value of List1.

The List2.index() function returns the index of the given value in List2.

With List3.append() I'm adding this value at the end of List3

You can try it online here.

I hope this was able to answer your question.

Title: How to build a function which return a list which contains for each value from lst1, its position in list lst2

Body:
In Python 3.6 I get two lists from the input, and they are permutations of each other.

For example:

List 1 = [4,2,8,3]

List 2 = [2,4,3,8]

I want to get List 3 =  [1, 0, 3, 2] with the positions of all elements of list 1 in list 2.

I have already built the part that identifies whether the lists are permutations or not, then I have tried running loops of k in list 2, and appending list2[k] into a new list, but all I have got is confused results.

Body:
This is how I'd tackle your described problem:

List1 = [4, 2, 8, 3]
List2 = [2, 4, 3, 8]
List3 = []
for i in List1:
    List3.append(List2.index(i))

print(List3)

Explanation

With the for-statement I'm iterating through each value of List1.

The List2.index() function returns the index of the given value in List2.

With List3.append() I'm adding this value at the end of List3

You can try it online here.

I hope this was able to answer your question.


问:
Geolocation find closest coordinate match
I'm trying to create a Javascript function that can find the closest coordinate match in an array of coordinates.

My coordinates: 33.9321, 18.8602
These coordinates will vary, but the 4 locations listed below will stay the same.

Location1: 33.9143, 18.5701
Location2: 26.2041, 28.0473
Location3: 25.7479, 28.2293
Location4: 29.8587, 31.0218

答:
try to run my code to see if it helps you.
I have used var home as your stargint point if browser didn't work for you.
Also I have saved all locations in var points so you can change that if you need.

Then I just look over each point and it will output in the console what is the distance to ref point. In your case it's the first point

var home = [ '33.9321', '18.8602' ];
var points = [
  [ '33.9143', '18.5701' ],
  [ '26.2041', '28.0473' ],
  [ '25.7479', '28.2293' ],
  [ '29.8587', '31.0218' ]
];
// loop over each point and output distance!
for( var i = 0; i < points.length; i++){
  var diff = twoPointsDiff(home[0],home[1],points[i][0],points[i][1]);
  console.log( 'distance from point' + (i+1) + ': ' + diff );
}
// helper fn to calc distance
function twoPointsDiff(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}
// helper fn to convert deg to radians
function deg2rad(deg) {
  return deg * (Math.PI/180)
}```


问:
C++: static function member shared between threads, can block all?
I have a class, which has static function defined to work with C-style extern C { static void callback(foo bar) { } }. // static is defined in header.

Three objects (each in separate pthread) are instantiated from this class, each of them has own loop (in class constructor), which can receive the callback.

The pointer to function is passed as:

```<code>x = init_function(h, queue_id, &callback, NULL);
while(1) { loop_function(x); }
</code>```

So each thread has the same pointer to &callback.

Callback function can block for minutes.

Each thread object, excluding the one which got the blocking callback, can call callback again.

If the callback function exists only once, then any thread attempting to callback will also block. This would give me an undesired bug, circa is interesting to ask: can anything in C++ become acting this way? Maybe, due to extern { } or some pointer usage?

答:
If you don't specifically code some sort of lock or call a function (including system functions) that  has some sort of lock (like opening the same file for exclusive write access, etc.) then there is no way to "block" other threads.  There is no automatic function locking in c or c++.

If the callback executes sleep(3600), that would not block other threads.  Each thread would enter the callback and execute sleep(3600).

If you want threads to wait for critical code to execute, you must code the locking mechanism yourself.  You generally activate the locking mechanism before executing the code (referred to commonly as "locking") and then you generally deactivate the lock after executing the code ("unlocking").  Linux coders generally use mutexes or gcc atomic operations to do this.

Sounds to me like you need to read some basic documentation about threads and multi threaded code and start from there.  Here is one of a million articles on the basics of threading: link text

Body:
I have a class, which has static function defined to work with C-style extern C { static void callback(foo bar) { } }. // static is defined in header.

Three objects (each in separate pthread) are instantiated from this class, each of them has own loop (in class constructor), which can receive the callback.

The pointer to function is passed as:

x = init_function(h, queue_id, &callback, NULL);
while(1) { loop_function(x); }

So each thread has the same pointer to &callback.

Callback function can block for minutes.

Each thread object, excluding the one which got the blocking callback, can call callback again.

If the callback function exists only once, then any thread attempting to callback will also block. This would give me an undesired bug, circa is interesting to ask: can anything in C++ become acting this way? Maybe, due to extern { } or some pointer usage?


答:
You should use 'input' event instead of keydown/keyup - if user pastes the value neither of them will work. So use this instead:

$('.inputClass').on('input', function() {
    $('.paragraphClass').text($(this).val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inputClass">
<p class="paragraphClass"></p></code>```

Title: Fill HTML element with text based on input with JavaScript

Body:
You should use 'input' event instead of keydown/keyup - if user pastes the value neither of them will work. So use this instead:

$('.inputClass').on('input', function() {
    $('.paragraphClass').text($(this).val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inputClass">
<p class="paragraphClass"></p>