问:
Why is createView never called?
My ultimate goal is to be able move my content widgets into a custom view and instantiate that view in an Anko layout in my MainView.  I thought I had this working at one point, but I can't reproduce it.

When I run with the following code, the content in the createView of the MainContextView is never displayed and I never see the message "creating main context view", but I do see the message "main content view".

I start by creating a MainContextView

```<code>class MainContextView(context: Context) : ViewGroup(context), AnkoComponent<Context> {

    lateinit var textBox: EditText
    lateinit var button: Button
    lateinit var clickCount: TextView

    override fun createView(ui: AnkoContext<Context>) = with(ui) {
        println("creating main context view")
        verticalLayout {
            themedEditText {
                hint = "hi from main context"
            }
            button = themedButton {
                text = "ok"
            }
            textBox = themedEditText {
                hint = "hi"
            }
            clickCount = themedTextView {
               text = "0"
            }
        }
    }

    override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {
        println("onLayout called")
    }

}
</code>```

and call it from my main view

```<code>class MainView : AnkoComponent<MainActivity> {

    lateinit var mainCtx: MainContextView
    lateinit var textBox: EditText
    lateinit var button: Button
    lateinit var clickCount: TextView
    lateinit var mainMenu: Menu
    lateinit var settingItem: MenuItem
    lateinit var otherItem: MenuItem
    lateinit var floatingActionButton: FloatingActionButton

    override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
        coordinatorLayout {
            verticalLayout {
                themedAppBarLayout {
                    themedToolbar(theme = R.style.Base_ThemeOverlay_AppCompat_Dark_ActionBar) {
                        title = resources.getString(R.string.app_name)
                        popupTheme = R.style.AppTheme
                        mainMenu = menu
                        settingItem = mainMenu.add("My Settings")
                        otherItem = mainMenu.add("My Other")
                    }
                }.lparams(width = matchParent, height = wrapContent)

                // ************************************
                // HERE IS THE CALL TO THE CONTEXT VIEW
                mainCtx = mainContextView { println("main content view ") }
               // *************************************

            }.lparams(width = matchParent, height = wrapContent) {
            }
            floatingActionButton = floatingActionButton {
                imageResource = android.R.drawable.ic_dialog_email
            }.lparams {
                margin = dip(10)
                gravity = Gravity.BOTTOM or Gravity.END
            }
        }
    }
}
</code>```

The MainView is called set as the content view from the  MainActivity

```<code>class MainActivity : AppCompatActivity() {

    private lateinit var presenter: MainPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val mainView = MainView()
        mainView.setContentView(this)
        presenter = MainPresenter(mainView)

    }

}
</code>```

And finally the ViewManger extensions

```<code>inline fun ViewManager.mainContextView(theme: Int = 0) = mainContextView(theme) {}

inline fun ViewManager.mainContextView(theme: Int = 0, init: MainContextView.() -> Unit): MainContextView {
    return ankoView({ MainContextView(it) }, theme, init)
}
</code>```

答:
I found my problem,  it had to do with my subView being defined as a subclass of View/ViewGroup, but not really implementing any of the methods.

As it turns out that was not really the right direction.  The solution is based on a comment on this issue

Here are some of the key parts of the solution,  I also created a Gist with the full code.

The extension function,  creates an instance of the "SubView" class and then calls the createView() method in the ankoView() method.  It also passes the created instance into the closure that is passed to the extension function, which is key as it allows access to the widgets contained within the view.

```<code>inline fun ViewManager.mainContentView(theme: Int = 0) = mainContentView(theme) {}

inline fun ViewManager.mainContentView(theme: Int = 0, init: View.(mainContentView: MainContentView) -> Unit): View {
    val mainContentView = MainContentView()
    return ankoView({ mainContentView.createView(AnkoContext.create(it)) }, theme, { init(mainContentView)} )
}
</code>```

The "content view" creates the layout and holds a reference to the widgets.

```<code>class MainContentView :  AnkoComponent<Context> {

    lateinit var textBox: EditText
    lateinit var button: Button
    lateinit var clickCount: TextView

    override fun createView(ui: AnkoContext<Context>) = with(ui) {
        verticalLayout {
            button = themedButton {
                text = "ok"
            }
            textBox = themedEditText {
                hint = "hi"
            }
            clickCount = themedTextView {
                text = "0"
            }
        }
    }
}
</code>```

In the main view I have fields to refer to the widgets in the "subView" which I then initialize in the closure passed to the mainContentView instance.

```<code>lateinit var textBox: EditText
lateinit var button: Button
lateinit var clickCount: TextView
private lateinit var mainMenu: Menu
lateinit var settingItem: MenuItem
lateinit var otherItem: MenuItem
private lateinit var floatingActionButton: FloatingActionButton

override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
    coordinatorLayout {
        verticalLayout {
            themedAppBarLayout {
                themedToolbar(theme = R.style.Base_ThemeOverlay_AppCompat_Dark_ActionBar) {
                    title = resources.getString(R.string.app_name)
                    popupTheme = R.style.AppTheme
                    mainMenu = menu
                    settingItem = mainMenu.add("My Settings")
                    otherItem = mainMenu.add("My Other")
                }
            }.lparams(width = matchParent, height = wrapContent)
            mainContentView {
                button = it.button
                textBox = it.textBox
                clickCount = it.clickCount
            }.lparams(width = matchParent, height = wrapContent)
        }.lparams(width = matchParent, height = wrapContent)
        floatingActionButton = floatingActionButton {
            imageResource = android.R.drawable.ic_dialog_email
        }.lparams {
            margin = dip(10)
            gravity = Gravity.BOTTOM or Gravity.END
        }
    }
}
</code>```

Title: Why is createView never called?

Body:
My ultimate goal is to be able move my content widgets into a custom view and instantiate that view in an Anko layout in my MainView.  I thought I had this working at one point, but I can't reproduce it.

When I run with the following code, the content in the createView of the MainContextView is never displayed and I never see the message "creating main context view", but I do see the message "main content view".

I start by creating a MainContextView

class MainContextView(context: Context) : ViewGroup(context), AnkoComponent<Context> {

    lateinit var textBox: EditText
    lateinit var button: Button
    lateinit var clickCount: TextView

    override fun createView(ui: AnkoContext<Context>) = with(ui) {
        println("creating main context view")
        verticalLayout {
            themedEditText {
                hint = "hi from main context"
            }
            button = themedButton {
                text = "ok"
            }
            textBox = themedEditText {
                hint = "hi"
            }
            clickCount = themedTextView {
               text = "0"
            }
        }
    }

    override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {
        println("onLayout called")
    }

}

and call it from my main view

class MainView : AnkoComponent<MainActivity> {

    lateinit var mainCtx: MainContextView
    lateinit var textBox: EditText
    lateinit var button: Button
    lateinit var clickCount: TextView
    lateinit var mainMenu: Menu
    lateinit var settingItem: MenuItem
    lateinit var otherItem: MenuItem
    lateinit var floatingActionButton: FloatingActionButton

    override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
        coordinatorLayout {
            verticalLayout {
                themedAppBarLayout {
                    themedToolbar(theme = R.style.Base_ThemeOverlay_AppCompat_Dark_ActionBar) {
                        title = resources.getString(R.string.app_name)
                        popupTheme = R.style.AppTheme
                        mainMenu = menu
                        settingItem = mainMenu.add("My Settings")
                        otherItem = mainMenu.add("My Other")
                    }
                }.lparams(width = matchParent, height = wrapContent)

                // ************************************
                // HERE IS THE CALL TO THE CONTEXT VIEW
                mainCtx = mainContextView { println("main content view ") }
               // *************************************

            }.lparams(width = matchParent, height = wrapContent) {
            }
            floatingActionButton = floatingActionButton {
                imageResource = android.R.drawable.ic_dialog_email
            }.lparams {
                margin = dip(10)
                gravity = Gravity.BOTTOM or Gravity.END
            }
        }
    }
}

The MainView is called set as the content view from the  MainActivity

class MainActivity : AppCompatActivity() {

    private lateinit var presenter: MainPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val mainView = MainView()
        mainView.setContentView(this)
        presenter = MainPresenter(mainView)

    }

}

And finally the ViewManger extensions

inline fun ViewManager.mainContextView(theme: Int = 0) = mainContextView(theme) {}

inline fun ViewManager.mainContextView(theme: Int = 0, init: MainContextView.() -> Unit): MainContextView {
    return ankoView({ MainContextView(it) }, theme, init)
}

Body:
I found my problem,  it had to do with my subView being defined as a subclass of View/ViewGroup, but not really implementing any of the methods.

As it turns out that was not really the right direction.  The solution is based on a comment on this issue

Here are some of the key parts of the solution,  I also created a Gist with the full code.

The extension function,  creates an instance of the "SubView" class and then calls the createView() method in the ankoView() method.  It also passes the created instance into the closure that is passed to the extension function, which is key as it allows access to the widgets contained within the view.

inline fun ViewManager.mainContentView(theme: Int = 0) = mainContentView(theme) {}

inline fun ViewManager.mainContentView(theme: Int = 0, init: View.(mainContentView: MainContentView) -> Unit): View {
    val mainContentView = MainContentView()
    return ankoView({ mainContentView.createView(AnkoContext.create(it)) }, theme, { init(mainContentView)} )
}

The "content view" creates the layout and holds a reference to the widgets.

class MainContentView :  AnkoComponent<Context> {

    lateinit var textBox: EditText
    lateinit var button: Button
    lateinit var clickCount: TextView

    override fun createView(ui: AnkoContext<Context>) = with(ui) {
        verticalLayout {
            button = themedButton {
                text = "ok"
            }
            textBox = themedEditText {
                hint = "hi"
            }
            clickCount = themedTextView {
                text = "0"
            }
        }
    }
}

In the main view I have fields to refer to the widgets in the "subView" which I then initialize in the closure passed to the mainContentView instance.

lateinit var textBox: EditText
lateinit var button: Button
lateinit var clickCount: TextView
private lateinit var mainMenu: Menu
lateinit var settingItem: MenuItem
lateinit var otherItem: MenuItem
private lateinit var floatingActionButton: FloatingActionButton

