问:
unable to dismiss Progress dialog using dismiss method in android
```<code>class CShowProgress(context: Context) {
    var s_m_oCShowProgress: CShowProgress? = null
    lateinit var m_Dialog: Dialog
    private var m_ProgressBar: ProgressBar? = null
    private var progressText: TextView? = null

    fun getInstance(): CShowProgress {
        if (s_m_oCShowProgress == null) {
            s_m_oCShowProgress = CShowProgress(context!!)
        }
        return s_m_oCShowProgress as CShowProgress
    }

    fun show(m_Context: Context, message: String) {
        m_Dialog = Dialog(m_Context)
        m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        m_Dialog.setContentView(R.layout.progress_bar)
        m_ProgressBar = m_Dialog.findViewById(R.id.progressBar_cyclic)
        m_ProgressBar!!.visibility = View.VISIBLE
        m_ProgressBar!!.isIndeterminate = true
        m_Dialog.setCancelable(false)
        m_Dialog.setCanceledOnTouchOutside(false)
        m_Dialog.show()
    }

    fun dismiss(m_Context: Context) {
        m_Dialog = Dialog(m_Context)
        m_Dialog.dismiss()
    }
}
</code>```

This is my singlton class for custom Progress dialog for show dialog we have show method and for dismiss we have dismiss method  i am calling this class

```<code>    CShowProgress(this).getInstance().show(this, "Please wait..")
     and for dismiss i am calling

    CShowProgress(this).getInstance().dismiss(this)
</code>```

using show i am able to show Progress dialog but using dimiss i am not able to dismiss can any one please tell me what i am doing wrong i am using kotlin language .

答:
Please try this

```<code>class CShowProgress(context: Context) {
     var s_m_oCShowProgress: CShowProgress? = null
     lateinit var m_Dialog: Dialog
     private var m_ProgressBar: ProgressBar? = null
     private var progressText: TextView? = null

fun getInstance(): CShowProgress {
    if (s_m_oCShowProgress == null) {
        s_m_oCShowProgress = CShowProgress(context!!)
    }
    return s_m_oCShowProgress as CShowProgress
}

fun show(m_Context: Context, message: String) {
    m_Dialog = Dialog(m_Context)
    m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    m_Dialog.setContentView(R.layout.progress_bar)
    m_ProgressBar = m_Dialog.findViewById(R.id.progressBar_cyclic)
    m_ProgressBar!!.visibility = View.VISIBLE
    m_ProgressBar!!.isIndeterminate = true
    m_Dialog.setCancelable(false)
    m_Dialog.setCanceledOnTouchOutside(false)
    m_Dialog.show()
}

fun dismiss() {
   //no need to re initialise dialog only check for if the dialog is showing
    if(m_Dialog.isShowing){
       m_Dialog.dismiss()
    }
}
}
</code>```

in your activity create a object for the class and use show and dismiss methods just like this

```<code> val dialoge:CShowProgress = CShowProgress(this)//create object for the class

    dialoge.show(this,"Your message")//for showing the dialog

    dialoge.dismiss()//to dismiss the dialog
</code>```

Body:
class CShowProgress(context: Context) {
    var s_m_oCShowProgress: CShowProgress? = null
    lateinit var m_Dialog: Dialog
    private var m_ProgressBar: ProgressBar? = null
    private var progressText: TextView? = null

    fun getInstance(): CShowProgress {
        if (s_m_oCShowProgress == null) {
            s_m_oCShowProgress = CShowProgress(context!!)
        }
        return s_m_oCShowProgress as CShowProgress
    }

    fun show(m_Context: Context, message: String) {
        m_Dialog = Dialog(m_Context)
        m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        m_Dialog.setContentView(R.layout.progress_bar)
        m_ProgressBar = m_Dialog.findViewById(R.id.progressBar_cyclic)
        m_ProgressBar!!.visibility = View.VISIBLE
        m_ProgressBar!!.isIndeterminate = true
        m_Dialog.setCancelable(false)
        m_Dialog.setCanceledOnTouchOutside(false)
        m_Dialog.show()
    }

    fun dismiss(m_Context: Context) {
        m_Dialog = Dialog(m_Context)
        m_Dialog.dismiss()
    }
}

This is my singlton class for custom Progress dialog for show dialog we have show method and for dismiss we have dismiss method  i am calling this class

    CShowProgress(this).getInstance().show(this, "Please wait..")
     and for dismiss i am calling

    CShowProgress(this).getInstance().dismiss(this)

using show i am able to show Progress dialog but using dimiss i am not able to dismiss can any one please tell me what i am doing wrong i am using kotlin language .

Body:
Please try this

class CShowProgress(context: Context) {
     var s_m_oCShowProgress: CShowProgress? = null
     lateinit var m_Dialog: Dialog
     private var m_ProgressBar: ProgressBar? = null
     private var progressText: TextView? = null

fun getInstance(): CShowProgress {
    if (s_m_oCShowProgress == null) {
        s_m_oCShowProgress = CShowProgress(context!!)
    }
    return s_m_oCShowProgress as CShowProgress
}

fun show(m_Context: Context, message: String) {
    m_Dialog = Dialog(m_Context)
    m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    m_Dialog.setContentView(R.layout.progress_bar)
    m_ProgressBar = m_Dialog.findViewById(R.id.progressBar_cyclic)
    m_ProgressBar!!.visibility = View.VISIBLE
    m_ProgressBar!!.isIndeterminate = true
    m_Dialog.setCancelable(false)
    m_Dialog.setCanceledOnTouchOutside(false)
    m_Dialog.show()
}

fun dismiss() {
   //no need to re initialise dialog only check for if the dialog is showing
    if(m_Dialog.isShowing){
       m_Dialog.dismiss()
    }
}
}

in your activity create a object for the class and use show and dismiss methods just like this

 val dialoge:CShowProgress = CShowProgress(this)//create object for the class

    dialoge.show(this,"Your message")//for showing the dialog

    dialoge.dismiss()//to dismiss the dialog


来源: stackexchange

问:
PowerShell: Run command from script's directory
I have a PowerShell script that does some stuff using the script’s current directory. So when inside that directory, running .\script.ps1 works correctly.

Now I want to call that script from a different directory without changing the referencing directory of the script. So I want to call ..\..\dir\script.ps1 and still want that script to behave as it was called from inside its directory.

How do I do that, or how do I modify a script so it can run from any directory?

答:
This would work fine.</p>

```<code>Push-Location $PSScriptRoot

Write-Host CurrentDirectory $CurDir
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This would work fine.

Push-Location $PSScriptRoot

Write-Host CurrentDirectory $CurDir


问:
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()'

When I call this method sometimes it's shows exception

```<code>public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}
</code>```

My error :

```<code>Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
       at java.util.Calendar.setTime(Calendar.java:1197)
       at com.utils.Utils.getTimestampFromDate(SourceFile:105)
       at com.fragment.MyProfileFragment.onViewClicked(SourceFile:768)
       at com.fragment.MyProfileFragment_ViewBinding$4.doClick(SourceFile:79)
       at butterknife.internal.DebouncingOnClickListener.onClick(SourceFile:22)
       at android.view.View.performClick(View.java:5205)
       at android.view.View$PerformClick.run(View.java:21162)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5453)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
</code>```

Date format :

```<code>public static String SLASH_MM_DD_YYYY = "dd-MMM-yyyy";
</code>```

Any solutions for this?

答:
Please specify the format that you are sending when you are using this method

```<code>public static long getTimestampFromDate(String date, String format) {
 DateFormat formatter = new SimpleDateFormat(yyyy-DD-MM hh:mm);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}
</code>```

while using this method i.e getTimestampFromDate() the date should be in year month day hour and minute

Body:
When I call this method sometimes it's shows exception

public static long getTimestampFromDate(String date, String format) {
    DateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}

My error :

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
       at java.util.Calendar.setTime(Calendar.java:1197)
       at com.utils.Utils.getTimestampFromDate(SourceFile:105)
       at com.fragment.MyProfileFragment.onViewClicked(SourceFile:768)
       at com.fragment.MyProfileFragment_ViewBinding$4.doClick(SourceFile:79)
       at butterknife.internal.DebouncingOnClickListener.onClick(SourceFile:22)
       at android.view.View.performClick(View.java:5205)
       at android.view.View$PerformClick.run(View.java:21162)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5453)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)

Date format :

public static String SLASH_MM_DD_YYYY = "dd-MMM-yyyy";

Any solutions for this?

Body:
Please specify the format that you are sending when you are using this method

public static long getTimestampFromDate(String date, String format) {
 DateFormat formatter = new SimpleDateFormat(yyyy-DD-MM hh:mm);
    //formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (Exception e) {
        e.printStackTrace();
        Crashlytics.logException(e);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 1);
    return calendar.getTimeInMillis();
}

while using this method i.e getTimestampFromDate() the date should be in year month day hour and minute


问:
jquery autocomplete - Menu doesn't open when key up/down for navigation
I like to navigate with keys from input to input. If the input field is a jquery autocomplete element, the menu open on key down/up. How can i stop to open the menu, when I'm navigating and not changing anything?</p>

答:
I can tell you only general hints, because of code snippet absence. You have two options to achieve this:

disable autocomplete and enable it when element was changed

use delay to show autocomplete dropdown after some time interval

http://api.jqueryui.com/autocomplete/


问:
How Do I Get DNS Server IP Address In NodeJS
I'm working on a project and stuck in the DNS Leak Tool, where I would have to perform the same task as http://dnsleak.com/ these website doing, is there any logic, where I can get fetch DNS server IP?

Really appreciate if you guys can help!

Regards,
Finn

答:
I think you just have to do something like this :

```<code>const dns = require('dns');

dns.getServers();
</code>```

See  documentation for more information.

Hope it helps.

Body:
I think you just have to do something like this :

const dns = require('dns');

dns.getServers();

See  documentation for more information.

Hope it helps.


问:
Header guards in C++ and C
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:

add.h:

```<code>#include "mymath.h"
int add(int x, int y);
</code>```

subtract.h:

```<code>#include "mymath.h"
int subtract(int x, int y);
</code>```

main.cpp:

```<code>#include "add.h"
#include "subtract.h"
</code>```

In implementing the header guard, it is mentioned as follows:

```<code>#ifndef ADD_H
#define ADD_H

// your declarations here

#endif
</code>```

What could the declaration be here? And, should int main() come after #endif?

Is adding _H a convention or a must do thing?

Thanks.

答:
I declare a declaration in header file and definitions or int main() comes in source.cpp file.

_H is there to merely indicate that someone is going to include header files using include guards.

If you're on MSVC++ you can also use #pragma once

ContentLicense: CC BY-SA 4.0

Title: Header guards in C++ and C

Body:
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:

add.h:

#include "mymath.h"
int add(int x, int y);

subtract.h:

#include "mymath.h"
int subtract(int x, int y);

main.cpp:

#include "add.h"
#include "subtract.h"

In implementing the header guard, it is mentioned as follows:

#ifndef ADD_H
#define ADD_H

// your declarations here

#endif

What could the declaration be here? And, should int main() come after #endif?

Is adding _H a convention or a must do thing?

Thanks.

ContentLicense: CC BY-SA 2.5


问:
Caching the results returned from a stored procedure
Is there a way to cache the results returned from a stored procedures using JDBC, the same like level 1 and 2 cache in Hibernate?

Currently I'm using Sql server, spring and mssql-jdbc. and need to enhance the procedure response time by caching the results in memory for some heavy ones.

I'm calling the stored procedure using the CallableStatement with prepareCall

Any ideas?

答:
If you're using Spring you can use the cache abstraction. See getting started here.

1) You have to enable caching with @EnableCaching

2) You have to annotate the methods that you want to be cached (the repository methods in your case) with @Cachable

See full documentations here.


问:
Conditional callback with request sub domain. is it possible?
I tried something like this

```<code>class SomeController < ApplicationController
  before_action :something, if: request.subdomain == "specific"

end
</code>```

but here i could not access request object and it throwing error.

```<code>undefined local variable or method `request' for SomeController:Class
</code>```

Can someone suggest me how i can achieve this?

答:
You can do something like these</p>

```<code>before_action :something

def something
  if request.subdomain == "specific"
   your code
  end
end
</code>```

Body:
I tried something like this

class SomeController < ApplicationController
  before_action :something, if: request.subdomain == "specific"

end

but here i could not access request object and it throwing error.

undefined local variable or method `request' for SomeController:Class

Can someone suggest me how i can achieve this?

Body:
You can do something like these

before_action :something

def something
  if request.subdomain == "specific"
   your code
  end
end


问:
background image not taking up full width
I am currently positioning a background image that is small in height but large in width to stretch all the way across the browser. I am only able to achieve this when I do background size cover, but not when I set a certain size to the image other than cover. I tried background repeat-x but that does not seem to work either.

```<code><html>
  <body>
    <div class="background">
      <div class=“header”></div>
      //some content
    </div>
    <footer><footer/>
  </body>
 </html>
</code>```

CSS

```<code>.background {
    background-image: url(some image);
    background-size: //tried cover and it works but not when I set it to width 100% or something like 2800px
    background-repeat: repeat-x;
    background-position-y: bottom;
}
html, body, .background {
    height: 100%;
}
</code>```

答:
```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>    html, body{
      height: 100%;
    }
    body {
       background-image: url(http://ppcdn.500px.org/75319705/1991f76c0c6a91ae1d23eb94ac5c7a9f7e79c480/2048.jpg) ;
       background-position: center center;
       background-repeat:  no-repeat;
       background-attachment: fixed;
       background-size:  cover;
       background-color: #999;

    }

    div, body{
      margin: 0;
      padding: 0;
    }
    .wrapper {
      height: 100%;
      width: 100%;
    }</code>```

```
</div>
</div>

</code>```

Body:
I am currently positioning a background image that is small in height but large in width to stretch all the way across the browser. I am only able to achieve this when I do background size cover, but not when I set a certain size to the image other than cover. I tried background repeat-x but that does not seem to work either.

      //some content

CSS

.background {
    background-image: url(some image);
    background-size: //tried cover and it works but not when I set it to width 100% or something like 2800px
    background-repeat: repeat-x;
    background-position-y: bottom;
}
html, body, .background {
    height: 100%;
}

Body:
    html, body{
      height: 100%;
    }
    body {
       background-image: url(http://ppcdn.500px.org/75319705/1991f76c0c6a91ae1d23eb94ac5c7a9f7e79c480/2048.jpg) ;
       background-position: center center;
       background-repeat:  no-repeat;
       background-attachment: fixed;
       background-size:  cover;
       background-color: #999;

    }

    div, body{
      margin: 0;
      padding: 0;
    }
    .wrapper {
      height: 100%;
      width: 100%;
    }

    <div class="wrapper">
      <div class="message"></div>
    </div>


问:
Is it possible to make an interface where the return type of a method is not specified?
I find it hard to describe this in English because it is not my first language so I hope the question/title makes sense.

I need to know if I can make an interface with a method which can return any type in the implementation.

I want to make a generic mapper that I can inject into another class. But I am wondering if I can make a generic mapper or if I need to make different interfaces for the different types. It looks pointless to me to make different interfaces which do the same but only have different return types?

sort of like this:

```<code>public interface IMapper()
{
    T MapObject() where T = the return type
    List<T> MapList() where T = the return type;
}

public class OrderMapper : IMapper()
{
   OrderDetails MapObject()
   {
      mapping code...
      return OrderDetails;
   }
}

public class CustomerMapper : IMapper()
{
    CustomerDetails MapObject()
    {
        mapping code...
        return CustomerDetails;
    }
}
</code>```

Is this possible to do? Or am I just being obtuse and do I need to make different interfaces.

答:
Generics are exactly what you need:</p>

```<code>public interface IMapper<T>
{
    T MapObject();
    List<T> MapList();
}

public class OrderMapper : IMapper<OrderDetails>
{
    public OrderDetails MapObject()
    {
        //  mapping code...

        return new OrderDetails();
    }

    public List<OrderDetails> MapList()
    {
        throw new NotImplementedException();
    }
}

public class CustomerMapper : IMapper<CustomerDetails>
{
    public CustomerDetails MapObject()
    {
        //  mapping code...

        return new CustomerDetails());
    }

    public List<CustomerDetails> MapList()
    {
        throw new NotImplementedException();
    }
}
</code>```

Body:
I find it hard to describe this in English because it is not my first language so I hope the question/title makes sense.

I need to know if I can make an interface with a method which can return any type in the implementation.

I want to make a generic mapper that I can inject into another class. But I am wondering if I can make a generic mapper or if I need to make different interfaces for the different types. It looks pointless to me to make different interfaces which do the same but only have different return types?

sort of like this:

public interface IMapper()
{
    T MapObject() where T = the return type
    List<T> MapList() where T = the return type;
}

public class OrderMapper : IMapper()
{
   OrderDetails MapObject()
   {
      mapping code...
      return OrderDetails;
   }
}

public class CustomerMapper : IMapper()
{
    CustomerDetails MapObject()
    {
        mapping code...
        return CustomerDetails;
    }
}

Is this possible to do? Or am I just being obtuse and do I need to make different interfaces.

Body:
Generics are exactly what you need:

public interface IMapper<T>
{
    T MapObject();
    List<T> MapList();
}

public class OrderMapper : IMapper<OrderDetails>
{
    public OrderDetails MapObject()
    {
        //  mapping code...

        return new OrderDetails();
    }

    public List<OrderDetails> MapList()
    {
        throw new NotImplementedException();
    }
}

public class CustomerMapper : IMapper<CustomerDetails>
{
    public CustomerDetails MapObject()
    {
        //  mapping code...

        return new CustomerDetails());
    }

    public List<CustomerDetails> MapList()
    {
        throw new NotImplementedException();
    }
}


问:
XNA Too many textures loaded in memory
I am working on a level editor for a graphics engine. Recently, as one project expanded I have been experiencing memory issues. In particular, the level is quite big and around 300 textures of varying size need to be loaded. A few textures are quite big like 2048x2048, others are smaller like 256x256 or 512x512. Anyway, the editor consumes 1.3gb of memory for this level and some textures can't be loaded as it throws out of memory exceptions. So what solutions do I have here?

Right now the only solution I can think of is to divide the level into smaller parts and load the textures on demand, depending on the visible area. But I believe this would slow down the performance big time when navigating in the scene. Any thoughts? There should be some standard approach for level editors on that matter.

答:
It might be a good idea to use with different quality of textures, if you're far away use the 64x64 texture, then when you get closer keep swaping it out to 128x128, 256x256, 512x512, etc...  Also reconsider using textures of 2056x2056, since its better to have 4 1024x1024 textures :).

(note: generating mip-maps partially does this, but doesn't free memory on your computer)

Edit: also try to turn on DXT5 texture compression, that might save a lot of memory!

Title: XNA Too many textures loaded in memory


问:
What column type should be used to store serialized data in a mysql db?
What column type should be used to store serialized data in a mysql db?
I know you can use varbinary, blob, text. What's considered the best and why?

Edit:
I understand it is not "good" to store serialized data. I need to do it in this one case though. Please just trust me on this and focus on the question if you have an answer. Thanks!

答:
I might be late to the party, but the php.net documentation about serialized object states the following:

Note that this is a binary string which may include null bytes, and
  needs to be stored and handled as such. For example, serialize()
  output should generally be stored in a BLOB field in a database,
  rather than a CHAR or TEXT field.

Source: http://php.net/manual/en/function.serialize.php

Hope that helps!


问:
Xcode won't build due to Framework not found
FYI - I'm a novice with Xcode.

I'm running Xcode on MacBook Pro High Sierra OS only to make minor amendments to a simple app. I was given the project folder and manage to get the project running previously and make the minor changes and publish these to Apple. No problem at all.

I moved the project off my desktop a while back. I now have to make an update. I have moved the project back to my desktop and attempted to build the project but I'm now getting an error where a library cannot be found even though it is there and is being referenced in the correct location. I don't think it's anything to do with moving the project... Here's what I'm seeing...

I have tried to remove and add the offending library with no success.

Maybe it's a red herrin?

I am stuck... please help!!!!

答:
You are getting this error because previous reference of library is present at following path:

Target->Build settings->Search Paths->Library search path

Remove previous path from here and add new one.It will work


问:
how to deep _sumBy using lodash?
```<code>var data= [{
        "item_name": "Jumbo Combo",
        "item_key": "9lazhy15tp2fgo72",
        "item_price": 25,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }, {
        "item_name": "Swiss & Mushroom Combo",
        "item_key": "e1vdfos6s50d5kej",
        "item_price": 22,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }]