override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
    coordinatorLayout {
        verticalLayout {
            themedAppBarLayout {
                themedToolbar(theme = R.style.Base_ThemeOverlay_AppCompat_Dark_ActionBar) {
                    title = resources.getString(R.string.app_name)
                    popupTheme = R.style.AppTheme
                    mainMenu = menu
                    settingItem = mainMenu.add("My Settings")
                    otherItem = mainMenu.add("My Other")
                }
            }.lparams(width = matchParent, height = wrapContent)
            mainContentView {
                button = it.button
                textBox = it.textBox
                clickCount = it.clickCount
            }.lparams(width = matchParent, height = wrapContent)
        }.lparams(width = matchParent, height = wrapContent)
        floatingActionButton = floatingActionButton {
            imageResource = android.R.drawable.ic_dialog_email
        }.lparams {
            margin = dip(10)
            gravity = Gravity.BOTTOM or Gravity.END
        }
    }
}


来源: stackexchange

问:
Curl API request value in body always null
I have the following controller  I am trying to use Curl to test it.  The problem is that fiscalId is always null its not reading my post body from curl.

Controler:

```<code>  [Route("api/token")]
  public class TokenController : Controller
  {
    [HttpPost("changefiscal")]
    [Authorize]
    public async Task<ActionResult> ChangeFiscal([FromBody] long fiscalId)
    {
      //fiscalId is always 0
    }
  }
</code>```

I have checked the documentation here which says to use the -d parameter and post it as a json object. Unfortunately thats not working

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/data

I have tried

```<code>curl -d "fiscalId=21875" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal
</code>```

and

```<code>curl -d "{"fiscalId":"21875"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal
</code>```

and

```<code>curl -d "{"fiscalId":"21875"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal
</code>```

and

```<code>curl -d "{\"fiscalId\":\"21875\"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal
</code>```

and everything else i can think of

I can see in the log that it appears to be sending it

Rebuilt URL to: POST/

timeout on name lookup is not supported

getaddrinfo(3) failed for POST:80

Couldn't resolve host 'POST'

Closing connection 0 curl: (6) Couldn't resolve host 'POST'

timeout on name lookup is not supported

Trying ::1...

TCP_NODELAY set

Trying 127.0.0.1...

TCP_NODELAY set

Connected to localhost (127.0.0.1) port 5000 (#1)

POST /api/token/changefiscal HTTP/1.1
    Host: localhost:5000
    User-Agent: curl/7.53.1
    Accept: /
    Content-Type: application/json
    Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjI2OTAzNzc0NjYyNzc4RDM1MzE2QUUwQUU1MjIyQUU1REIzM0M0NUEiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJKcEEzZEdZbmVOTlRGcTRLNVNJcTVkc3p4Rm8ifQ.eyJuYmYiOjE1MTA1NjcxNzMsImV4cCI6MTUxMDU3MDc3MywiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJ0ZXN0YXBpIl0sImNsaWVudF9pZCI6IlNlcnZpY2VBY2NvdW50QWNjZXNzIiwic3ViIjoiMjEyNDg1ODIiLCJhdXRoX3RpbWUiOjE1MTA1NjcxNzMsImlkcCI6ImxvY2FsIiwibmFtZSI6ImxpbGF3IiwiZS1tYWlsIjoibGlsYXdAZWcuZGsiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwidGVzdGFwaSJdLCJhbXIiOlsicGFzc3dvcmQiXX0.Q_oJ-xOIKdTtGoRqJbtNjwLV82cQQLhJUVl2Ey-4riZdp45rPIrmfOw9VdknUOLpm8RYZ0iLFC31gCpn1vKb4zLiTmBuTuzYsKxnAvf-UkCj1L8soH4W2lCvx560bZeS7B67tJ4nK9t36OiMLQY4m-_NRTSRBs5QtsXBd5VQGPsTpxf_MxVbQm6Hj6Ot3FGRIa08gmwD3iEr9vsCU6732InbGzU26wtm-WLWp_A_k66Z29G8ms_U8x6gg-aOlQG9_0v_DEjTXCkKNcgWoL0IvaCC0psiYkdIjQxaOwz-e_fcqXpKEFmuoSqmGd1l-eMl3HimOomdOHwqploWGxnJ4Q
    Content-Length: 7

upload completely sent off: 7 out of 7 bytes

However when i check fiscalId its always 0 i even tried to change fiscalId to a string and its just null.

答:
Finally after more then an hour of playing with this I got it even though the content-Type is json its just sent as a string <code>"'21875'"</code>  even though all the documentation shows sending it as JSon.  For some reason the API isnt able to read it as a JSon Object but expects it just to be sent as a string. </p>

```<code>curl POST -v -d "'21875'" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" http://localhost:5000/api/token/changefiscal
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following controller  I am trying to use Curl to test it.  The problem is that fiscalId is always null its not reading my post body from curl.

Controler:

  [Route("api/token")]
  public class TokenController : Controller
  {
    [HttpPost("changefiscal")]
    [Authorize]
    public async Task<ActionResult> ChangeFiscal([FromBody] long fiscalId)
    {
      //fiscalId is always 0
    }
  }

I have checked the documentation here which says to use the -d parameter and post it as a json object. Unfortunately thats not working

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/data

I have tried

curl -d "fiscalId=21875" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal

and

curl -d "{"fiscalId":"21875"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal

and

curl -d "{"fiscalId":"21875"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal

and

curl -d "{\"fiscalId\":\"21875\"}" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" -X POST -i http://localhost:5000/api/token/changefiscal

and everything else i can think of

I can see in the log that it appears to be sending it

Rebuilt URL to: POST/

timeout on name lookup is not supported

getaddrinfo(3) failed for POST:80

Couldn't resolve host 'POST'

Closing connection 0 curl: (6) Couldn't resolve host 'POST'

timeout on name lookup is not supported

Trying ::1...

TCP_NODELAY set

Trying 127.0.0.1...

TCP_NODELAY set

Connected to localhost (127.0.0.1) port 5000 (#1)

POST /api/token/changefiscal HTTP/1.1
    Host: localhost:5000
    User-Agent: curl/7.53.1
    Accept: /
    Content-Type: application/json
    Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjI2OTAzNzc0NjYyNzc4RDM1MzE2QUUwQUU1MjIyQUU1REIzM0M0NUEiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJKcEEzZEdZbmVOTlRGcTRLNVNJcTVkc3p4Rm8ifQ.eyJuYmYiOjE1MTA1NjcxNzMsImV4cCI6MTUxMDU3MDc3MywiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJ0ZXN0YXBpIl0sImNsaWVudF9pZCI6IlNlcnZpY2VBY2NvdW50QWNjZXNzIiwic3ViIjoiMjEyNDg1ODIiLCJhdXRoX3RpbWUiOjE1MTA1NjcxNzMsImlkcCI6ImxvY2FsIiwibmFtZSI6ImxpbGF3IiwiZS1tYWlsIjoibGlsYXdAZWcuZGsiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwidGVzdGFwaSJdLCJhbXIiOlsicGFzc3dvcmQiXX0.Q_oJ-xOIKdTtGoRqJbtNjwLV82cQQLhJUVl2Ey-4riZdp45rPIrmfOw9VdknUOLpm8RYZ0iLFC31gCpn1vKb4zLiTmBuTuzYsKxnAvf-UkCj1L8soH4W2lCvx560bZeS7B67tJ4nK9t36OiMLQY4m-_NRTSRBs5QtsXBd5VQGPsTpxf_MxVbQm6Hj6Ot3FGRIa08gmwD3iEr9vsCU6732InbGzU26wtm-WLWp_A_k66Z29G8ms_U8x6gg-aOlQG9_0v_DEjTXCkKNcgWoL0IvaCC0psiYkdIjQxaOwz-e_fcqXpKEFmuoSqmGd1l-eMl3HimOomdOHwqploWGxnJ4Q
    Content-Length: 7

upload completely sent off: 7 out of 7 bytes

However when i check fiscalId its always 0 i even tried to change fiscalId to a string and its just null.

Body:
Finally after more then an hour of playing with this I got it even though the content-Type is json its just sent as a string "'21875'"  even though all the documentation shows sending it as JSon.  For some reason the API isnt able to read it as a JSon Object but expects it just to be sent as a string.

curl POST -v -d "'21875'" -H "Content-Type: application/json" -H "Authorization: Bearer XXX" http://localhost:5000/api/token/changefiscal


问:
.net SQL Server stored procs wrapper class structure
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

```<code>void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}
</code>```

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?

答:
Something like this should do:

```<code>void RunStoredProc(string storedProcName, IDictionary<string, object> args)
{
    using (SqlConnection conn = new SqlConnection(connStr))
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = storedProcName;
        cmd.CommandType = CommandType.StoredProcedure;

        foreach (KeyValuePair<string, object> kvp in args)
        {
            cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
        }

        conn.Open();
        cmd.ExecuteNonQuery();
    }
}
</code>```

The connection object itself would probably also be better off as a parameter to this helper method, so you could make it static. It might be interesting to write it as an extension method on SqlConnection.

I would keep the exception handling in your RunStoredProc1 method or even more likely: in the methods that call RunStoredProc1, because exception handling will likely differ on a case by case basis.

```<code>void RunStoredProc1(object input1)
{
    var args = new Dictionary<string, object>()
               {
                   { "input1", input1 }
               };

    try
    {
        RunStoredProc("storedProc1", args);
    }
    catch (Exception ex)
    {
        // Handle exception properly
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?

Body:
Something like this should do:

void RunStoredProc(string storedProcName, IDictionary<string, object> args)
{
    using (SqlConnection conn = new SqlConnection(connStr))
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = storedProcName;
        cmd.CommandType = CommandType.StoredProcedure;

        foreach (KeyValuePair<string, object> kvp in args)
        {
            cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
        }

        conn.Open();
        cmd.ExecuteNonQuery();
    }
}

The connection object itself would probably also be better off as a parameter to this helper method, so you could make it static. It might be interesting to write it as an extension method on SqlConnection.

I would keep the exception handling in your RunStoredProc1 method or even more likely: in the methods that call RunStoredProc1, because exception handling will likely differ on a case by case basis.

void RunStoredProc1(object input1)
{
    var args = new Dictionary<string, object>()
               {
                   { "input1", input1 }
               };

    try
    {
        RunStoredProc("storedProc1", args);
    }
    catch (Exception ex)
    {
        // Handle exception properly
    }
}


问:
Converting a Vision VNTextObservation to a String
I'm looking through the Apple's Vision API documentation and I see a couple of classes that relate to text detection in UIImages:

1) class VNDetectTextRectanglesRequest

2) class VNTextObservation

It looks like they can detect characters, but I don't see a means to do anything with the characters. Once you've got characters detected, how would you go about turning them into something that can be interpreted by NSLinguisticTagger?

Here's a post that is a brief overview of Vision.

Thank you for reading.

答:
I'm using Google's Tesseract OCR engine to convert the images into actual strings. You'll have to add it to your Xcode project using cocoapods. Although Tesseract will perform OCR even if you simply feed the image containing texts to it, the way to make it perform better/faster is to use the detected text rectangles to feed pieces of the image that actually contain text, which is where Apple's Vision Framework comes in handy.
Here's a link to the engine:
Tesseract OCR
And here's a link to the current stage of my project that has text detection + OCR already implemented:
Out Loud - Camera to Speech
Hope these can be of some use. Good luck!</p>


问:
Initial query resent the data when client got reconnect
I tried to use contentious query to monitor a cache and set initial query, LocalListener and RemoteFilter as example did.

The issue I met is when client reconnect to Ignite cluster, the initial query will query the data from cache which the client might already got before.

I tried to use unchanged ID or instance name

```<code>cfg.setConsistentId("de01");
cfg.setIgniteInstanceName("test1");
</code>```

but does not work.

Is any way to solve this issue?

Many thanks,

答: On disconnect phase of reconnect server closes query listener and loses information which updates were already sent to client. The only way not to miss some updates in that situation - run initial query again. </p>

Body:
I tried to use contentious query to monitor a cache and set initial query, LocalListener and RemoteFilter as example did.

The issue I met is when client reconnect to Ignite cluster, the initial query will query the data from cache which the client might already got before.

I tried to use unchanged ID or instance name

cfg.setConsistentId("de01");
cfg.setIgniteInstanceName("test1");

but does not work.

Is any way to solve this issue?

Many thanks,


问:
Django __str__ returned non-string (type NoneType)
I am getting __str__ returned non-string (type NoneType) error at edit  Product Model object

Product Model

```<code>class Product(models.Model):
    ProductName = models.CharField(blank=True, max_length=250)
    Price = models.FloatField(blank=True, default=9.99)
    Tax = models.FloatField(blank=True, null=True, default=0.0)
    StoreId = models.IntegerField(blank=True, null=True)
    RelatedStore = models.ForeignKey(Store, blank=True, null=True)
    Category = models.CharField(max_length=200,
                                blank=True, null=True,
                                default='No Specific Category')
    ProductImage = models.CharField(max_length=400, null=True, blank=True)
    Features = models.TextField(blank=True, null=True)
    ProductSize = models.IntegerField(blank=True, null=True, default=3)
    FavoriteField = models.BooleanField(blank=True, default=False)
    Active = models.BooleanField(blank=True, default=True)

    def __unicode__(self):
        return self.ProductName

    def __str__(self):
        return self.ProductName
</code>```

Any helpful answer will be appreciated.

答:
you can try:</p>

```<code>def __str__(self):
    return str(self.ProductName) if self.ProductName else ''
</code>```

Body:
I am getting __str__ returned non-string (type NoneType) error at edit  Product Model object

Product Model

class Product(models.Model):
    ProductName = models.CharField(blank=True, max_length=250)
    Price = models.FloatField(blank=True, default=9.99)
    Tax = models.FloatField(blank=True, null=True, default=0.0)
    StoreId = models.IntegerField(blank=True, null=True)
    RelatedStore = models.ForeignKey(Store, blank=True, null=True)
    Category = models.CharField(max_length=200,
                                blank=True, null=True,
                                default='No Specific Category')
    ProductImage = models.CharField(max_length=400, null=True, blank=True)
    Features = models.TextField(blank=True, null=True)
    ProductSize = models.IntegerField(blank=True, null=True, default=3)
    FavoriteField = models.BooleanField(blank=True, default=False)
    Active = models.BooleanField(blank=True, default=True)

    def __unicode__(self):
        return self.ProductName

    def __str__(self):
        return self.ProductName

Any helpful answer will be appreciated.

Body:
you can try:

def __str__(self):
    return str(self.ProductName) if self.ProductName else ''


问:
The remote server returned an error: (403) Forbidden
I've written an app that has worked fine for months, in the last few days I've been getting the error below on the installed version only.

If I run the source code in VS everything works fine. Also, the .exe in the bin folders work fine. It's only the installed version which generates the error, if I recompile and reinstall I get the same error.

I'm a bit stumped as to what's causing this and hoped for a few pointers. It seems to be a WebRequest response through IE is not being returned but I'm stumped as to why it works fine in VS without any errors. Are there any new IE security measures/polices that may cause this?

Things I've tried so far include:

Disabled all AntiVirus & Firewall

Run as Administrator

The Exception:

```<code>Exception: System.Windows.Markup.XamlParseException: The invocation of the constructor on type 'XApp.MainWindow' that matches the specified binding constraints threw an exception. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at XApp.HtmlRequest.getHtml(Uri uri) in J:\Path\MainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:\Path\MainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:\Path\MainWindow.xaml.cs:line 124
   --- End of inner exception stack trace ---
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
   at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
   at System.Windows.Application.DoStartup()
   at System.Windows.Application.<.ctor>b__1(Object unused)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
Exception: System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at XApp.HtmlRequest.getHtml(Uri uri) in J:\Path\MainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:\Path\MainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:\Path\MainWindow.xaml.cs:line 124
</code>```

EDIT:

This is installed as a standalone app. When I've run as Administrator, I've opened the program folder and run the exe as administrator rather than the shortcut.

The code that causes the issue is this

```<code>private void GetLinks()
{
    //Navigate to front page to Set cookies
    HtmlRequest htmlReq = new HtmlRequest();

    OLinks = new Dictionary<string, List<string>>();

    string Url = "http://www.somesite.com/somepage";
    CookieContainer cookieJar = new CookieContainer();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
    request.CookieContainer = cookieJar;

    request.Accept = @"text/html, application/xhtml+xml, */*";
    request.Referer = @"http://www.somesite.com/";
    request.Headers.Add("Accept-Language", "en-GB");
    request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
    request.Host = @"www.somesite.com";

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    String htmlString;
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        htmlString = reader.ReadToEnd();
    }

    //More Code

 }
</code>```

答:
Setting:

```<code>request.Referer = @"http://www.somesite.com/";
</code>```

and adding cookies than worked for me

Body:
I've written an app that has worked fine for months, in the last few days I've been getting the error below on the installed version only.

If I run the source code in VS everything works fine. Also, the .exe in the bin folders work fine. It's only the installed version which generates the error, if I recompile and reinstall I get the same error.

I'm a bit stumped as to what's causing this and hoped for a few pointers. It seems to be a WebRequest response through IE is not being returned but I'm stumped as to why it works fine in VS without any errors. Are there any new IE security measures/polices that may cause this?

Things I've tried so far include:

Disabled all AntiVirus & Firewall

Run as Administrator

The Exception:

Exception: System.Windows.Markup.XamlParseException: The invocation of the constructor on type 'XApp.MainWindow' that matches the specified binding constraints threw an exception. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at XApp.HtmlRequest.getHtml(Uri uri) in J:\Path\MainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:\Path\MainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:\Path\MainWindow.xaml.cs:line 124
   --- End of inner exception stack trace ---
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
   at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
   at System.Windows.Application.DoStartup()
   at System.Windows.Application.<.ctor>b__1(Object unused)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
Exception: System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at XApp.HtmlRequest.getHtml(Uri uri) in J:\Path\MainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:\Path\MainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:\Path\MainWindow.xaml.cs:line 124

EDIT:

This is installed as a standalone app. When I've run as Administrator, I've opened the program folder and run the exe as administrator rather than the shortcut.

The code that causes the issue is this

private void GetLinks()
{
    //Navigate to front page to Set cookies
    HtmlRequest htmlReq = new HtmlRequest();

    OLinks = new Dictionary<string, List<string>>();

    string Url = "http://www.somesite.com/somepage";
    CookieContainer cookieJar = new CookieContainer();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
    request.CookieContainer = cookieJar;

    request.Accept = @"text/html, application/xhtml+xml, */*";
    request.Referer = @"http://www.somesite.com/";
    request.Headers.Add("Accept-Language", "en-GB");
    request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
    request.Host = @"www.somesite.com";

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    String htmlString;
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        htmlString = reader.ReadToEnd();
    }

    //More Code

 }

Body:
Setting:

request.Referer = @"http://www.somesite.com/";

and adding cookies than worked for me


问:
Web API suddenly returns 403 forbidden after a few successfull requests
I've been working on an ionic application in combination with an ASP.NET Web API. I'm using that API for all the data transfer.

I have been experiencing a problem: after a few successful requests, the API suddenly returns 403 forbidden. It seems like the API has a limitation or something, because it happens when I do multiple requests in a really short time.

The strange thing about this problem is that if I run the Web API locally it works perfectly fine, but if I host it on an external IIS server this problem shows up after a few requests. I end the process on the server to fix it temporary.

I hope some of you guys know this problem.

This might fix a lot for me in the future.

Thanks.

答: The problem was inside my IIS Manager for the ASP.NET Web API. I had to increase the limit of my Dynamic IP Restrictions (DIPR), because the API returned an 403 error after a few requests at the same time. When I increased the limited I noticed that the problem was fixed.</p>


问:
java.lang.ClassCastException: __redirected.__XMLInputFactory cannot be cast to org.codehaus.stax2.XMLInputFactory2
I am migration Java Web Application from jboss 6.0 to wildfly 11. I am getting

"java.lang.ClassCastException: __redirected.__XMLInputFactory cannot
  be cast to org.codehaus.stax2.XMLInputFactory2" while running the code
  on wildfly 11.0.0.Final. Junit tests are working without error.