</code>```

i want to sum the item_price as well as "ingredients":[{"price":3}] using loadash how to deep sumBy

i tryed item_price

```<code>_.sumBy(data, 'item_price')
</code>```

this can get the total price of item price in an array, but how to get sum of price of ingredients and item_price

答:
Lodash#SumBy can take a function as second argument. You can use it to access the ingredients of each items and use SumBy once again.

const data = [{ item_name: 'Jumbo Combo', item_price: 25, item_key: '9lazhy15tp2fgo72', quantity: 1, ingredients: [{ group_key: 'fg1udvnz81qwpxtp', key: 'kcck54k7h3fzp5f0', ingredient_name: 'Large', price: 3 }]}, { item_name: 'Swiss & Mushroom Combo', item_key: 'e1vdfos6s50d5kej', item_price: 22, quantity: 1, ingredients: [{ group_key: 'fg1udvnz81qwpxtp', key: 'kcck54k7h3fzp5f0', ingredient_name: 'Large', price: 3 }]}];

const sum = _.sumBy(data, item => item.item_price + _.sumBy(item.ingredients, 'price'));

console.log(sum);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script></code>```

Title: how to deep _sumBy using lodash?

Body:
var data= [{
        "item_name": "Jumbo Combo",
        "item_key": "9lazhy15tp2fgo72",
        "item_price": 25,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }, {
        "item_name": "Swiss & Mushroom Combo",
        "item_key": "e1vdfos6s50d5kej",
        "item_price": 22,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }]

i want to sum the item_price as well as "ingredients":[{"price":3}] using loadash how to deep sumBy

i tryed item_price

_.sumBy(data, 'item_price')

this can get the total price of item price in an array, but how to get sum of price of ingredients and item_price

Body:
Lodash#SumBy can take a function as second argument. You can use it to access the ingredients of each items and use SumBy once again.

const data = [{ item_name: 'Jumbo Combo', item_price: 25, item_key: '9lazhy15tp2fgo72', quantity: 1, ingredients: [{ group_key: 'fg1udvnz81qwpxtp', key: 'kcck54k7h3fzp5f0', ingredient_name: 'Large', price: 3 }]}, { item_name: 'Swiss & Mushroom Combo', item_key: 'e1vdfos6s50d5kej', item_price: 22, quantity: 1, ingredients: [{ group_key: 'fg1udvnz81qwpxtp', key: 'kcck54k7h3fzp5f0', ingredient_name: 'Large', price: 3 }]}];

const sum = _.sumBy(data, item => item.item_price + _.sumBy(item.ingredients, 'price'));

console.log(sum);

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>


问:
if (view == null) issues in fragment
I have updated my Sdk Oreo 8.0 When i come my current fragment to my previous fragment its crash because i am using if (view == null)
if i removed this condition it 'll work fine but have to load again view. </p>

```<code>@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.home_fragement_layout, container, false);
            ButterKnife.bind(this, view);
            bundle=getArguments();
            registrationResponse=(RegistrationResponse)bundle.getSerializable("registerresponse");
            setadapter();
            hitUserFavouriteOutfitsapi();
           swipeRefreshLayout.setOnRefreshListener(this);
        }
        toolBarTopChangeState =((ToolBarTopChangeState)context);
        toolBarTopChangeState.stateChangeToolBarIcon(0);
        toolBarTopChangeState.stateChangeToolBarText(getString(R.string.app_name));
        return view;
    }
</code>```

答:
Use this code:</p>

```<code>@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_fragement_layout, container, false);
        ButterKnife.bind(this, view);
        bundle=getArguments();
        registrationResponse=(RegistrationResponse)bundle.getSerializable("registerresponse");
        setadapter();

        hitUserFavouriteOutfitsapi();
        swipeRefreshLayout.setOnRefreshListener(this);
        toolBarTopChangeState =((ToolBarTopChangeState)context);
        toolBarTopChangeState.stateChangeToolBarIcon(0);
        toolBarTopChangeState.stateChangeToolBarText(getString(R.string.app_name));
        return view;
}
</code>```

Title: if (view == null) issues in fragment

Body:
I have updated my Sdk Oreo 8.0 When i come my current fragment to my previous fragment its crash because i am using if (view == null)
if i removed this condition it 'll work fine but have to load again view.

@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.home_fragement_layout, container, false);
            ButterKnife.bind(this, view);
            bundle=getArguments();
            registrationResponse=(RegistrationResponse)bundle.getSerializable("registerresponse");
            setadapter();
            hitUserFavouriteOutfitsapi();
           swipeRefreshLayout.setOnRefreshListener(this);
        }
        toolBarTopChangeState =((ToolBarTopChangeState)context);
        toolBarTopChangeState.stateChangeToolBarIcon(0);
        toolBarTopChangeState.stateChangeToolBarText(getString(R.string.app_name));
        return view;
    }

Body:
Use this code:

@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_fragement_layout, container, false);
        ButterKnife.bind(this, view);
        bundle=getArguments();
        registrationResponse=(RegistrationResponse)bundle.getSerializable("registerresponse");
        setadapter();

        hitUserFavouriteOutfitsapi();
        swipeRefreshLayout.setOnRefreshListener(this);
        toolBarTopChangeState =((ToolBarTopChangeState)context);
        toolBarTopChangeState.stateChangeToolBarIcon(0);
        toolBarTopChangeState.stateChangeToolBarText(getString(R.string.app_name));
        return view;
}


问:
How can I uncheck the options from multiple selected select pickers
I want to uncheck the selected options from the select picker based on the  values passed into a function.

To achieve this I'm using the below code. I'm using the onclick event to uncheck the options a,b...

```<code>$("#select1 option[value='"+myname+"']").prop("selected", false);
</code>```