Looks like there is some dependency issue in wildfly but unable to find any solution. Appreciate any help to resolve this issue..
I have included following woodstox dependencies in pom.

woodstox-core-asl 4.4.1
stax2-api 3.1.4

Thanks
Sanjay

答:
This is caused by duplicate classes in the classpath.

Wildfly ships stax2-api as part of the woodstocks module, see modules/system/layers/base/org/codehaus/woodstox/main/ in the wildfly dist folder.

If you also have it in your application's lib folder, this will cause issues.

The solution is to either set the dependency to <scope>provided</scope> (or build) in pom.xml, or if you really need a special version, exclude wildfly's module via jboss-deployment-structure.xml.

See https://docs.jboss.org/author/display/WFLY10/Class+Loading+in+WildFly for more information on classloading in Wildfly.


问:
Static member functions
After reading sbi and Eli Bendersky's answers in this question I started to wondering what static member functions are for.

A class' friend free function shouldn't be able to do anything a static member function can do? If so, why/when should I prefer a static member function to a friend free one?

答:
There is no added value to static member functions, as you correctly identified. Worse, when used for implementation details this introduce extra dependencies (in term of compilation).

The only use that could not be emulated with an anonymous free-function, is the protected access, that is, a derived class accessing a parent static function. However, this is never required: you can just make it a regular member function instead (I assume you don't have global state, otherwise the static/friend distinction is not of immediate concern).

The use of static functions in template meta-programming has been evoked... however it is very similar to the inner types issue: it makes it difficult to provide a default version. On the other hand, a suitably defined free function (which takes the type as a pointer), can propose a template version:

```<code>struct some_traits
{
  static void doStuff();
};

// versus

struct some_traits {};

void doStuff(some_traits*);

// and the default: void doStuff(...);
</code>```

And of course, there is always the question of why this should be a static function, when a member function would provide more flexibility to the user. To this effect I would cite the move the Standard Committee made with the Allocator concept: stateful allocators are now authorized, which gives us the opportunity of packing the nodes of a given map in a same page rather than spreading them all over the heap.

Finally, there is the interface issue. However it's been a long time already since Sutter advocated that a class and the free functions defined in the same header both constituted the public interface of this class => that is what ADL is for! So it is more something to comfort ancient OO-programmers than a "good practice".

Really, I don't see any benefit from using static member functions. I would like people would think the contrary to propose real cases.

Title: Static member functions

Body:
There is no added value to static member functions, as you correctly identified. Worse, when used for implementation details this introduce extra dependencies (in term of compilation).

The only use that could not be emulated with an anonymous free-function, is the protected access, that is, a derived class accessing a parent static function. However, this is never required: you can just make it a regular member function instead (I assume you don't have global state, otherwise the static/friend distinction is not of immediate concern).

The use of static functions in template meta-programming has been evoked... however it is very similar to the inner types issue: it makes it difficult to provide a default version. On the other hand, a suitably defined free function (which takes the type as a pointer), can propose a template version:

struct some_traits
{
  static void doStuff();
};

// versus

struct some_traits {};

void doStuff(some_traits*);

// and the default: void doStuff(...);

And of course, there is always the question of why this should be a static function, when a member function would provide more flexibility to the user. To this effect I would cite the move the Standard Committee made with the Allocator concept: stateful allocators are now authorized, which gives us the opportunity of packing the nodes of a given map in a same page rather than spreading them all over the heap.

Finally, there is the interface issue. However it's been a long time already since Sutter advocated that a class and the free functions defined in the same header both constituted the public interface of this class => that is what ADL is for! So it is more something to comfort ancient OO-programmers than a "good practice".

Really, I don't see any benefit from using static member functions. I would like people would think the contrary to propose real cases.


问:
Laravel - getting data from a few tables ordered by created_at (not related)
I want to get data from a few tables (not related) and order it by created_at column.

For example I have tables:

posts:
id
title
text
created_at

products:
id
name
description
created_at

users:
id
name
email
created_at

As you see, on every table we have created_at, I want to get data from these tables sorted by created_at in one query. It will be similar to wall on Facebook.

答:
As commented by some, you can't do this in a single query.

Use Collections instead.

```<code>$posts = App\Post::all();
$products = App\Product::all();
$users = App\User::all();

$collection = new \Illuminate\Support\Collection();
$collection = $collection->merge($posts)
                         ->merge($products)
                         ->merge($users)
                         ->sortBy('created_at');
</code>```

Then use the $collection object to display the data.

Body:
As commented by some, you can't do this in a single query.

Use Collections instead.

$posts = App\Post::all();
$products = App\Product::all();
$users = App\User::all();

$collection = new \Illuminate\Support\Collection();
$collection = $collection->merge($posts)
                         ->merge($products)
                         ->merge($users)
                         ->sortBy('created_at');

Then use the $collection object to display the data.


问:
Grails 3 fontawesome setup
i'm attempting to include fontawesome (fa) in my grails 3 project. I saw for grails2 there was a plugin for this, but the configuration and explanation for how to install this plugin didn't seem to work in grails 3.

So I tried to add fa more or less manually by creating an assets/fonts/ directory, and placing the fonts in there, added the css to my stylesheets directory and referenced it from the application.css. When I run in Idea via grails run-app all the fa resources show up fine.

However when I package a war file to run in tomcat, none of the fa resources show up at all. When I look at the compiled style sheet that is created for the app, the ../fonts/ that I put in my fa style sheet has been removed, and then the font files can't be found.

```<code>@font-face {font-family: 'FontAwesome';src: url('fontawesome-webfont-32400f4e08932a94d8bfd2422702c446.eot?v=4.5.0')
</code>```

This generated font resource, and all the others are not resolvable(404) from the root of my application, but are resolvable if I prepend /assets/ to them.

What am I missing configuration wise with the asset pipeline to get this working?

答:
Download Fonts from this link enter link description here and in that add Fonts folder only to assets in grail app.Add below code:

```<code>assets {
minifyJs = true
minifyCss = true
includes = ["fonts/*"]
</code>```

}

Title: Grails 3 fontawesome setup

Body:
i'm attempting to include fontawesome (fa) in my grails 3 project. I saw for grails2 there was a plugin for this, but the configuration and explanation for how to install this plugin didn't seem to work in grails 3.

So I tried to add fa more or less manually by creating an assets/fonts/ directory, and placing the fonts in there, added the css to my stylesheets directory and referenced it from the application.css. When I run in Idea via grails run-app all the fa resources show up fine.

However when I package a war file to run in tomcat, none of the fa resources show up at all. When I look at the compiled style sheet that is created for the app, the ../fonts/ that I put in my fa style sheet has been removed, and then the font files can't be found.

@font-face {font-family: 'FontAwesome';src: url('fontawesome-webfont-32400f4e08932a94d8bfd2422702c446.eot?v=4.5.0')

This generated font resource, and all the others are not resolvable(404) from the root of my application, but are resolvable if I prepend /assets/ to them.

What am I missing configuration wise with the asset pipeline to get this working?

Body:
Download Fonts from this link enter link description here and in that add Fonts folder only to assets in grail app.Add below code:

assets {
minifyJs = true
minifyCss = true
includes = ["fonts/*"]

}


问:
RSpec How to add meta data for helper
I want to add custom tag for my rspec test. Example:

```<code>it 'should do something', transactional: false do
end
</code>```

The custom tag is transactional: false.

And then in my database_cleaner_helper.rb, I can write something like below.

```<code>before(:suite) do
    if (it.tags[:transactional] == true)
    else
    end
end
</code>```

Can you please give me an example?

答:
The right syntax would be like

```<code>before(:suite, transactional: true) do
  # do something
end
</code>```

See https://relishapp.com/rspec/rspec-core/docs/hooks/filters

Title: RSpec How to add meta data for helper

Body:
I want to add custom tag for my rspec test. Example:

it 'should do something', transactional: false do
end

The custom tag is transactional: false.

And then in my database_cleaner_helper.rb, I can write something like below.

before(:suite) do
    if (it.tags[:transactional] == true)
    else
    end
end

Can you please give me an example?

Body:
The right syntax would be like

before(:suite, transactional: true) do
  # do something
end

See https://relishapp.com/rspec/rspec-core/docs/hooks/filters


问:
How to apply filter on finch endpoint without using finagle filters?
I have more than one endpoints.I am able to apply common filters on endpoints using finagle filter.But now I want to apply a filter on a specific endpoint.
How can I achieve this? </p>

答:
I had a similar question (for basic authentication filtering) that popped up while playing with redbubble's finch template which I partially solved in the following way:

```<code>class AuthenticatedEndpoint[A](e: Endpoint[A]) extends Endpoint[A] { self =>

final def apply(mapper: Mapper[A]): Endpoint[mapper.Out] = mapper(self)

final def apply(input: Input): Endpoint.Result[A] =
  if (checkSession(input.request)) {
    e(input)
  } else {
    // TODO return something meaningful to the caller (if possible?)
    EndpointResult.Skipped
  }
}

object AuthenticatedEndpoint {

  def validSession[A](e: Endpoint[A]): Endpoint[A] = new AuthenticatedEndpoint(e)

}
</code>```

(with checkSession returning true if all is well with the request). Then my api is defined as:

```<code>val api = "v1" :: loginApi :+: validSession(peopleApi :+: healthApi :+: adminApi)
</code>```

This works well in the sense that requests without a session won't have access to the endpoints passed to validSession, but I have yet to find an easy way to return an error message to the caller, and I'd be curious to know if I chose the right path here.

Body:
I had a similar question (for basic authentication filtering) that popped up while playing with redbubble's finch template which I partially solved in the following way:

class AuthenticatedEndpoint[A](e: Endpoint[A]) extends Endpoint[A] { self =>

final def apply(mapper: Mapper[A]): Endpoint[mapper.Out] = mapper(self)

final def apply(input: Input): Endpoint.Result[A] =
  if (checkSession(input.request)) {
    e(input)
  } else {
    // TODO return something meaningful to the caller (if possible?)
    EndpointResult.Skipped
  }
}

object AuthenticatedEndpoint {

  def validSession[A](e: Endpoint[A]): Endpoint[A] = new AuthenticatedEndpoint(e)

}

(with checkSession returning true if all is well with the request). Then my api is defined as:

val api = "v1" :: loginApi :+: validSession(peopleApi :+: healthApi :+: adminApi)

This works well in the sense that requests without a session won't have access to the endpoints passed to validSession, but I have yet to find an easy way to return an error message to the caller, and I'd be curious to know if I chose the right path here.


问:
How to create piano UI in iPhone?
I am a beginner in creating such piano based UI application. I am developing an application in which I have to use Piano. How to create piano UI in iPhone? How to create it using Interface builder ? or is there any other way to create the piano?</p>

答: You can get piano key sounds from here: http://www.sonicspot.com/news/free-musical-instrument-samples.html . The files are quite big, you can cut them with Audacity and export to .wav</p>

ContentLicense: CC BY-SA 4.0

Title: How to create piano UI in iPhone?


问:
date data loading from backend set bootstrap datepicker in correct format
I use bootstrap datepicker plugin for my calendar and I have a little problem with formatting my loading data, I want to get my date format in this type dd/M/yyyy = 15/Nov/2017 when my page loaded

Could you help me, thank you very much!

The Step 1) is my static HTML,
The Step 2) when my page was loaded