function rem(myname) {
  $("#select1 option[value='" + myname + "']").prop("selected", false);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>

<div class="container body-content">
  Select Fee Types
  <select class="selectpicker form-control" id="select1" name="select1" data-width="200px" data-size="4" data-live-search="true" multiple>
<option disabled>Select</option>
<option value="a,b" selected>a</option>
<option value="d,c" selected>c</option>
<option value="f,e">e</option>
 </select>
</div>

<button onclick=r em( 'a,b')>Unselect</button></code>```

答:
Ok, so you have two options. If you want only to deselect specific values you can do it as shown in snippet. If you want to deselect all values you can simply do it like this: $("#select1").selectpicker('deselectAll'); (source)

How did I find the answer? I typed "bootstrap-select methods" in google browser and it was first result. Please before you ask a question do some research by your own :) If you did, then no problem ;)

function rem(myname) {
  $("#select1 option[value='" + myname + "']").prop("selected", false);
  $("#select1").selectpicker('refresh');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>

<div class="container body-content">
  Select Fee Types
  <select class="selectpicker form-control" id="select1" name="select1" data-width="200px" data-size="4" data-live-search="true" multiple>
<option disabled>Select</option>
<option value="a,b" selected>a</option>
<option value="d,c" selected>c</option>
<option value="f,e">e</option>
 </select>
</div>

<button onclick="rem('a,b')">Unselect</button></code>```

Body:
I want to uncheck the selected options from the select picker based on the  values passed into a function.

To achieve this I'm using the below code. I'm using the onclick event to uncheck the options a,b...

$("#select1 option[value='"+myname+"']").prop("selected", false);

function rem(myname) {
  $("#select1 option[value='" + myname + "']").prop("selected", false);

}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">

  Select Fee Types
  <select class="selectpicker form-control" id="select1" name="select1" data-width="200px" data-size="4" data-live-search="true" multiple>
<option disabled>Select</option>
<option value="a,b" selected>a</option>
<option value="d,c" selected>c</option>
<option value="f,e">e</option>
 </select>

<button onclick=r em( 'a,b')>Unselect</button>

Body:
Ok, so you have two options. If you want only to deselect specific values you can do it as shown in snippet. If you want to deselect all values you can simply do it like this: $("#select1").selectpicker('deselectAll'); (source)

How did I find the answer? I typed "bootstrap-select methods" in google browser and it was first result. Please before you ask a question do some research by your own :) If you did, then no problem ;)

function rem(myname) {
  $("#select1 option[value='" + myname + "']").prop("selected", false);
  $("#select1").selectpicker('refresh');
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>

<div class="container body-content">
  Select Fee Types
  <select class="selectpicker form-control" id="select1" name="select1" data-width="200px" data-size="4" data-live-search="true" multiple>
<option disabled>Select</option>
<option value="a,b" selected>a</option>
<option value="d,c" selected>c</option>
<option value="f,e">e</option>
 </select>
</div>

<button onclick="rem('a,b')">Unselect</button>


问:
Handling File Upload Exception - Laravel
This is how i upload a file into my database but i am not able to handle my exception when the file uploaded is an invalid format or type.

I am able to handle exception when no file is uploaded but not when the file type is invalid or does not meet the standard.

How do i get this done please?

Controller

```<code> public function import($id, Request $request)
    {

       $country= Country::all()->where('id',$id)->first();

           if($request->file('imported-file'))
           {
                     $path = $request->file('imported-file')->getRealPath();
                     $data = Excel::load($path, function($reader)
               {
                     })->get();

               if(!empty($data) && $data->count())
               {
                 foreach ($data->toArray() as $row)
                 {
                   if(!empty($row))
                   {
                     $dataArray[] =
                     [
                       'name' => $row['name'],

                     ];
                   }
    else {
            return redirect('admin')->with('error','File format Error');

         }
               }

               if(!empty($dataArray))
               {
                $country->teams()->createMany($dataArray);
                 return redirect('admin')->with('status','Countries successfully added');

                }
              }
            }
else {
            return redirect('admin')->with('error','No file was uploaded');

         }

        }
</code>```

答:
From Laravel's documentation, You can accept only a certain type of file using mime validation rule,

```<code>        'file' => 'required | mimes:application/vnd.ms-excel',
</code>```

The mime-type application/vnd.ms-excel will match these file extensions xls xlm xla xlc xlt xlw

Body:
This is how i upload a file into my database but i am not able to handle my exception when the file uploaded is an invalid format or type.

I am able to handle exception when no file is uploaded but not when the file type is invalid or does not meet the standard.

How do i get this done please?

Controller

 public function import($id, Request $request)
    {

       $country= Country::all()->where('id',$id)->first();

           if($request->file('imported-file'))
           {
                     $path = $request->file('imported-file')->getRealPath();
                     $data = Excel::load($path, function($reader)
               {
                     })->get();

               if(!empty($data) && $data->count())
               {
                 foreach ($data->toArray() as $row)
                 {
                   if(!empty($row))
                   {
                     $dataArray[] =
                     [
                       'name' => $row['name'],

                     ];
                   }
    else {
            return redirect('admin')->with('error','File format Error');

         }
               }

               if(!empty($dataArray))
               {
                $country->teams()->createMany($dataArray);
                 return redirect('admin')->with('status','Countries successfully added');

                }
              }
            }
else {
            return redirect('admin')->with('error','No file was uploaded');

         }

        }

Body:
From Laravel's documentation, You can accept only a certain type of file using mime validation rule,

        'file' => 'required | mimes:application/vnd.ms-excel',

The mime-type application/vnd.ms-excel will match these file extensions xls xlm xla xlc xlt xlw


问:
ExpressionChangedAfterIsHasBeenCheckedError because of updating my dropdownlist in angular 2
As the title says I'm getting an ExpressionChangedAfterIsHasBeenCheckedError and after reading this article, from what I understand it is a cautionary put in place to prevent inconsistencies. Exactly those words. So at some point I'm probably violating the unidirectional flow (I assume).
What I have:

A dropdown box.

```<code><select id="product" [(ngModel)]="model.searchParameters.productId">
 <option *ngFor="let product of products [value]="product.id">{{product.name}}</option>
</select>
</code>```

An input box which triggers checkIban.

```<code><div *ngIf="checkIban(productnumber, searchForm)">
   //show validation errors
</div>

checkIban(field: any, form: any): Boolean {
    if(field.dirty)
    {
        if(field.viewModel.length === Productnumber.Iban )
        {
           this.model.searchParameters.productId = Product.Ibannumber;
        }
    }
}
</code>```

I'd like to think I understand the concept of the ExpressionChangedAfterIsHasBeenCheckedError, unfortunately for me, not well enough to truly apply a proper solution to this problem.

Using setTimeout is not an option (I've tried) as it creates an unpredictable state (as was written in the article).
So can someone give me some pointers as to what I'm doing wrong?

答:
Binding to a function in the view is usually a bad idea in Angular, because the function will be called every time change detection runs. When 2 subsequent calls (during a single change detection run) return 2 different results, you get the error message in your question.

Instead use an event to update the result and assign it to a field in your component and then bind to that field instead:

```<code><select id="product" [(ngModel)]="model.searchParameters.productId"
    (ngModelChange)="checkIban()">
 <option *ngFor="let product of products [value]="product.id">{{product.name}}</option>
</select>

<div *ngIf="isIbanOk">
   //show validation errors
</div>
</code>```

```<code>checkIban(field: any, form: any): Boolean {
    ...

    this.isIbanOk = result; // true or false
}
</code>```

Body:
As the title says I'm getting an ExpressionChangedAfterIsHasBeenCheckedError and after reading this article, from what I understand it is a cautionary put in place to prevent inconsistencies. Exactly those words. So at some point I'm probably violating the unidirectional flow (I assume).
What I have:

A dropdown box.

<select id="product" [(ngModel)]="model.searchParameters.productId">
 <option *ngFor="let product of products [value]="product.id">{{product.name}}</option>
</select>

An input box which triggers checkIban.

   //show validation errors

checkIban(field: any, form: any): Boolean {
    if(field.dirty)
    {
        if(field.viewModel.length === Productnumber.Iban )
        {
           this.model.searchParameters.productId = Product.Ibannumber;
        }
    }
}

I'd like to think I understand the concept of the ExpressionChangedAfterIsHasBeenCheckedError, unfortunately for me, not well enough to truly apply a proper solution to this problem.

Using setTimeout is not an option (I've tried) as it creates an unpredictable state (as was written in the article).
So can someone give me some pointers as to what I'm doing wrong?

Body:
Binding to a function in the view is usually a bad idea in Angular, because the function will be called every time change detection runs. When 2 subsequent calls (during a single change detection run) return 2 different results, you get the error message in your question.

Instead use an event to update the result and assign it to a field in your component and then bind to that field instead:

<select id="product" [(ngModel)]="model.searchParameters.productId"
    (ngModelChange)="checkIban()">
 <option *ngFor="let product of products [value]="product.id">{{product.name}}</option>
</select>

<div *ngIf="isIbanOk">
   //show validation errors
</div>

checkIban(field: any, form: any): Boolean {
    ...

    this.isIbanOk = result; // true or false
}


问:
c programming using execvp
I'm working on a side project where I want to spawn 5 children processes then execvp into a second program called isEven which will tell if the number passed to it is even or not. However, the execvp call keeps failing as I ran it in gdb and it doesn't execute.
Args and load(args) are both called in another function.

Thanks in advance!!!

```<code>//Code to load binary
void load(char* args[])
{
    execvp("./isEven", args);
    printf("ERROR\n");
}

//args being passed in
char *args[] = {"./isEven", number, NULL};
load(args);
</code>```

Here is a smaller program I wrote which does the same thing I'm trying to do right now. Gdb says I am getting a segmentation fault.

```<code>int main(int argc, char *argv[])
{
    int returnCode = fork();

    if(returnCode == 0)
    {
        char *args[] = {"./isEven", 12345, NULL};
        execvp("./isEven", args);
        printf(errno);
        printf("ERROR: execvp failed\n");
        exit(-1);
    }
    else if(returnCode < 0)
    {
        fprintf(stderr, "fork failed\n");
    }
    else
    {
        //i am the parent
        printf("I am the parent");
    }
    return 1;
}
</code>```

答:
The main problem is with this line:

```<code>char *args[] = {"./isEven", 12345, NULL};
</code>```

The args passed to execvp must be an array of char*. Having 12345 as an argument makes it interpret it as address and it's unlikely to be a valid address. In any case, that's not what you wanted to pass. So do:

```<code>char *args[] = {"./isEven", "12345", NULL};
</code>```

You need to convert number into a string. For example:

```<code>int number = 12345;
char num_str[256];
snprintf(num_str, sizeof num_str, "%d", number);
char *args[] = {"./isEven", num_str, NULL};
execvp("./isEven", args);
perror("exec");
</code>```

In your modified example, you are printing errno as:

```<code>printf(errno);
</code>```

This will fail because printf expects a string as its first argument. You can use perror() to print the error as shown above.

Title: c programming using execvp

Body:
I'm working on a side project where I want to spawn 5 children processes then execvp into a second program called isEven which will tell if the number passed to it is even or not. However, the execvp call keeps failing as I ran it in gdb and it doesn't execute.
Args and load(args) are both called in another function.

Thanks in advance!!!

//Code to load binary
void load(char* args[])
{
    execvp("./isEven", args);
    printf("ERROR\n");
}

//args being passed in
char *args[] = {"./isEven", number, NULL};
load(args);

Here is a smaller program I wrote which does the same thing I'm trying to do right now. Gdb says I am getting a segmentation fault.

int main(int argc, char *argv[])
{
    int returnCode = fork();

    if(returnCode == 0)
    {
        char *args[] = {"./isEven", 12345, NULL};
        execvp("./isEven", args);
        printf(errno);
        printf("ERROR: execvp failed\n");
        exit(-1);
    }
    else if(returnCode < 0)
    {
        fprintf(stderr, "fork failed\n");
    }
    else
    {
        //i am the parent
        printf("I am the parent");
    }
    return 1;
}

Body:
The main problem is with this line:

char *args[] = {"./isEven", 12345, NULL};

The args passed to execvp must be an array of char*. Having 12345 as an argument makes it interpret it as address and it's unlikely to be a valid address. In any case, that's not what you wanted to pass. So do:

char *args[] = {"./isEven", "12345", NULL};

You need to convert number into a string. For example:

int number = 12345;
char num_str[256];
snprintf(num_str, sizeof num_str, "%d", number);
char *args[] = {"./isEven", num_str, NULL};
execvp("./isEven", args);
perror("exec");

In your modified example, you are printing errno as:

printf(errno);

This will fail because printf expects a string as its first argument. You can use perror() to print the error as shown above.


问:
Google Tag manager: get the amount of time (minutes/seconds) it takes to complete progress
I have an issue with tracking the completion of a progress within a web application. I want to track the amount of time it take for a user to finish a process (let's say he fills in an form, get's a confirmation and accepts the term/confirmation).
The process takes place in three different pages.

These are the three pseudo pages:

```<code>Page 1: Form
Page 2: Confirmation
Virtual pageview: Registration completed
</code>```

The Virtual pageview is being made when the user has pressed the submit button and there are no errors on the screen.

What I would like to know now is:

How to track the amount of time (seconds/minutes) it took the user to complete the registration? (in GTM)

答:
You can use custom HTML in GTM just start a timer when the user is on the first page and start filling the form on page unload save the time in a cookie.
At the last page when the registration is complete send an event with the cookie value containing the total time taken by the user in event value. Later you can analyze the average time.</p>

Body:
I have an issue with tracking the completion of a progress within a web application. I want to track the amount of time it take for a user to finish a process (let's say he fills in an form, get's a confirmation and accepts the term/confirmation).
The process takes place in three different pages.

These are the three pseudo pages:

Page 1: Form
Page 2: Confirmation
Virtual pageview: Registration completed

The Virtual pageview is being made when the user has pressed the submit button and there are no errors on the screen.

What I would like to know now is:

How to track the amount of time (seconds/minutes) it took the user to complete the registration? (in GTM)


问:
Dynamics 2016 email tracking ignoring outgoing replies
We have server-side synchronisation set up for our Dynamics 2016 on-premise instance, and it is correctly sending emails from a Case, and tracking replies from the customer.  However, when an internal user replies using Outlook (without the CRM add in), their responses aren't being tracked.  This means that the email conversation consists of an initial "outgoing" email, followed by only incoming responses.

The full scenario is:

Internal user sends an email from a CRM Case.  Email tracked in CRM

Customer replies to email.  Reply tracked in CRM and goes to internal user's Outlook

Internal user sends a reply from their Outlook.  Reply is not tracked in CRM

Customer replies to email.  Reply tracked in CRM and goes to internal user's Outlook

Is it possible to allow the Internal user's replies (point 3) to be tracked in CRM without installing the Outlook add in (i.e. so it also works from the Web/mobile versions of Outlook)?

答: I have heard back from our Microsoft Partner, and they say that this scenario isn't possible.  By design, it'll only track incoming emails to CRM, or outgoing if sent from within CRM itself.</p>


问:
Find distance to waypoints? Or waypoint within x miles?
This is more of a theoretical question on how to do it rather then an actual programming question. Target platform is Android, though.

I have a list of waypoints. And I have my current position. I want to know if any of the waypoints are close to me, eg. +/-5 km. I could calculate the distans to each waypoint seperately to find out if it is within the specified radius, but isn't there a better way to do this? Like, are these points included in this area (area beeing a 5km circle around my position) (you can do something like this when working with graphics and click/touch events)?

Any help is appreciated!

/Magnus

答:
What you are looking for is Geo-spatial analysis? There is an open source java project for this.

http://java-source.net/open-source/geospatial

Google of course provides this service as part of pro maps package.

http://www.google.com/enterprise/earthmaps/index.html

(Note: I use semantic technology and allegrograph provides a decent geospatial api)


问:
wxPython get colour of panel
I am trying to retrieve the background colour of a panel in wxPython

```<code>import wx

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Panel colour')
        panel = MainPanel(self)
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(panel)
        self.SetSizerAndFit(main_sizer)

        self.Centre()
        self.Show()
        print(self.GetBackgroundColour())
        print(panel.GetBackgroundColour())

class MainPanel(wx.Panel):
    def __init__(self, frame):
        wx.Panel.__init__(self, frame)
        lbl_description = wx.StaticText(self, label='Hello world')
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(lbl_description, flag=wx.ALL, border=10)
        self.SetSizer(main_sizer)

if __name__ == "__main__":
    screen_app = wx.App()
    main_frame = MainFrame()
    screen_app.MainLoop()
</code>```

but the output I get is

```<code>(225, 225, 225, 255)
(225, 225, 225, 255)
</code>```

Clearly, I am doing something wrong. How should I get it?

答:
These numbers gives you the colour as RGB values.

RGB colours are defined by three values for Red, Green and Blue going from 0 to 255. The fourth  values is the alpha value (transparency).

Title: wxPython get colour of panel

Body:
I am trying to retrieve the background colour of a panel in wxPython

import wx

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Panel colour')
        panel = MainPanel(self)
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(panel)
        self.SetSizerAndFit(main_sizer)

        self.Centre()
        self.Show()
        print(self.GetBackgroundColour())
        print(panel.GetBackgroundColour())

class MainPanel(wx.Panel):
    def __init__(self, frame):
        wx.Panel.__init__(self, frame)
        lbl_description = wx.StaticText(self, label='Hello world')
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(lbl_description, flag=wx.ALL, border=10)
        self.SetSizer(main_sizer)

if __name__ == "__main__":
    screen_app = wx.App()
    main_frame = MainFrame()
    screen_app.MainLoop()

but the output I get is

(225, 225, 225, 255)
(225, 225, 225, 255)

Clearly, I am doing something wrong. How should I get it?


问:
.NET hot deploy/undeploy of bundled code. How to? Which container?
We are new to the .NET world and have built a small C# application on top of Nancy

We are looking for a way to "package" the application code so that we can programmatically hot deploy and undeploy it on top of a minimal Nancy based container (or any other appropriate container you may suggest)

How do we do this in the .NET world ?

In the JVM world, one way to do it is to package a Web Application Resource (war) that is deployed on top of a servlet engine, typically Jetty or Tomcat. There are other solutions (micro-containers, using class loaders directly, etc..). We are looking of an equivalent .NET paradigm.

EDIT Dec 5

There seems to be solutions around building Assemblies and using methods such as Assembly.LoadFromString.

This still seems pretty manual and we are looking for a C# library/framework to help with loading/unloading

答:
Unfortunately, it's not a typical task in .NET world, so you won't necessarily find a simple widely used plug-ins solution.

There is Managed Extensibility Framework, later known as  Microsoft.Composition, later known as System.Composition.
Please check How to discover new MEF parts while the application is running? as it may be a solution you are looking for.

There are some articles on using System.Composition with .NET Core as well.

It's not hard to implement a plugin system yourself though using an IoC framework like AutoFac .

Let's assume your application has Nancy modules which do call services, and the services implement the actual logic you may want to change dynamically. That makes a service essentially a plugin. The idea is to make IoC to return an updated instance of a service for every http call.

You could have a scoped service provider \ factory which will resolve and create a service instance from a refreshed assembly using reflection.

You could refresh services collection container (or create a new IoC container) on assembly reload.

Sadly, in both cases you will have to manually detect an assembly file changed, but this is a trivial job with FileSystemWatcher class.

Also, in some IoC libraries updating dependencies in runtime is not considered a good practice, take a look here, for example.


问:
Coded UI Throws "Unable to load one or more of the requested types"
I am unable to get Coded UI debugging to work. Visual Studio won't stop on a breakpoint. A simple demo test (which merely enters a number into an Excel worksheet cell) succeeds when it's run without debugging. But when debugging the test, the test runner errors immediately without attempting to step into the test-class constructor (if provided) or into the test-method.

The error reported is:

```<code>Message: Unit Test Adapter threw exception:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information..
</code>```

I'm running Visual Studio 2017, Version 15.5.0.

The Debug window's output:

```<code>'testhost.x86.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\testhost.x86.exe'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: testhost.x86.exe): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.TestPlatform.CoreUtilities.dll'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: testhost.x86.exe): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.TestPlatform.PlatformAbstractions.dll'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: testhost.x86.exe): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.VisualStudio.TestPlatform.ObjectModel.dll'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: testhost.x86.exe): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.TestPlatform.CrossPlatEngine.dll'. Cannot find or open the PDB file.

...

'QTAgent32_40.exe' (CLR v4.0.30319: TestAppDomain: 0bb1983f-0f53-41cc-b4ed-143874102a64): Unloaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel.dll'
'QTAgent32_40.exe' (CLR v4.0.30319: TestAppDomain: 0bb1983f-0f53-41cc-b4ed-143874102a64): Unloaded 'C:\VST\CodedUITestProject2\TestResults\abcdef_X#XXX## 2017-12-05 11_05_06\Out\CodedUITestProject2.dll'
The thread 0x1860 has exited with code 0 (0x0).
The thread 0x1dcc has exited with code 0 (0x0).
Exception thrown: 'System.Threading.ThreadInterruptedException' in mscorlib.dll
The thread 0x1cb0 has exited with code 0 (0x0).
The thread 0x2d54 has exited with code 0 (0x0).
The thread 0x2a40 has exited with code 0 (0x0).
The thread 0x1e04 has exited with code 0 (0x0).
The program '[8104] QTAgent32_40.exe: Program Trace' has exited with code 0 (0x0).
The thread 0x1714 has exited with code 0 (0x0).
The thread 0x265c has exited with code 0 (0x0).
The program '[8104] QTAgent32_40.exe' has exited with code 0 (0x0).
The thread 0x2d9c has exited with code 0 (0x0).
The thread 0xde4 has exited with code 0 (0x0).
The thread 0x3bc has exited with code 0 (0x0).
The thread 0x253c has exited with code 0 (0x0).
The program '[12012] testhost.x86.exe: Program Trace' has exited with code 0 (0x0).
The program '[12012] testhost.x86.exe' has exited with code 0 (0x0).
</code>```

I've tried repaving Visual Studio and installing the latest bits, etc. to no avail. And I'm experiencing this issue on two different machines.

答:
I use the latest VS2017 15.5, it really has this issue:

But in other VS version or VS 2017 15.4.4,it really has no this issue.

Since I could repro this issue, I help you report this feedback to the product team here:

https://developercommunity.visualstudio.com/content/problem/161803/cant-debug-coded-ui-test-in-latest-vs2017.html

If possible, you could add your comment and vote this feedback.

Update:

I update my VS2017 to 15.5.1 version, and then set the System environment variable like the following screen shot, Note: Your VS2017 would be installed to the path like C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE. And then I restart the VS IDE and reopen the test project, I could debug it well now.

Since the latest VS version was the 15.5.2, please also update it to the latest version.

Body:
I am unable to get Coded UI debugging to work. Visual Studio won't stop on a breakpoint. A simple demo test (which merely enters a number into an Excel worksheet cell) succeeds when it's run without debugging. But when debugging the test, the test runner errors immediately without attempting to step into the test-class constructor (if provided) or into the test-method.

The error reported is:

Message: Unit Test Adapter threw exception:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information..

I'm running Visual Studio 2017, Version 15.5.0.

The Debug window's output:

'testhost.x86.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\testhost.x86.exe'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: testhost.x86.exe): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.TestPlatform.CoreUtilities.dll'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: testhost.x86.exe): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.TestPlatform.PlatformAbstractions.dll'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: testhost.x86.exe): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.VisualStudio.TestPlatform.ObjectModel.dll'. Cannot find or open the PDB file.
'testhost.x86.exe' (CLR v4.0.30319: testhost.x86.exe): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.TestPlatform.CrossPlatEngine.dll'. Cannot find or open the PDB file.

...

'QTAgent32_40.exe' (CLR v4.0.30319: TestAppDomain: 0bb1983f-0f53-41cc-b4ed-143874102a64): Unloaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel.dll'
'QTAgent32_40.exe' (CLR v4.0.30319: TestAppDomain: 0bb1983f-0f53-41cc-b4ed-143874102a64): Unloaded 'C:\VST\CodedUITestProject2\TestResults\abcdef_X#XXX## 2017-12-05 11_05_06\Out\CodedUITestProject2.dll'
The thread 0x1860 has exited with code 0 (0x0).
The thread 0x1dcc has exited with code 0 (0x0).
Exception thrown: 'System.Threading.ThreadInterruptedException' in mscorlib.dll
The thread 0x1cb0 has exited with code 0 (0x0).
The thread 0x2d54 has exited with code 0 (0x0).
The thread 0x2a40 has exited with code 0 (0x0).
The thread 0x1e04 has exited with code 0 (0x0).
The program '[8104] QTAgent32_40.exe: Program Trace' has exited with code 0 (0x0).
The thread 0x1714 has exited with code 0 (0x0).
The thread 0x265c has exited with code 0 (0x0).
The program '[8104] QTAgent32_40.exe' has exited with code 0 (0x0).
The thread 0x2d9c has exited with code 0 (0x0).
The thread 0xde4 has exited with code 0 (0x0).
The thread 0x3bc has exited with code 0 (0x0).
The thread 0x253c has exited with code 0 (0x0).
The program '[12012] testhost.x86.exe: Program Trace' has exited with code 0 (0x0).
The program '[12012] testhost.x86.exe' has exited with code 0 (0x0).

I've tried repaving Visual Studio and installing the latest bits, etc. to no avail. And I'm experiencing this issue on two different machines.


问:
android studio platform-tools missing adb.exe
Today, I clicked some update when I launch Android Stodio. I forgot what it is. Then, I run some code when there is a error
"8:34 PM    IllegalArgumentException: Unable to locate adb"

Then, I google for few hours and still cannot solve my problem. And I found that there is no "adb.exe" under my platform-tools folder.

Can someone help?

my os is Window 10.
I have tried uninstall Android Studio and install it back. It doesn't help.

Edit 1: After I re-install the platform-tools, I get back the adb.exe.But, I run my program again, it does the "ADB initialization", my adb.exe file lose again.

答:
I am writing the solution which worked for me:

go to SDK Platform Tools;

download SDK Platform-Tools for Windows;

extract zip file and copy to \AppData\Local\Android\sdk\platform-tools.


问:
IntelliJ/PhpStorm inline @var with magic fields
I am trying to define with a PHPDoc inline @var a magic field variable to set the correct type but the IDE is not auto-completing anything.

It is showing "Field accessed via magic method". I tried to remove it from the Inspections settings but then the warning is not showed and still it is not auto-completing.

I have tried different ways without success:

/** @var \NameSpace\SomeClass $this->field */
$this->field->someMethod(); // Not auto-completing

/** @var \NameSpace\SomeClass $this::field */
$this->field->someMethod(); // Not auto-completing
```

<p>For other hand if I define a new variable it will work:</p>

<pre class="lang-php prettyprint-override"><code>$field = $this->field;

/** @var \NameSpace\SomeClass $field */
$field->someMethod(); // Auto-completing correctly
</code>```

Somebody knows how to do it to work the auto-completing feature without define a new variable? Is it possible?

UPDATE: I cannot use the @property attribute because $field is not always the same class in the main class.

答:
It is not possible to provide typehint for 2nd level variable/element ($this->field) using inline @var (thank to @LazyOne).

So a possible solution would be set the @property with all classes using in the main class:

```<code>/**
 * My special class
 *
 * @property \NameSpace\SomeClass|OtherSomeClass|OneMore $field
 */
class MySpecialClass {
</code>```

By this way the magic field $field would be auto-completing with all method of all classes defined.

Body:
I am trying to define with a PHPDoc inline @var a magic field variable to set the correct type but the IDE is not auto-completing anything.

It is showing "Field accessed via magic method". I tried to remove it from the Inspections settings but then the warning is not showed and still it is not auto-completing.

I have tried different ways without success:

/** @var \NameSpace\SomeClass $this->field */
$this->field->someMethod(); // Not auto-completing

/** @var \NameSpace\SomeClass $this::field */
$this->field->someMethod(); // Not auto-completing

For other hand if I define a new variable it will work:

$field = $this->field;

/** @var \NameSpace\SomeClass $field */
$field->someMethod(); // Auto-completing correctly

Somebody knows how to do it to work the auto-completing feature without define a new variable? Is it possible?

UPDATE: I cannot use the @property attribute because $field is not always the same class in the main class.

Body:
It is not possible to provide typehint for 2nd level variable/element ($this->field) using inline @var (thank to @LazyOne).

So a possible solution would be set the @property with all classes using in the main class:

/**
 * My special class
 *
 * @property \NameSpace\SomeClass|OtherSomeClass|OneMore $field
 */
class MySpecialClass {

By this way the magic field $field would be auto-completing with all method of all classes defined.


问:
writing xpath for getting a row in a table
If I write the XPath for a row in a table which is expandable, like each row is expandable on the table. it has a dropdown. if I click on the dropdown of the row, I get to see some stuff inside it.

if I want to write XPath for the body inside the dropdown. ex: for the second row, I get it by writing the XPath:

//div[@class=‘react-bs-container-body’]//tbody/tr[2]

If i write the  following xpath :

//div[@class=‘react-bs-container-body’]//tbody/tr[td[@tabindex="7"]]

where I am trying to access the same thing by giving the attribute of the column which is unique. Xpath should give me the body inside the dropdown.

but this is not happening. The second case won't work. Can anyone tell me why?

答:
You can try this xpath with single quotations,

```<code>//div[@class=‘react-bs-container-body’]//tbody/tr[td[@tabindex='7']]
</code>```

Also, you can try with the below xpath as well

```<code>//div[@class=‘react-bs-container-body’]//tbody/tr[td[7]]
</code>```

Body:
You can try this xpath with single quotations,

//div[@class=‘react-bs-container-body’]//tbody/tr[td[@tabindex='7']]

Also, you can try with the below xpath as well

//div[@class=‘react-bs-container-body’]//tbody/tr[td[7]]


问:
Optimal way to get last posts of user's friends in Firebase
In my DB each user has friends. And I need to get 50 last posts of the user's friends. See below structure of posts of each user in Firebase DB.

So what is optimal way to do that? If a user has for example 150 friends, then my Android app should have as many listeners as friends. Is it ok to have 150 or more DB listeners in the app? Also what is the way to get all friends' posts in single query? Thanks.

```<code>root
- posts
  - {userUid}
    - {postUid}
      - text
      - dateCreated
</code>```

答:
You can have as many listeners as you want with the condition to remove them according to your life-cycle of your activity. But in your case, you don't need 150 listeners, you only need just one. Assuming that the node under the user is is named friends, you can attach a single listener on friends node and then iterate over the DataSnapshot object using getChildren() method. Assuming that your database looks simmilar with this:

```<code>Firebase-root
  |
  --- users
       |
       --- uid1
            |
            --- friends
                  |
                  --- friendId1: true
                  |
                  --- friendId2: true
</code>```

To get all the friends that corespond to a particular user, please use the following code:

```<code>String uid = firebaseAuth.getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendsRef = rootRef.child("users").child(uid).child(friends);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String friendId = ds.getKey();
            Log.d("TAG", friendId);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
friendsRef.addListenerForSingleValueEvent(eventListener);
</code>```

To get all post that of all users, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("posts");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String uid = ds.getKey();

            DatabaseReference uidRef = postsRef.child(uid);
            ValueEventListener eventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
                        String text = dSnapshot.child("text").getValue(String.class);
                        long dateCreated = dSnapshot.child("dateCreated").getValue(Long.class);
                        Log.d("TAG", text + " / " + dateCreated)
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            };
            uidRef.addListenerForSingleValueEvent(eventListener);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(valueEventListener);
</code>```

Body:
In my DB each user has friends. And I need to get 50 last posts of the user's friends. See below structure of posts of each user in Firebase DB.

So what is optimal way to do that? If a user has for example 150 friends, then my Android app should have as many listeners as friends. Is it ok to have 150 or more DB listeners in the app? Also what is the way to get all friends' posts in single query? Thanks.

root
- posts
  - {userUid}
    - {postUid}
      - text
      - dateCreated

Body:
You can have as many listeners as you want with the condition to remove them according to your life-cycle of your activity. But in your case, you don't need 150 listeners, you only need just one. Assuming that the node under the user is is named friends, you can attach a single listener on friends node and then iterate over the DataSnapshot object using getChildren() method. Assuming that your database looks simmilar with this:

Firebase-root
  |
  --- users
       |
       --- uid1
            |
            --- friends
                  |
                  --- friendId1: true
                  |
                  --- friendId2: true

To get all the friends that corespond to a particular user, please use the following code:

String uid = firebaseAuth.getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendsRef = rootRef.child("users").child(uid).child(friends);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String friendId = ds.getKey();
            Log.d("TAG", friendId);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
friendsRef.addListenerForSingleValueEvent(eventListener);

To get all post that of all users, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("posts");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String uid = ds.getKey();

            DatabaseReference uidRef = postsRef.child(uid);
            ValueEventListener eventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
                        String text = dSnapshot.child("text").getValue(String.class);
                        long dateCreated = dSnapshot.child("dateCreated").getValue(Long.class);
                        Log.d("TAG", text + " / " + dateCreated)
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            };
            uidRef.addListenerForSingleValueEvent(eventListener);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(valueEventListener);


问:
Pandas: Calculating value of difference between current column value and next column value depending if it meets criteria at a different column
I have a dataframe:

```<code>df = pd.DataFrame.from_items([('A', [10, 'foo']), ('B', [440, 'foo']), ('C', [790, 'bar']), ('D', [800, 'bar']), ('E', [7000, 'foo'])], orient='index', columns=['position', 'foobar'])
</code>```

Which looks like the below:

```<code>    position foobar
A   10       foo
B   440      foo
C   790      bar
D   800      bar
E   7000     foo
</code>```

I would like to know the difference between each position and the next position that has the opposite value in the foobar column. Normally I would use the shift method to move down the position column:

```<code>df[comparisonCol].shift(-1) - df[comparisonCol]
</code>```

but as I am using the foobar column to decide which position is applicable, I am not sure how to do this.

The result should look like:

```<code>    position foobar difference
A   10       foo      780
B   440      foo      350
C   790      bar      6210
D   800      bar      6200
E   7000     foo      NaN
</code>```

答:
I think you need if unique values in foobar are only 2, so is possible shift between groups in a Series:

```<code>#identify consecutive groups
a = df['foobar'].ne(df['foobar'].shift()).cumsum()
print (a)
A    1
B    1
C    2
D    2
E    3
Name: foobar, dtype: int32

#get first value by a of position column
b = df.groupby(a)['position'].first()
print (b)
foobar
1      10
2     790
3    7000
Name: position, dtype: int64

#subtract mapped value, but for next group is added 1 to a Series
df['difference'] = a.add(1).map(b) - df['position']
print (df)
   position foobar  difference
A        10    foo       780.0
B       440    foo       350.0
C       790    bar      6210.0
D       800    bar      6200.0
E      7000    foo         NaN
</code>```

Detail:

```<code>print (a.add(1).map(b))
A     790.0
B     790.0
C    7000.0
D    7000.0
E       NaN
Name: foobar, dtype: float64
</code>```

Body:
I have a dataframe:

df = pd.DataFrame.from_items([('A', [10, 'foo']), ('B', [440, 'foo']), ('C', [790, 'bar']), ('D', [800, 'bar']), ('E', [7000, 'foo'])], orient='index', columns=['position', 'foobar'])

Which looks like the below:

    position foobar
A   10       foo
B   440      foo
C   790      bar
D   800      bar
E   7000     foo

I would like to know the difference between each position and the next position that has the opposite value in the foobar column. Normally I would use the shift method to move down the position column:

df[comparisonCol].shift(-1) - df[comparisonCol]

but as I am using the foobar column to decide which position is applicable, I am not sure how to do this.

The result should look like:

    position foobar difference
A   10       foo      780
B   440      foo      350
C   790      bar      6210
D   800      bar      6200
E   7000     foo      NaN

Body:
I think you need if unique values in foobar are only 2, so is possible shift between groups in a Series:

#identify consecutive groups
a = df['foobar'].ne(df['foobar'].shift()).cumsum()
print (a)
A    1
B    1
C    2
D    2
E    3
Name: foobar, dtype: int32

#get first value by a of position column
b = df.groupby(a)['position'].first()
print (b)
foobar
1      10
2     790
3    7000
Name: position, dtype: int64

#subtract mapped value, but for next group is added 1 to a Series
df['difference'] = a.add(1).map(b) - df['position']
print (df)
   position foobar  difference
A        10    foo       780.0
B       440    foo       350.0
C       790    bar      6210.0
D       800    bar      6200.0
E      7000    foo         NaN

Detail:

print (a.add(1).map(b))
A     790.0
B     790.0
C    7000.0
D    7000.0
E       NaN
Name: foobar, dtype: float64


问:
Different code path according to different type in a template method
Let's say I have a template class like this:

```<code>template<typename TRequest, typename TResponse = void>
class handler
{
private:
    TResponse process_core(const TRequest& request);
public:
    TResponse process(const TRequest& request)
    {
        //log the request
        TResponse response = process_core(request);  //return process_core(request) works;
        //log the response, for void it's fine to log nothing
        return response;
    }
};
</code>```

Somewhere else in the project process_core is implemented for different TRequest/TResponse types. For example:

```<code>template<> void handler<Foo>::process_core(const Foo& foo) { }
template<> Baz handler<Bar, Baz>::process_core(const Bar& bar) { }
</code>```

Obviously return response breaks for void types. What's the correct way to do this? Or my design is not the C++ way? I'm new to C++.

答:
Unfortunately void is not a regular type, even though there's a proposal that aims to fix that ("regular void" by Matt Calabrese), so you need to handle it in a special way. With C++17, you can simply use if constexpr(...) to branch at compile-time:

```<code>TResponse process(const TRequest& request)
{
    TResponse response = process_core(request);
    // ...

    if constexpr(!std::is_same_v<TResponse, void>)
    {
        return response;
    }
}
</code>```

With C++11/14, you can use tag dispatching:

```<code>TResponse process(const TRequest& request)
{
    return processImpl(request, std::is_same<TResponse, void>{});
}

void process(const TRequest& request, std::true_type /* void */)
{
    TResponse response = process_core(request);
    // ...
}

TResponse process(const TRequest& request, std::false_type /* not void */)
{
    TResponse response = process_core(request);
    // ...
    return response;
}
</code>```

Alternatively, you can transform void into a regular nothing type and handle it homogeneously.

```<code>struct nothing { };

template <typename T>
struct void_to_nothing { using type = T; };

template <>
struct void_to_nothing<void> { using type = nothing; };

template <typename T>
using void_to_nothing_t = typename void_to_nothing<T>::type;

auto process(const TRequest& request)
{
    void_to_nothing_t<TResponse> response = process_core(request);
    // ...
    return response;
}
</code>```

Note that process_core must return nothing instead of void in this case, so you'll need some sort of specialization or compile-time branching anyway.

Body:
Let's say I have a template class like this:

template<typename TRequest, typename TResponse = void>
class handler
{
private:
    TResponse process_core(const TRequest& request);
public:
    TResponse process(const TRequest& request)
    {
        //log the request
        TResponse response = process_core(request);  //return process_core(request) works;
        //log the response, for void it's fine to log nothing
        return response;
    }
};

Somewhere else in the project process_core is implemented for different TRequest/TResponse types. For example:

template<> void handler<Foo>::process_core(const Foo& foo) { }
template<> Baz handler<Bar, Baz>::process_core(const Bar& bar) { }

Obviously return response breaks for void types. What's the correct way to do this? Or my design is not the C++ way? I'm new to C++.

Body:
Unfortunately void is not a regular type, even though there's a proposal that aims to fix that ("regular void" by Matt Calabrese), so you need to handle it in a special way. With C++17, you can simply use if constexpr(...) to branch at compile-time:

TResponse process(const TRequest& request)
{
    TResponse response = process_core(request);
    // ...

    if constexpr(!std::is_same_v<TResponse, void>)
    {
        return response;
    }
}

With C++11/14, you can use tag dispatching:

TResponse process(const TRequest& request)
{
    return processImpl(request, std::is_same<TResponse, void>{});
}

void process(const TRequest& request, std::true_type /* void */)
{
    TResponse response = process_core(request);
    // ...
}

TResponse process(const TRequest& request, std::false_type /* not void */)
{
    TResponse response = process_core(request);
    // ...
    return response;
}

Alternatively, you can transform void into a regular nothing type and handle it homogeneously.

struct nothing { };

template <typename T>
struct void_to_nothing { using type = T; };

template <>
struct void_to_nothing<void> { using type = nothing; };

template <typename T>
using void_to_nothing_t = typename void_to_nothing<T>::type;

auto process(const TRequest& request)
{
    void_to_nothing_t<TResponse> response = process_core(request);
    // ...
    return response;
}

Note that process_core must return nothing instead of void in this case, so you'll need some sort of specialization or compile-time branching anyway.


问:
Swift optional binding with check for several types
I have model for my class that may be instance of 2 different classes. Now i check that model is class i need with following:

```<code> guard let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as myClassOne? else {
                assertionFailure("Wrong model for RetailSalesVC")
                return
            }
</code>```

Now i want to check if model is class one OR model is class two. Is that possible to achieve?

Now i ended up with this (but without optional binding):

```<code>   guard (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassOne?) != nil)) ||
            (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassTwo?) != nil)) else {
                assertionFailure("Wrong model for \(self)")
                return
        }