Step 1)

```<code><input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate">
</code>```

Step 2)

```<code><input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="06.06.2017 00:00:00">
</code>```

jsfiddle

答:
Try setting value in the required format.
like</p>

```<code><input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate.ToString("dd/MMM/yyyy");">
</code>```

Body:
I use bootstrap datepicker plugin for my calendar and I have a little problem with formatting my loading data, I want to get my date format in this type dd/M/yyyy = 15/Nov/2017 when my page loaded

Could you help me, thank you very much!

The Step 1) is my static HTML,
The Step 2) when my page was loaded

Step 1)

<input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate">

Step 2)

<input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="06.06.2017 00:00:00">

jsfiddle

Body:
Try setting value in the required format.
like

<input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate.ToString("dd/MMM/yyyy");">


问:
What is the difference between starting Choregraphe application with a trigger sentence and starting in a different way?
I have a variety of apps that can be started in one of three ways:

1. from the robots's tablet - when the user clicks the icon I use runBehaviour or startBehaviour

2. from a dialog - trigger an event or start a behaviour

3. with trigger sentences

When the app runs, I want the robot to stay focused until it's over. That's why I stop modules such as the ALBasicAwarness and ALSpeechRecognition. However, if someone touches the robot on the head, the dialog_touch from the basic channel is triggered and Pepper begins to listen and answer questions, even though he has not left the application yet. Тhis happens if the app is started in a way (1) or (2) but if it is started in a way (3) (with trigger sentences) the robot remains focused at all times.

I want to know what is the difference between starting with a trigger sentence and other ways and how to run the application so the robot does not focus off.

答:
I cannot tell you how the system works in detail, but I would guess that both the dialog and a trigger sentence use ALBehaviorManager.startBehaviorin the background. If you want to make sure that nothing interrupts your application, you must set the state of your app (i.e. behavior) to 'Interactive'. Only one behavior can be running as interactive.

Details about states: http://doc.aldebaran.com/2-5/ref/life/state_machine_management.html?#states


问:
Longest sequence of number in two arrays
I have two array that initialize in random number between 0-9

I need to find the longest same sequence that exist in both of them.

For example

```<code>var arrFirst = [8,5,3,0,3,1,8,2,8,7,3,5,4,0,8,5,7,3,1]
var arrSecond = [8,5,4,0,2,9,4,3,6,9,2,3,1,8,2,8,7,3,3]
</code>```

The result array need to contain the longest sequence that appear in both array

```<code>var arrResult = [3,1,8,2,8,7,3]
</code>```

In this example we have sequence right on start [8, 5] but it's not the longest one.

Could you please provide some code that would help me?

Thanx

答:
Use like this to search maximum length exist in second array

var arrFirst = [8,5,3,0,3,1,8,2,8,7,3,5,4,0,8,5,7,3,1];
var arrSecond = [8,5,4,0,2,9,4,3,6,9,2,3,1,8,2,8,7,3,3];
var firstStr = arrFirst.join("");
var secondStr = arrSecond.join("");
var combinations = getCombination(firstStr);
combinations = combinations.sort(function(a, b){
  return b.length - a.length;
});
for(var i in combinations){
  if(secondStr.indexOf(combinations[i]) !== -1){
    console.log(combinations[i]+" found with length : "+combinations[i].length);
    console.log(combinations[i].split(""));
    break;
  }
}

function getCombination(str) {
    var fn = function(active, rest, a) {
        if (!active && !rest)
            return;
        if (!rest) {
            if(firstStr.search(active) !== -1){
              a.push(active);
            }
        } else {
            fn(active + rest[0], rest.slice(1), a);
            fn(active, rest.slice(1), a);
        }
        return a;
    }
    return fn("", str, []);
}```

Body:
I have two array that initialize in random number between 0-9

I need to find the longest same sequence that exist in both of them.

For example

var arrFirst = [8,5,3,0,3,1,8,2,8,7,3,5,4,0,8,5,7,3,1]
var arrSecond = [8,5,4,0,2,9,4,3,6,9,2,3,1,8,2,8,7,3,3]

The result array need to contain the longest sequence that appear in both array

var arrResult = [3,1,8,2,8,7,3]

In this example we have sequence right on start [8, 5] but it's not the longest one.

Could you please provide some code that would help me?

Thanx


问:
Not able to run angular 2 material plunker example
I am trying to follow the https://material.angular.io/components link to learn some material concepts. However when I am running their examples on plunker i keep getting an error:

The exapmles used to work just fine a week before but why this error now.

答:
First, go back to the documentation page you were reading and hard-refresh (SHIFT + reload or clear your cache).  The documentation caches aggressively and doesn't show the latest API; this is a known issue and you can easily wind up looking at old code that doesn't work anymore.

Second, check your adblocker.  Mine was stopping a request for pubfig (?) that resulted in the same error you're seeing above.


问:
BatchUpdateException: the batch will not terminate
I have an application which processes a very large file and sends data to an oracle database (using Java 6, oracle 9).

In a loop, I use a PreparedStatement ps and create all SQL statements generated with ps.addBatch().

I have a situation where a BatchUpdateException bue is thrown somewhere during the ps.executeBatch(). At that point, the batch stops to be executed.

I'd like the batch execution to continue, so that I can then check on failed updates in a method processUpdateCounts(bue.getUpdateCounts()).

The javadoc about class BatchUpdateException says:

After a command in a batch update
  fails to execute properly and a
  BatchUpdateException is thrown, the
  driver may or may not continue to
  process the remaining commands in the
  batch.

Is there a way to enforce continuation or do I need to alter my program so that it will execute the statement individually?

答:
there is a workaround that would allow you to use the batch feature. Instead of executing a simple INSERT statement, you can execute a PL/SQL block that will deal with the error appropriately:

```<code>BEGIN
   INSERT INTO your_table VALUES (?,?,...?);
EXCEPTION
   WHEN OTHERS THEN
      /* deal with the error. For example, log the error id and error msg
         so that you can list them after the batch */
      INSERT INTO error_table VALUES (?, sqlerrm);
END
</code>```

The performance should be on par with the batch insert (should be faster than individual execution of the statements). You could also call a stored procedure instead of a PL/SQL block.

Body:
there is a workaround that would allow you to use the batch feature. Instead of executing a simple INSERT statement, you can execute a PL/SQL block that will deal with the error appropriately:

BEGIN
   INSERT INTO your_table VALUES (?,?,...?);
EXCEPTION
   WHEN OTHERS THEN
      /* deal with the error. For example, log the error id and error msg
         so that you can list them after the batch */
      INSERT INTO error_table VALUES (?, sqlerrm);
END

The performance should be on par with the batch insert (should be faster than individual execution of the statements). You could also call a stored procedure instead of a PL/SQL block.


问:
When activity is recreated, adding layer has no effect
I have this issue: after screen orientation I try to (re)add Layer that I have previously removed in onDestroy(). If I look for a Layer in mapBoxMap.getLayer(String id), I get null, even if just before that I added this layer to the map. Logs show nothing suspicious.

答:
Add this to the manifest, where  ".MainActivity" is the Activity name,

```<code><activity android:name=".MainActivity"
                android:configChanges="orientation|screenSize"
              / >
</code>```

Body:
Add this to the manifest, where  ".MainActivity" is the Activity name,

<activity android:name=".MainActivity"
                android:configChanges="orientation|screenSize"
              / >


问:
NUnit Unit tests not showing in Test Explorer with Test Adapter installed
I've installed NUnit Test Adapter for VS2012 + 2013.  When I first installed the Adapter tests were showing up, but they stopped showing up for some reason today.  After building, rebuilding, cleaning, restarting, nothing shows up in Test Explorer.  Why would this be happening?  I'm using VS2013 Ultimate.</p>

答:
I had this problem too but the cause was different.  I'm using VS2017 with F# 4.0.

Firstly, the console in Visual Studio does not give you enough details why the tests could not be found; it will just fail to the load the DLL with the tests.  So use NUnit3console.exe on the command line as this gives you more details.

In my case, it was because the test adapter was looking for a newer version of the F# Core DLL (4.4.1.0) (F# 4.1) whereas I'm still using 4.4.0.0 (F# 4.0).  So I just added this to the app.config of the test project:-

```<code>  <dependentAssembly>
    <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-65535.65535.65535.65535" newVersion="4.4.0.0" />
  </dependentAssembly>
</code>```

i.e. redirect to the earlier F# core.

Body:
I had this problem too but the cause was different.  I'm using VS2017 with F# 4.0.

Firstly, the console in Visual Studio does not give you enough details why the tests could not be found; it will just fail to the load the DLL with the tests.  So use NUnit3console.exe on the command line as this gives you more details.

In my case, it was because the test adapter was looking for a newer version of the F# Core DLL (4.4.1.0) (F# 4.1) whereas I'm still using 4.4.0.0 (F# 4.0).  So I just added this to the app.config of the test project:-

  <dependentAssembly>
    <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-65535.65535.65535.65535" newVersion="4.4.0.0" />
  </dependentAssembly>

i.e. redirect to the earlier F# core.


问:
Getting nil response while passing string to another view controller - Swift3
In FirstViewController i'm fetching the response from JSON and want to pass that fetched response to another view controller.Below is the code which i have used so far for parsing and passing the response.

FirstViewController

```<code>var fn:String!  //globally declared variable
</code>```

code i have tried for parsing in FirstViewController

```<code> do {

    let detailsDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary<String, AnyObject> as NSDictionary

    print(detailsDictionary)
    let details = detailsDictionary["Data"] as! [[String:AnyObject]]
    print(details)
    for dtl in details
    {
        self.fn = dtl["Father_Name"] as? String ?? "NA"
        print(self.fn)  //here i'm getting the exact value from JSON
     }

    }
}
</code>```

SecondViewController

In SecondViewController there is a Label called profile_name and want to set that parsed string(fn) as Label's text. for that i declared another variable as global.

```<code>var pname:String!
</code>```

below is the code i have used to fetch the value from FirstViewController.

```<code>viewDidLoad()
{
       let othervc = FirstViewController()
       self.pname = othervc.fn
       self.profile_name.text = self.pname
}
</code>```

Problem : I tried my best efforts to get the desired output but i'm getting nil response.

Please Help.

答:
Your updated code just won't work.

```<code>let othervc = FirstViewController()
</code>```

creates a new instance of FirstViewController (not the one that got the JSON).

You should be handling it something like this:

In FirstViewController

```<code>let fn = dtl["Father_Name"] as? String ?? "NA"
let svc = SecondViewController() // Or maybe instantiate from Storyboard, or maybe you already have a reference to it
svc.pname = fn
present(svc, animated: true, completion: nil)
</code>```

Then in SecondViewController

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    profile_name.text = pname
}
</code>```

I'd suggest you take some time out and re-read Apple's View Controller programming guide.

Original Answer

The problem you have here…

```<code>vcvalue.profile_name.text = fn
</code>```

is that profile_name is nil as the view for the view controller hasn't been loaded at this point.

You should handle this by creating a property in LeftSideMenuViewController

```<code>var name: String?
</code>```

Then set

```<code>vcvalue.name = fn
</code>```

And then in LeftSideMenuViewController

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    profile_name.text = name
}
</code>```

Also, some basic tips…

Don't force unwrap (!) apart from IBOutlets. You may have to write a bit more code, but you will reduce crashes.

Make @IBOutlets private - this will prevent you accidentally assigning to them as you are now

If you're overriding any viewWill/DidDis/Appear methods, you must call super at some point.

You need to re-read the section on switch/case

So this…

```<code>let  a = indexPath.row
switch(a)
    {
    case 0 :
        if(a == 0)
        {
            return 45
        }
        break
     etc
</code>```

could just be…

```<code>switch indexPath.row {
case 0...4:
    return 45
case 5:
    return 50
default:
    break
}
</code>```

Body:
In FirstViewController i'm fetching the response from JSON and want to pass that fetched response to another view controller.Below is the code which i have used so far for parsing and passing the response.

FirstViewController

var fn:String!  //globally declared variable

code i have tried for parsing in FirstViewController

 do {

    let detailsDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary<String, AnyObject> as NSDictionary

    print(detailsDictionary)
    let details = detailsDictionary["Data"] as! [[String:AnyObject]]
    print(details)
    for dtl in details
    {
        self.fn = dtl["Father_Name"] as? String ?? "NA"
        print(self.fn)  //here i'm getting the exact value from JSON
     }

    }
}

SecondViewController

In SecondViewController there is a Label called profile_name and want to set that parsed string(fn) as Label's text. for that i declared another variable as global.

var pname:String!

below is the code i have used to fetch the value from FirstViewController.

viewDidLoad()
{
       let othervc = FirstViewController()
       self.pname = othervc.fn
       self.profile_name.text = self.pname
}

Problem : I tried my best efforts to get the desired output but i'm getting nil response.

Please Help.

Body:
Your updated code just won't work.

let othervc = FirstViewController()

creates a new instance of FirstViewController (not the one that got the JSON).

You should be handling it something like this:

In FirstViewController

let fn = dtl["Father_Name"] as? String ?? "NA"
let svc = SecondViewController() // Or maybe instantiate from Storyboard, or maybe you already have a reference to it
svc.pname = fn
present(svc, animated: true, completion: nil)

Then in SecondViewController

override func viewDidLoad() {
    super.viewDidLoad()

    profile_name.text = pname
}

I'd suggest you take some time out and re-read Apple's View Controller programming guide.

Original Answer

The problem you have here…

vcvalue.profile_name.text = fn

is that profile_name is nil as the view for the view controller hasn't been loaded at this point.

You should handle this by creating a property in LeftSideMenuViewController

var name: String?

Then set

vcvalue.name = fn

And then in LeftSideMenuViewController

override func viewDidLoad() {
    super.viewDidLoad()

    profile_name.text = name
}

Also, some basic tips…

Don't force unwrap (!) apart from IBOutlets. You may have to write a bit more code, but you will reduce crashes.

Make @IBOutlets private - this will prevent you accidentally assigning to them as you are now

If you're overriding any viewWill/DidDis/Appear methods, you must call super at some point.

You need to re-read the section on switch/case

So this…

let  a = indexPath.row
switch(a)
    {
    case 0 :
        if(a == 0)
        {
            return 45
        }
        break
     etc

could just be…

switch indexPath.row {
case 0...4:
    return 45
case 5:
    return 50
default:
    break
}


问:
Why can't I see cookie value in a WebSocket handshake request header?
I wanted to send a websocket handshake request from an html page and wrote codes like below:

```<code>  document.cookie = "guestId=xxxx; remember=xxxxxx;";
  var ws = new WebSocket("ws://localhost:5000/ws");
</code>```

But what shown in Chrome Dev Tools appears that no cookie was sent:

```<code>General:
  Request URL:ws://localhost:5000/ws
  Request Method:GET
  Status Code:307 Temporary Redirect
Response Headers
  Content-Length:59
  Content-Type:text/html; charset=utf-8
  Date:Fri, 18 Mar 2016 09:39:11 GMT
  Location:/preorder/landing/index
Request Headers
  Accept-Encoding:gzip, deflate, sdch
  Accept-Language:en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4
  Cache-Control:no-cache
  Connection:Upgrade
  Host:localhost:5000
  Origin:http://localhost:63342
  Pragma:no-cache
  Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits
  Sec-WebSocket-Key:t3N0vVaLCsOmOXLSh+Arsw==
  Sec-WebSocket-Version:13
  Upgrade:websocket
  User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
</code>```

How can I fix this? Why there is no cookie in request headers? If I send other ajax request not upgraded, I can see cookies in Dev Tools. Why is there such differences?

答: Your Origin header is http://localhost:63342 and the WS request is to ws://localhost:5000/ws so your domains are different (different ports). I imagine your other ajax requests are to http://localhost:63342 and thus the browser sends the cookie.

Body:
I wanted to send a websocket handshake request from an html page and wrote codes like below:

  document.cookie = "guestId=xxxx; remember=xxxxxx;";
  var ws = new WebSocket("ws://localhost:5000/ws");

But what shown in Chrome Dev Tools appears that no cookie was sent:

General:
  Request URL:ws://localhost:5000/ws
  Request Method:GET
  Status Code:307 Temporary Redirect
Response Headers
  Content-Length:59
  Content-Type:text/html; charset=utf-8
  Date:Fri, 18 Mar 2016 09:39:11 GMT
  Location:/preorder/landing/index
Request Headers
  Accept-Encoding:gzip, deflate, sdch
  Accept-Language:en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4
  Cache-Control:no-cache
  Connection:Upgrade
  Host:localhost:5000
  Origin:http://localhost:63342
  Pragma:no-cache
  Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits
  Sec-WebSocket-Key:t3N0vVaLCsOmOXLSh+Arsw==
  Sec-WebSocket-Version:13
  Upgrade:websocket
  User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36

How can I fix this? Why there is no cookie in request headers? If I send other ajax request not upgraded, I can see cookies in Dev Tools. Why is there such differences?


问:
Set column width to content length in CSS Grid
I looked at the documentation but did not find such property.
I want to fit all cells in one column to its content width using css grid.

For the first case I should apply this property for the container: grid-template-columns: auto auto;

But what should I do for the second case?

答:
Set the following on the grid container:

```<code>grid-template-columns: auto 1fr;
</code>```

This sets the width of the first column to equal the width of the widest item in that column, and the width of the second column to get the remaining width of the grid.

To right-align the content of the second column we can simply use text-align: right

```<code>span:nth-child(2n) {
  text-align: right;
}
</code>```

div {
  display: grid;
  grid-template-columns: auto 1fr;
}
span {
  padding: 0.5em;
}
span:nth-child(2n) {
  text-align: right;
}
span:nth-child(1) {
  background-color: beige; /* colors for demo */
}
span:nth-child(2) {
  background-color: wheat;
}
span:nth-child(3) {
  background-color: lightgreen;
}
span:nth-child(4) {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>some content here</span>
  <span>content</span>
  <span>cell3</span>
  <span>cell4</span>
</div></code>```

NB: Setting column widths with min-content is a little more aggressive :) and will set the width of the column to the width of the largest word in the column.