</code>```

答:
Here's an example if you want to run it:

```<code>class ModelOne {}
class ModelTwo {}

let testObjects : [Any] = [ModelOne.init(), ModelTwo.init(), NSCoder.init()]
for obj in  testObjects {
    if  (obj is ModelOne || obj is ModelTwo) {
        print("\(obj) passes")
    }else{
        print("\(obj) fails")
    }
}
</code>```

should give the followig output:

```<code>main.ModelOne passes
main.ModelTwo passes
<NSCoder: 0x7f93a0c02b40> fails
</code>```

Body:
I have model for my class that may be instance of 2 different classes. Now i check that model is class i need with following:

 guard let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as myClassOne? else {
                assertionFailure("Wrong model for RetailSalesVC")
                return
            }

Now i want to check if model is class one OR model is class two. Is that possible to achieve?

Now i ended up with this (but without optional binding):

   guard (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassOne?) != nil)) ||
            (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassTwo?) != nil)) else {
                assertionFailure("Wrong model for \(self)")
                return
        }

Body:
Here's an example if you want to run it:

class ModelOne {}
class ModelTwo {}

let testObjects : [Any] = [ModelOne.init(), ModelTwo.init(), NSCoder.init()]
for obj in  testObjects {
    if  (obj is ModelOne || obj is ModelTwo) {
        print("\(obj) passes")
    }else{
        print("\(obj) fails")
    }
}

should give the followig output:

main.ModelOne passes
main.ModelTwo passes
<NSCoder: 0x7f93a0c02b40> fails


问:
Error when using dtruncnorm: Argument 's_x' is not a real vector
I am attempting to fit a truncated normal distribution to a dataset of 5000 claim sizes using maximum likelihood:

```<code>l1 = function(theta)
{
  -sum(dtruncnorm(x=size, a=0, b=Inf, mean = theta[1], sd=theta[2]))
}
mle1=optim(par=c(4,4), fn=l1)
</code>```

When I run the optim(par=c(4, 2), fn=l1) line however, I get the error:

```<code>Error in dtruncnorm(x = size, a = 0, b = Inf, mean = theta[1], sd = theta[2]) :
Argument 's_x' is not a real vector.
</code>```

I know it has something to do with the size variable but as far as I can tell it is a vector of integers since when I run typeof(size) I get "integer" as the output.

Any help is appreciated!

答:
For some reason the function does not accept sequences. This worked for me:</p>

```<code>-sum(sapply(size, function(v){
 dtruncnorm(x=as.numeric(v), a=0, b=Inf, mean = theta[1], sd=theta[2])
}))
</code>```

Body:
I am attempting to fit a truncated normal distribution to a dataset of 5000 claim sizes using maximum likelihood:

l1 = function(theta)
{
  -sum(dtruncnorm(x=size, a=0, b=Inf, mean = theta[1], sd=theta[2]))
}
mle1=optim(par=c(4,4), fn=l1)

When I run the optim(par=c(4, 2), fn=l1) line however, I get the error:

Error in dtruncnorm(x = size, a = 0, b = Inf, mean = theta[1], sd = theta[2]) :
Argument 's_x' is not a real vector.

I know it has something to do with the size variable but as far as I can tell it is a vector of integers since when I run typeof(size) I get "integer" as the output.

Any help is appreciated!

Body:
For some reason the function does not accept sequences. This worked for me:

-sum(sapply(size, function(v){
 dtruncnorm(x=as.numeric(v), a=0, b=Inf, mean = theta[1], sd=theta[2])
}))


问:
Checking for EOF using shell script
I have a project that involves extracting data from a database into a text file, and then ingesting it into Hadoop. So i want to create a shell script that NiFi can run to automatically to check if a text file is extracted and ingest it, but I need to make sure that the whole data has been extracted first before ingesting it. Meaning I would need to check that the text file has an EOF, how do I do that?

Don't have any code as of yet, I have very little knowledge writing shell scripts.

答:
EOF is not something that actually gets put in the text file - in fact, there isn't really any EOF value. EOF or end-of-file is a condition that occurs when you try to consume input from a source that has none to give.

There is no general marker you can look for in your text files that will tell you whether they are complete. You'll need to make your script indicate when a given chunk of data has been extracted in some other way. There are many possibilities; you could change the name of the file as choroba suggested, or you could create a lock file and remove it once the data extraction is done, or you could have your extraction program write a distinctive sequence of bytes to the file at the end, or so on.

Title: Checking for EOF using shell script