div {
  display: grid;
  grid-template-columns: min-content auto;
}
span {
  padding: 0.5em;
}
span:nth-child(2n) {
  text-align: right;
}
span:nth-child(1) {
  background-color: beige;
}
span:nth-child(2) {
  background-color: wheat;
}
span:nth-child(3) {
  background-color: lightgreen;
}
span:nth-child(4) {
  background-color: salmon;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>some content here</span>
  <span>content</span>
  <span>cell3</span>
  <span>cell4</span>
</div></code>```

Body:
Set the following on the grid container:

grid-template-columns: auto 1fr;

This sets the width of the first column to equal the width of the widest item in that column, and the width of the second column to get the remaining width of the grid.

To right-align the content of the second column we can simply use text-align: right

span:nth-child(2n) {
  text-align: right;
}

div {
  display: grid;
  grid-template-columns: auto 1fr;
}
span {
  padding: 0.5em;
}
span:nth-child(2n) {
  text-align: right;
}
span:nth-child(1) {
  background-color: beige; /* colors for demo */
}
span:nth-child(2) {
  background-color: wheat;
}
span:nth-child(3) {
  background-color: lightgreen;
}
span:nth-child(4) {
  background-color: salmon;
}

<div>
  <span>some content here</span>
  <span>content</span>
  <span>cell3</span>
  <span>cell4</span>
</div>

NB: Setting column widths with min-content is a little more aggressive :) and will set the width of the column to the width of the largest word in the column.

div {
  display: grid;
  grid-template-columns: min-content auto;
}
span {
  padding: 0.5em;
}
span:nth-child(2n) {
  text-align: right;
}
span:nth-child(1) {
  background-color: beige;
}
span:nth-child(2) {
  background-color: wheat;
}
span:nth-child(3) {
  background-color: lightgreen;
}
span:nth-child(4) {
  background-color: salmon;
}

<div>
  <span>some content here</span>
  <span>content</span>
  <span>cell3</span>
  <span>cell4</span>
</div>


问:
application.current.properties doesn't persist value from service call (Asynchronous Method) in xamarin.forms?
I want to store object in isolated storage. I am using Application.Current.Properties.

Problem is when I store static string to isolated storage like

```<code>Application.Current.Properties["EC"] = "10008";
</code>```

then it works perfectly but when I call service (Asynchronous method) and Fill the object it doesn't store persistently.

```<code>private async Task CallWebServiceForUserProfile(string EmpCode)
 {
     try
     {
         var response = await ServiceLayer.GetResponseFromWebService.GetResponse<ServiceLayer.ServiceClasses.Profile_RootObject>
                                          (ServiceLayer.ServiceURL.UserProfile + "UserId=" + EmpCode);
         if (response != null)
         {
             if (response.Flag == true)
             {
                 objProfile = new Profile();
                 objProfile.BranchCd = response.PrInfoList[0].BranchCd != null ? response.PrInfoList[0].BranchCd : string.Empty; ;
                 objProfile.CLBalance = response.PrInfoList[0].CLBalance != null ? response.PrInfoList[0].CLBalance : string.Empty;
                 objProfile.COFFBalance = response.PrInfoList[0].COFFBalance != null ? response.PrInfoList[0].COFFBalance : string.Empty;
                 objProfile.Designation = response.PrInfoList[0].Designation != null ? response.PrInfoList[0].Designation : string.Empty;
                 objProfile.ELBalance = response.PrInfoList[0].ELBalance != null ? response.PrInfoList[0].ELBalance : string.Empty;
                 objProfile.EmpCode = response.PrInfoList[0].EmpCode != null ? response.PrInfoList[0].EmpCode : string.Empty;
                 objProfile.EmpName = response.PrInfoList[0].EmpName != null ? response.PrInfoList[0].EmpName : string.Empty;
                 objProfile.Grade = response.PrInfoList[0].Grade != null ? response.PrInfoList[0].Grade : string.Empty;
                 objProfile.HOD = response.PrInfoList[0].HOD != null ? response.PrInfoList[0].HOD : string.Empty;
                 objProfile.HPLBalance = response.PrInfoList[0].HPLBalance != null ? response.PrInfoList[0].HPLBalance : string.Empty;
                 objProfile.LocCd = response.PrInfoList[0].LocCd != null ? response.PrInfoList[0].LocCd : string.Empty;
                 objProfile.ReportingTo = response.PrInfoList[0].ReportingTo != null ? response.PrInfoList[0].ReportingTo : string.Empty;
                 objProfile.Unit = response.PrInfoList[0].Unit != null ? response.PrInfoList[0].CLBalance : string.Empty;
                 objProfile.Photo = response.PrInfoList[0].Photo != null ? response.PrInfoList[0].Photo : null;
                 objProfile.Join_Dt = response.PrInfoList[0].Join_Dt != null ? response.PrInfoList[0].Join_Dt : string.Empty;

                 Application.Current.Properties["UserProfile"] = objProfile;
                 Application.Current.Properties.Add("UserProfile", objProfile);
                 Application.Current.Properties["EmployeeCode"] = response.PrInfoList[0].EmpCode != null ? response.PrInfoList[0].EmpCode : string.Empty;
                 //await Application.Current.SavePropertiesAsync();
             }
             else if (response.Flag == false)
             {
                 await DisplayAlert(AppResources.LError, response.Message, "OK");
             }
         }
         else
         {
             await DisplayAlert(AppResources.LError, AppResources.LConnectionError, "OK");
         }
     }
     catch (WebException Exception)
     {
         await DisplayAlert(AppResources.LError, AppResources.LConnectionError, "OK");
     }
 }
</code>```

I want to use this information when my application is start.

```<code>Profile objProfile = new Profile();

if (Application.Current.Properties.ContainsKey("UserProfile"))
{
    objProfile = Application.Current.Properties["UserProfile"] as Profile;

    if (objProfile.EmpCode != null)
    {
        MyEmployeeId = objProfile.EmpCode;
    }

    MainPage = new SideMenu();
}
else
{
    MainPage = new NavigationPage(new LoginPage());
}
</code>```

As you can see in above code I have put following code to store data.

```<code>Application.Current.Properties["UserProfile"] = objProfile;
//Application.Current.Properties.Add("UserProfile", objProfile);
Application.Current.Properties["EmployeeCode"] = response.PrInfoList[0].EmpCode != null ? response.PrInfoList[0].EmpCode : string.Empty;
</code>```

I have also try but don't solve my problem.

```<code>await Application.Current.SavePropertiesAsync();
</code>```

Every time Login-page is open at application start.

Is there any alternative way to solve this issue? I don't want to use SQLite.

答:
You need to serialize/deserialize your Profile object manually.

Please refer this link for example-
https://codemilltech.com/persist-whatever-you-want-with-xamarin-forms/

Body:
I want to store object in isolated storage. I am using Application.Current.Properties.

Problem is when I store static string to isolated storage like

Application.Current.Properties["EC"] = "10008";

then it works perfectly but when I call service (Asynchronous method) and Fill the object it doesn't store persistently.

private async Task CallWebServiceForUserProfile(string EmpCode)
 {
     try
     {
         var response = await ServiceLayer.GetResponseFromWebService.GetResponse<ServiceLayer.ServiceClasses.Profile_RootObject>
                                          (ServiceLayer.ServiceURL.UserProfile + "UserId=" + EmpCode);
         if (response != null)
         {
             if (response.Flag == true)
             {
                 objProfile = new Profile();
                 objProfile.BranchCd = response.PrInfoList[0].BranchCd != null ? response.PrInfoList[0].BranchCd : string.Empty; ;
                 objProfile.CLBalance = response.PrInfoList[0].CLBalance != null ? response.PrInfoList[0].CLBalance : string.Empty;
                 objProfile.COFFBalance = response.PrInfoList[0].COFFBalance != null ? response.PrInfoList[0].COFFBalance : string.Empty;
                 objProfile.Designation = response.PrInfoList[0].Designation != null ? response.PrInfoList[0].Designation : string.Empty;
                 objProfile.ELBalance = response.PrInfoList[0].ELBalance != null ? response.PrInfoList[0].ELBalance : string.Empty;
                 objProfile.EmpCode = response.PrInfoList[0].EmpCode != null ? response.PrInfoList[0].EmpCode : string.Empty;
                 objProfile.EmpName = response.PrInfoList[0].EmpName != null ? response.PrInfoList[0].EmpName : string.Empty;
                 objProfile.Grade = response.PrInfoList[0].Grade != null ? response.PrInfoList[0].Grade : string.Empty;
                 objProfile.HOD = response.PrInfoList[0].HOD != null ? response.PrInfoList[0].HOD : string.Empty;
                 objProfile.HPLBalance = response.PrInfoList[0].HPLBalance != null ? response.PrInfoList[0].HPLBalance : string.Empty;
                 objProfile.LocCd = response.PrInfoList[0].LocCd != null ? response.PrInfoList[0].LocCd : string.Empty;
                 objProfile.ReportingTo = response.PrInfoList[0].ReportingTo != null ? response.PrInfoList[0].ReportingTo : string.Empty;
                 objProfile.Unit = response.PrInfoList[0].Unit != null ? response.PrInfoList[0].CLBalance : string.Empty;
                 objProfile.Photo = response.PrInfoList[0].Photo != null ? response.PrInfoList[0].Photo : null;
                 objProfile.Join_Dt = response.PrInfoList[0].Join_Dt != null ? response.PrInfoList[0].Join_Dt : string.Empty;

                 Application.Current.Properties["UserProfile"] = objProfile;
                 Application.Current.Properties.Add("UserProfile", objProfile);
                 Application.Current.Properties["EmployeeCode"] = response.PrInfoList[0].EmpCode != null ? response.PrInfoList[0].EmpCode : string.Empty;
                 //await Application.Current.SavePropertiesAsync();
             }
             else if (response.Flag == false)
             {
                 await DisplayAlert(AppResources.LError, response.Message, "OK");
             }
         }
         else
         {
             await DisplayAlert(AppResources.LError, AppResources.LConnectionError, "OK");
         }
     }
     catch (WebException Exception)
     {
         await DisplayAlert(AppResources.LError, AppResources.LConnectionError, "OK");
     }
 }

I want to use this information when my application is start.

Profile objProfile = new Profile();

if (Application.Current.Properties.ContainsKey("UserProfile"))
{
    objProfile = Application.Current.Properties["UserProfile"] as Profile;

    if (objProfile.EmpCode != null)
    {
        MyEmployeeId = objProfile.EmpCode;
    }

    MainPage = new SideMenu();
}
else
{
    MainPage = new NavigationPage(new LoginPage());
}

As you can see in above code I have put following code to store data.

Application.Current.Properties["UserProfile"] = objProfile;
//Application.Current.Properties.Add("UserProfile", objProfile);
Application.Current.Properties["EmployeeCode"] = response.PrInfoList[0].EmpCode != null ? response.PrInfoList[0].EmpCode : string.Empty;

I have also try but don't solve my problem.

await Application.Current.SavePropertiesAsync();

Every time Login-page is open at application start.

Is there any alternative way to solve this issue? I don't want to use SQLite.


问:
Set Electron favicon with electron-builder
I would like set new favicon in my Electron App and replace default Electron icon when my app is build.

I use electron-builder package. In the doc, i see the icons need to be placed in the build directory. So :

And when i build my app, i've this message :

Application icon is not set, default Electron icon will be used.

Anyone can help me ?

Part of my package.json :

```<code>  "scripts": {
    "postinstall": "install-app-deps && npmpd",
    "pre-build": "./node_modules/.bin/electron-rebuild",
    "build-bcrypt": "npm rebuild bcrypt --update-binary",
    "develop": "npm run private:compile -- --source-maps true && run-p -r private:watch private:serve",
    "test": "mocha -R spec --compilers js:babel-core/register test/**/*.spec.js",
    "lint": "eslint --no-ignore scripts app test *.js",
    "pack": "run-s private:clean private:compile private:build:all",
    "pack:mac": "run-s private:clean private:compile private:build:mac",
    "pack:win": "run-s private:clean private:compile private:build:win",
    "pack:linux": "run-s private:clean private:compile private:build:linux",
    "private:build:all": "build -mwl",
    "private:build:mac": "build --mac",
    "private:build:win": "build --win",
    "private:build:linux": "build --linux",
    "private:watch": "npm run private:compile -- --source-maps true --watch --skip-initial-build",
    "private:serve": "babel-node scripts/serve.js",
    "private:compile": "babel app/ --copy-files --out-dir build",
    "private:clean": "rimraf build",
    "private:cleandb": "rm -rf ./categories ./presentations ./slides ./users"
  },
  "build": {
    "win": {
      "icon": "build/icon.ico"
    }
  }
</code>```

答:
In package.json, under the win key, you also need to specify the icon path:

```<code>"build": {
  "win": {
    "icon": "build/app.ico"
  }
}
</code>```

Body:
I would like set new favicon in my Electron App and replace default Electron icon when my app is build.

I use electron-builder package. In the doc, i see the icons need to be placed in the build directory. So :

And when i build my app, i've this message :

Application icon is not set, default Electron icon will be used.

Anyone can help me ?

Part of my package.json :

  "scripts": {
    "postinstall": "install-app-deps && npmpd",
    "pre-build": "./node_modules/.bin/electron-rebuild",
    "build-bcrypt": "npm rebuild bcrypt --update-binary",
    "develop": "npm run private:compile -- --source-maps true && run-p -r private:watch private:serve",
    "test": "mocha -R spec --compilers js:babel-core/register test/**/*.spec.js",
    "lint": "eslint --no-ignore scripts app test *.js",
    "pack": "run-s private:clean private:compile private:build:all",
    "pack:mac": "run-s private:clean private:compile private:build:mac",
    "pack:win": "run-s private:clean private:compile private:build:win",
    "pack:linux": "run-s private:clean private:compile private:build:linux",
    "private:build:all": "build -mwl",
    "private:build:mac": "build --mac",
    "private:build:win": "build --win",
    "private:build:linux": "build --linux",
    "private:watch": "npm run private:compile -- --source-maps true --watch --skip-initial-build",
    "private:serve": "babel-node scripts/serve.js",
    "private:compile": "babel app/ --copy-files --out-dir build",
    "private:clean": "rimraf build",
    "private:cleandb": "rm -rf ./categories ./presentations ./slides ./users"
  },
  "build": {
    "win": {
      "icon": "build/icon.ico"
    }
  }

Body:
In package.json, under the win key, you also need to specify the icon path:

"build": {
  "win": {
    "icon": "build/app.ico"
  }
}


问:
GlassFish Server deployment
I am new using GlassFish Server and WS. I just deployed a Web app. generated with maven having this web.xml

```<code><!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

</web-app>
</code>```

I click on the Web Application Links

I have this class in the application:

```<code>import javax.jws.WebMethod;
import javax.jws.WebService;

import javax.servlet.http.HttpSession;

import javax.xml.ws.WebServiceContext;

import javax.xml.ws.handler.MessageContext;

    @WebService(serviceName="IberiaWS")
    public class IberiaWS {

      @Resource
      private WebServiceContext wsContext;

      public IberiaWS () {
      }

      private UserVO getSessionUserVO() {
        MessageContext mc = wsContext.getMessageContext();
        HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
        return (UserVO)session.getAttribute("uservo");
      }

      private void setSessionUserVO(UserVO uservo) {
        MessageContext mc = wsContext.getMessageContext();
        HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
        session.setAttribute("uservo", uservo);

      }

      @WebMethod
      public boolean login(String loginName, String loginPwd) throws Exception {
        this.setSessionUserVO(new UserDAO().findUser("_"+loginName, "__"+loginPwd));
        return isConnected();
      }

      @WebMethod
      public boolean isConnected() {
        return (this.getSessionUserVO()!=null);
      }

      @WebMethod
      public IberiaPerson getPerson(String id) {
        return new IberiaPerson();
      }

      @WebMethod
      public IberiaPerson findPerson(String companyNr) {
        UserVO uservo = this.getSessionUserVO();
        IberiaPerson ret=null;
        PersonVO p= new PersonDAO().findByCompanyNr(uservo.getAdminCenterId(), uservo.getUserId(), "Iberia", companyNr);
        if (p!=null) {
          ret = new IberiaPerson();
          ret.setPersonId(p.getPersonId());
          ret.setCompanyName(p.getVehicleOwnerName());
          ret.setCategoryName(p.getCategoryName());
          ret.setCompanyNr(p.getCompanyNr());
          ret.setFirstName(p.getFirstName());
          ret.setLastName(p.getLastName());
          ret.setStatusId(p.getStatusId());
          ret.setGroupName(p.getGroupList());
          ret.setKeyCode(p.getKeyString());
          ret.setComments(p.getLmComment());
        }
        return ret;
      }
    }
</code>```

It seems that the WS is deployed since I saw it in Engines

I can access the spp. http://localhost:8080/iberiafleet/

But I don't now how to access the WSLD of the deployed WS

I got a HTTP Status 404 on this URL

http://localhost:8080/iberiafleet/IberiaWSPort?WSDL

and also

http://localhost:8080/iberiafleet/IberiaWS?wsdl

But according to this tutorial I should see a the link View Endpoint

https://blog.idrsolutions.com/2013/08/creating-and-deploying-a-java-web-service/

but I don't see it.

I can see this message in the console:

```<code>  [#|2017-11-13T10:50:39.993+0100|INFO|glassfish 5.0|javax.enterprise.webservices.metroglue|_ThreadID=19;_ThreadName=RunLevelControllerThread-1510566633374;_TimeMillis=1510566639993;_LevelValue=800;_MessageID=AS-WSMETROGLUE-10010;|
  Web service endpoint deployment events listener registered successfully.|#]
</code>```

答:
I think you have a typo in your WSDL URL, does

```<code>http://localhost:8080/iberiafleet/IberiaWS?wsdl
</code>```

work?

Title: GlassFish Server deployment

Body:
I am new using GlassFish Server and WS. I just deployed a Web app. generated with maven having this web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

</web-app>

I click on the Web Application Links

I have this class in the application:

import javax.jws.WebMethod;
import javax.jws.WebService;

import javax.servlet.http.HttpSession;

import javax.xml.ws.WebServiceContext;

import javax.xml.ws.handler.MessageContext;

    @WebService(serviceName="IberiaWS")
    public class IberiaWS {

      @Resource
      private WebServiceContext wsContext;

      public IberiaWS () {
      }

      private UserVO getSessionUserVO() {
        MessageContext mc = wsContext.getMessageContext();
        HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
        return (UserVO)session.getAttribute("uservo");
      }

      private void setSessionUserVO(UserVO uservo) {
        MessageContext mc = wsContext.getMessageContext();
        HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
        session.setAttribute("uservo", uservo);

      }

      @WebMethod
      public boolean login(String loginName, String loginPwd) throws Exception {
        this.setSessionUserVO(new UserDAO().findUser("_"+loginName, "__"+loginPwd));
        return isConnected();
      }

      @WebMethod
      public boolean isConnected() {
        return (this.getSessionUserVO()!=null);
      }

      @WebMethod
      public IberiaPerson getPerson(String id) {
        return new IberiaPerson();
      }

      @WebMethod
      public IberiaPerson findPerson(String companyNr) {
        UserVO uservo = this.getSessionUserVO();
        IberiaPerson ret=null;
        PersonVO p= new PersonDAO().findByCompanyNr(uservo.getAdminCenterId(), uservo.getUserId(), "Iberia", companyNr);
        if (p!=null) {
          ret = new IberiaPerson();
          ret.setPersonId(p.getPersonId());
          ret.setCompanyName(p.getVehicleOwnerName());
          ret.setCategoryName(p.getCategoryName());
          ret.setCompanyNr(p.getCompanyNr());
          ret.setFirstName(p.getFirstName());
          ret.setLastName(p.getLastName());
          ret.setStatusId(p.getStatusId());
          ret.setGroupName(p.getGroupList());
          ret.setKeyCode(p.getKeyString());
          ret.setComments(p.getLmComment());
        }
        return ret;
      }
    }

It seems that the WS is deployed since I saw it in Engines

I can access the spp. http://localhost:8080/iberiafleet/

But I don't now how to access the WSLD of the deployed WS

I got a HTTP Status 404 on this URL

http://localhost:8080/iberiafleet/IberiaWSPort?WSDL

and also

http://localhost:8080/iberiafleet/IberiaWS?wsdl

But according to this tutorial I should see a the link View Endpoint

https://blog.idrsolutions.com/2013/08/creating-and-deploying-a-java-web-service/

but I don't see it.

I can see this message in the console:

  [#|2017-11-13T10:50:39.993+0100|INFO|glassfish 5.0|javax.enterprise.webservices.metroglue|_ThreadID=19;_ThreadName=RunLevelControllerThread-1510566633374;_TimeMillis=1510566639993;_LevelValue=800;_MessageID=AS-WSMETROGLUE-10010;|
  Web service endpoint deployment events listener registered successfully.|#]

Body:
I think you have a typo in your WSDL URL, does

http://localhost:8080/iberiafleet/IberiaWS?wsdl

work?