问:
Multi-entity Aggregates command handling
I have an aggregate root like this:

Aggregate root:

```<code>@NoArgsConstructor
@Aggregate(repository = "positionAggregateRepository")
@AggregateRoot
@XSlf4j
@Data
public class HopAggregate {

@AggregateIdentifier
private String hopId;
private FilteredPosition position;
private LocalDate positionDate;
@AggregateMember
private Security security;

@CommandHandler
public HopAggregate(NewHopCommand cmd) {
    log.info("creating new position , {}", cmd.getDateId());
    apply(new HopEvent(cmd.getHopId(), cmd.getDateId(), cmd.getFilteredPosition(), cmd.getSecurity(), false));
}

@CommandHandler
public void handle(UpdateHopCommand cmd) {
    log.info("creating hop update event {}", cmd);
    apply(new HopEvent(this.hopId, this.positionDate, cmd.getFilteredPosition(), this.security, true));
}

@CommandHandler
public void handle(SecurityUpdate cmd) {
    log.info("updating security {}", cmd);
    apply(new SecurityUpdateEvent(this.hopId, cmd.getFilteredSecurity()));
}

@EventSourcingHandler
public void on(HopEvent evt) {
    if (evt.getIsUpdate()) {
        log.info("updating position {}", evt);
        this.position = evt.getFilteredPosition();
    } else {
        log.info("adding new position to date {}", evt);
        this.hopId = evt.getHopId();
        this.positionDate = evt.getDate();
        this.position = evt.getFilteredPosition();
        this.security= evt.getSecurity();
    }
}

@EventSourcingHandler
public void on(SecurityUpdateEvent evt) {
    log.info("hop id {}, security update {}", this.hopId, evt.getFilteredSecurity().getSecurityId());
}
</code>```

}

Child entity:

```<code>@XSlf4j
@Data
@RequiredArgsConstructor
@NoArgsConstructor
public class IpaSecurity implements Serializable {

@EntityId
@NonNull
private String id;
@NonNull
private FilteredSecurity security;
}
</code>```

My issue is that when i am pushing and update like this:

```<code>@EventHandler
public void handleSecurityEvent(SecurityUpdate securityUpdate) {
log.info("got security event {}", securityUpdate);
commandGateway.send(securityUpdate);
}
</code>```

and my command being:

```<code>@Data
@RequiredArgsConstructor
@NoArgsConstructor
@ToString
public class SecurityUpdate {

@NonNull
@TargetAggregateIdentifier
private String id;
@NonNull
private FilteredSecurity filteredSecurity;
}
</code>```

I am getting aggregate root not found exception:

Command 'com.hb.apps.ipa.events.SecurityUpdate' resulted in org.axonframework.modelling.command.AggregateNotFoundException(The aggregate was not found in the event store)

I am not sure how to handle this scenario. My requirement is that each aggregate should check whether it contains the security and then update it if the command was issued. What am i missing? let me know if you need any more info on the code.

Thanks for your help.

答:
A Command is always targeted towards a single entity.
This entity can be an Aggregate, an entity contained in an Aggregate (what Axon Framework calls an Aggregate Member) or a simple singleton component.
Important to note though, is that there will only be one entity handling the command.

This is what requires you to set the @TargetAggregateIdentifier in your Command for Axon to be able to route it to a single Aggregate instance if the Command Handler in question is part of it.

The AggregateNotFoundException you're getting signals that the @TargetAggregateIdentifier annotated field in your SecurityUpdate command does no correspond to any existing Aggregate.
I'd thus suspect that the id field in the SecurityUpdate does not correspond to any @AggregateIdentifier annotated field in your HopAggregate aggregates.

A part from the above, I have a couple of other suggestions when looking at your snippets which I'd like to share with you:

@Aggregate is meta-annotated with @AggregateRoot. You're thus not required to specify both on an Aggregate class

For logging messages being handled, you can utilize LoggingInterceptor. You can configure this on any component capable of handling messages, thus providing a universal way of logging. This will omit the necessity to add log lines in your message handling functions

You're publishing a HopEvent on both the create and update commands. Doing so makes your HopEvent very generic. Ideally, your events clarify business operations occurring in your system. My rule of thumb typically is such: "If I tell my business manager/customer about the event class, he/she should know exactly what it does". I'd thus suggest to rename the event to something more specific

Just as with the HopEvent, the UpdateHopCommand is quite generic. Your commands should express the intent to perform an operation in your application. Users will typically not desire an update, they desire an address change for example. Your commands classes ideally reflect this

The suggested naming convention for commands is to start with verb in the present tense. Thus, it should no be SecurityUpdate, but UpdateSecurity. A command is a request expressing intent, the messages ideally reflect this

Hope this helps you out @juggernaut!

Body:
I have an aggregate root like this:

Aggregate root:

@NoArgsConstructor
@Aggregate(repository = "positionAggregateRepository")
@AggregateRoot
@XSlf4j
@Data
public class HopAggregate {

@AggregateIdentifier
private String hopId;
private FilteredPosition position;
private LocalDate positionDate;
@AggregateMember
private Security security;

@CommandHandler
public HopAggregate(NewHopCommand cmd) {
    log.info("creating new position , {}", cmd.getDateId());
    apply(new HopEvent(cmd.getHopId(), cmd.getDateId(), cmd.getFilteredPosition(), cmd.getSecurity(), false));
}

@CommandHandler
public void handle(UpdateHopCommand cmd) {
    log.info("creating hop update event {}", cmd);
    apply(new HopEvent(this.hopId, this.positionDate, cmd.getFilteredPosition(), this.security, true));
}

@CommandHandler
public void handle(SecurityUpdate cmd) {
    log.info("updating security {}", cmd);
    apply(new SecurityUpdateEvent(this.hopId, cmd.getFilteredSecurity()));
}

@EventSourcingHandler
public void on(HopEvent evt) {
    if (evt.getIsUpdate()) {
        log.info("updating position {}", evt);
        this.position = evt.getFilteredPosition();
    } else {
        log.info("adding new position to date {}", evt);
        this.hopId = evt.getHopId();
        this.positionDate = evt.getDate();
        this.position = evt.getFilteredPosition();
        this.security= evt.getSecurity();
    }
}

@EventSourcingHandler
public void on(SecurityUpdateEvent evt) {
    log.info("hop id {}, security update {}", this.hopId, evt.getFilteredSecurity().getSecurityId());
}

}

Child entity:

@XSlf4j
@Data
@RequiredArgsConstructor
@NoArgsConstructor
public class IpaSecurity implements Serializable {

@EntityId
@NonNull
private String id;
@NonNull
private FilteredSecurity security;
}

My issue is that when i am pushing and update like this:

@EventHandler
public void handleSecurityEvent(SecurityUpdate securityUpdate) {
log.info("got security event {}", securityUpdate);
commandGateway.send(securityUpdate);
}

and my command being:

@Data
@RequiredArgsConstructor
@NoArgsConstructor
@ToString
public class SecurityUpdate {

@NonNull
@TargetAggregateIdentifier
private String id;
@NonNull
private FilteredSecurity filteredSecurity;
}

I am getting aggregate root not found exception:

Command 'com.hb.apps.ipa.events.SecurityUpdate' resulted in org.axonframework.modelling.command.AggregateNotFoundException(The aggregate was not found in the event store)

I am not sure how to handle this scenario. My requirement is that each aggregate should check whether it contains the security and then update it if the command was issued. What am i missing? let me know if you need any more info on the code.

Thanks for your help.


来源: stackexchange

问:
Any Way to "Safely" Call assembly.GetTypes()?
I've searched high and low, but I can't come up with a solution for this.

I need to get all the interface types from an assembly with code like this:

```<code>IEnumerable<Type> interfaces = _assembly.GetTypes().Where(x => x.IsInterface);
</code>```

The problem is, for certain assemblies I run into the following error:

Unable to load one or more of the
  requested types. Retrieve the
  LoaderExceptions property for more
  information.

I'm completely clear on why this happens (dependant assemblies are not loaded), and how it can be worked around if I want to troubleshoot a specific assembly.  In my case, I don't know the assembly up front (the user will select it).

What I'd like to know is whether there is any way to allow the code to continue past any types that can't be retrieved, and still pull the ones that don't fail.

答:
Handle the exception in another method that takes the place of the lambda expression and catches the exception. You could also have the exceptions accumulate in some global object for inspection later.</p>

```<code>IEnumerable<Type> interfaces = _assembly.GetTypes().Where(IsInterface);

List<string> Messages = new List<string>();

private bool IsInterface(Type x)
{
    try { return x.IsInterface; }
    catch (Exception e)
    {
        Messages.Add(e.Message);
    }
    return false;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've searched high and low, but I can't come up with a solution for this.

I need to get all the interface types from an assembly with code like this:

IEnumerable<Type> interfaces = _assembly.GetTypes().Where(x => x.IsInterface);

The problem is, for certain assemblies I run into the following error:

Unable to load one or more of the
  requested types. Retrieve the
  LoaderExceptions property for more
  information.

I'm completely clear on why this happens (dependant assemblies are not loaded), and how it can be worked around if I want to troubleshoot a specific assembly.  In my case, I don't know the assembly up front (the user will select it).

What I'd like to know is whether there is any way to allow the code to continue past any types that can't be retrieved, and still pull the ones that don't fail.

Body:
Handle the exception in another method that takes the place of the lambda expression and catches the exception. You could also have the exceptions accumulate in some global object for inspection later.

IEnumerable<Type> interfaces = _assembly.GetTypes().Where(IsInterface);

List<string> Messages = new List<string>();

private bool IsInterface(Type x)
{
    try { return x.IsInterface; }
    catch (Exception e)
    {
        Messages.Add(e.Message);
    }
    return false;
}


问:
onRetrofitFailure() Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
I am given a Json data where an image and some other data is stored. I am trying to fetch that image in an imageview using Retrofit. I created a DTO of the required things as detailed in the code. I am getting and error, on retrofit failure. How can I solve this?

Created Retrofit Instance

Created DTO of JSON data and properties

API service created also
https://s3.ap-south-1.amazonaws.com/zestlife/promotional_banner.json
Link where JSON data is stored.

```<code>@Parcelize
@JsonIgnoreProperties(ignoreUnknown = true)
open class MerchantPromotionDTO(

    @JsonProperty("image") var image: ImageUrlsDTO? = null,
    @JsonProperty("cta") var cta: CTADTO? = null,
    @JsonProperty("probability") var probability: Int? = 0,
    @JsonProperty("isDismissible") var isDismissible: Boolean? = true,
    @JsonProperty("showImmediate") var showImmediate: Boolean? = false
    ) : BaseResponseDTO()

@Parcelize
    @JsonIgnoreProperties(ignoreUnknown = true)
    class MerchantpromotionBDTO(
    @JsonProperty("promotions") var promotions: ArrayList<MerchantPromotionDTO>?=null
) : BaseResponseDTO()

@GET("https://demo6861386.mockable.io/banner/test")
fun getPromotionalBanner(): Call<ArrayList<MerchantpromotionBDTO>>

fun getPromotionalDetails(): LiveData<ResponseDTO<ArrayList<MerchantpromotionBDTO>>>{
    val pBannerDetails=MutableLiveData<ResponseDTO<ArrayList<MerchantpromotionBDTO>>>()
    ApiComponent.enqueue({
        getPromotionalBanner(

        )
    },object :OnRequestComplete<ArrayList<MerchantpromotionBDTO>>{
        override fun onComplete(responseDTO: ResponseDTO<ArrayList<MerchantpromotionBDTO>>) {
            pBannerDetails.value=responseDTO
        }
    }
)
</code>```

EDIT:

```<code>override fun onStart() {
    super.onStart()

    populateData()
}

@Synchronized
private fun populateData() {
    MerchantpromotionBDTO?.let {
        val promImageUrl = it.image?.getImageUrl(CommonUtils.getDisplayDensityLevel(context))
        picasso.load(if (promImageUrl.isNullOrEmpty()) null else promImageUrl)
                .placeholder(R.drawable.ic_placeholder_minimal)
                .into(ivMerchantPromotionBanner)
    }
}
</code>```

I want the response into my logcat and to fetch an image in Imageview

答:
The issue is that the JSON you're getting from the backend is:

```<code>{
    "promotions": [
        ...
    ]
}
</code>```

Thas is a JSON object, not an array, but you defined getPromotionalBanner method as returning a List<MerchantpromotionBDTO>, so the JSON library cannot perform deserialisation as it expects an array (i.e. something starting with [) but it finds a START_OBJECT token (i.e., {).

You can solve the issue by changing the signature of that method to:

```<code>@GET("https://demo6861386.mockable.io/banner/test")
fun getPromotionalBanner(): Call<MerchantpromotionBDTO>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am given a Json data where an image and some other data is stored. I am trying to fetch that image in an imageview using Retrofit. I created a DTO of the required things as detailed in the code. I am getting and error, on retrofit failure. How can I solve this?

Created Retrofit Instance

Created DTO of JSON data and properties

API service created also
https://s3.ap-south-1.amazonaws.com/zestlife/promotional_banner.json
Link where JSON data is stored.

@Parcelize
@JsonIgnoreProperties(ignoreUnknown = true)
open class MerchantPromotionDTO(

    @JsonProperty("image") var image: ImageUrlsDTO? = null,
    @JsonProperty("cta") var cta: CTADTO? = null,
    @JsonProperty("probability") var probability: Int? = 0,
    @JsonProperty("isDismissible") var isDismissible: Boolean? = true,
    @JsonProperty("showImmediate") var showImmediate: Boolean? = false
    ) : BaseResponseDTO()

@Parcelize
    @JsonIgnoreProperties(ignoreUnknown = true)
    class MerchantpromotionBDTO(
    @JsonProperty("promotions") var promotions: ArrayList<MerchantPromotionDTO>?=null
) : BaseResponseDTO()

@GET("https://demo6861386.mockable.io/banner/test")
fun getPromotionalBanner(): Call<ArrayList<MerchantpromotionBDTO>>

fun getPromotionalDetails(): LiveData<ResponseDTO<ArrayList<MerchantpromotionBDTO>>>{
    val pBannerDetails=MutableLiveData<ResponseDTO<ArrayList<MerchantpromotionBDTO>>>()
    ApiComponent.enqueue({
        getPromotionalBanner(

        )
    },object :OnRequestComplete<ArrayList<MerchantpromotionBDTO>>{
        override fun onComplete(responseDTO: ResponseDTO<ArrayList<MerchantpromotionBDTO>>) {
            pBannerDetails.value=responseDTO
        }
    }
)

EDIT:

override fun onStart() {
    super.onStart()

    populateData()
}

@Synchronized
private fun populateData() {
    MerchantpromotionBDTO?.let {
        val promImageUrl = it.image?.getImageUrl(CommonUtils.getDisplayDensityLevel(context))
        picasso.load(if (promImageUrl.isNullOrEmpty()) null else promImageUrl)
                .placeholder(R.drawable.ic_placeholder_minimal)
                .into(ivMerchantPromotionBanner)
    }
}

I want the response into my logcat and to fetch an image in Imageview

Body:
The issue is that the JSON you're getting from the backend is:

{
    "promotions": [
        ...
    ]
}

Thas is a JSON object, not an array, but you defined getPromotionalBanner method as returning a List<MerchantpromotionBDTO>, so the JSON library cannot perform deserialisation as it expects an array (i.e. something starting with [) but it finds a START_OBJECT token (i.e., {).

You can solve the issue by changing the signature of that method to:

@GET("https://demo6861386.mockable.io/banner/test")
fun getPromotionalBanner(): Call<MerchantpromotionBDTO>


问:
Computing an HMAC-SHA signature
I'm writing a module for Amazon's SimpleDB. They require REST requests to be signed using HMAC-SHA algorithm. (Details here.)

I'm told that there is a function to computer this signature, but I can't find it in the documentation. What is the function called, and what do its arguments look like?

答:
EDITED: The following should work:

```<code>pre {
  message = "Four score and seven years ago";
  key = "Abe Lincoln";
  signature = math:hmac_sha256_base64(message, key);
}
notify("Signature is", signature);
</code>```

The function is math:hmac_sha256_base64(<datastring>,<keystring>)

Title: Computing an HMAC-SHA signature

Body:
EDITED: The following should work:

pre {
  message = "Four score and seven years ago";
  key = "Abe Lincoln";
  signature = math:hmac_sha256_base64(message, key);
}
notify("Signature is", signature);

The function is math:hmac_sha256_base64(<datastring>,<keystring>)


问:
How to avoid Matlab to convert doubles to integers while putting those doubles to a vector?
Hi I am trying to put double values into a vector but when I display this vector, I see that double values I put inside are converted to integers. How can I avoid this?

I checked the values of teta and they are as expected (ie. 1.802, 1.688), but in the matrix x, the values are all 1's.

```<code>SerialPort = 'COM23';
s = serial(SerialPort, 'BaudRate', 115200);
fopen(s);

n = 1;

while n<200
    dis = fscanf(s,'d',2);
    ang = fscanf(s,'d',3);
    intDis = str2double(dis);
    intAng = str2double(ang);
    teta = pi/6 +(intAng-100)*pi/300;
    x(n) = teta
    y(n) = intDis;

    n = n+1;
end

%polar(x,y)
fclose(s);
delete(s);
clear s;
</code>```

答:
The only way this can happen is if x was declared as an integer (or maybe logical?) before the script started. You should always initialize all variables, always, to avoid unexpected errors: add x=[]; to your script before the loop.

But your loop runs exactly 200 iterations, so you know the size x will have at the end. You can preallocate:

```<code>x = zeros(200,1);
</code>```

I also recommend that you look into the syntax of the for loop, as that would be simpler in this case than while.

Body:
Hi I am trying to put double values into a vector but when I display this vector, I see that double values I put inside are converted to integers. How can I avoid this?

I checked the values of teta and they are as expected (ie. 1.802, 1.688), but in the matrix x, the values are all 1's.

SerialPort = 'COM23';
s = serial(SerialPort, 'BaudRate', 115200);
fopen(s);

n = 1;

while n<200
    dis = fscanf(s,'d',2);
    ang = fscanf(s,'d',3);
    intDis = str2double(dis);
    intAng = str2double(ang);
    teta = pi/6 +(intAng-100)*pi/300;
    x(n) = teta
    y(n) = intDis;

    n = n+1;
end

%polar(x,y)
fclose(s);
delete(s);
clear s;

Body:
The only way this can happen is if x was declared as an integer (or maybe logical?) before the script started. You should always initialize all variables, always, to avoid unexpected errors: add x=[]; to your script before the loop.

But your loop runs exactly 200 iterations, so you know the size x will have at the end. You can preallocate:

x = zeros(200,1);

I also recommend that you look into the syntax of the for loop, as that would be simpler in this case than while.


问:
CSS - Define Print Canvas
If I wanted to create a text editor and wanted to control / display exactly what part of you document will be printed where on a DIN-A4 page, how would that be possible in CSS / JS? How can I know where the page would end and how could I display that in the browser?

If the grey boxes were my text content, how could I know / show / control where the lines would break (width) and where the page would break (height)?

答:
Your best bet is to use CSS Grid to build up your layout/template.

A good tutorial to walk you through: https://css-tricks.com/snippets/css/complete-guide-grid/

Title: CSS - Define Print Canvas


问:
AttributeError: 'list' object has no attribute 'h3' ( Beautifulsoup )
I am a beginner in Web-scraping and I am following this tutorial ( https://www.dataquest.io/blog/web-scraping-beautifulsoup/ ) to extract movie data, I think that I have badly defined " first_movie " !

this is the code

```<code>  from requests import get
  from bs4 import BeautifulSoup

  first_movie =[]

  url = 'http://www.imdb.com/search/title?
  release_date=2017&sort=num_votes,desc&page=1'
  response = get(url)
  html_soup = BeautifulSoup(response.text, 'html.parser')
  type(html_soup)

  movie_containers = html_soup.find_all('div', class_ = 'lister-item mode-advanced')

  first_name = first_movie.h3.a.text
</code>```

I get this error :

```<code>Traceback (most recent call last):
File "mov1.py", line 13, in <module>
first_name = first_movie.h3.a.text
AttributeError: 'list' object has no attribute 'h3'
</code>```

答:
first_movie is not assigned, replace movie_containers with it. use find() to select first element

```<code>first_movie = html_soup.find('div', class_ = 'lister-item mode-advanced')
first_name = first_movie.h3.a.text
</code>```

or use find_all() with index

```<code>first_movie = html_soup.find_all('div', class_ = 'lister-item mode-advanced')[0]
first_name = first_movie.h3.a.text
</code>```

Body:
I am a beginner in Web-scraping and I am following this tutorial ( https://www.dataquest.io/blog/web-scraping-beautifulsoup/ ) to extract movie data, I think that I have badly defined " first_movie " !

this is the code

  from requests import get
  from bs4 import BeautifulSoup

  first_movie =[]

  url = 'http://www.imdb.com/search/title?
  release_date=2017&sort=num_votes,desc&page=1'
  response = get(url)
  html_soup = BeautifulSoup(response.text, 'html.parser')
  type(html_soup)

  movie_containers = html_soup.find_all('div', class_ = 'lister-item mode-advanced')

  first_name = first_movie.h3.a.text

I get this error :

Traceback (most recent call last):
File "mov1.py", line 13, in <module>
first_name = first_movie.h3.a.text
AttributeError: 'list' object has no attribute 'h3'

Body:
first_movie is not assigned, replace movie_containers with it. use find() to select first element

first_movie = html_soup.find('div', class_ = 'lister-item mode-advanced')
first_name = first_movie.h3.a.text

or use find_all() with index

first_movie = html_soup.find_all('div', class_ = 'lister-item mode-advanced')[0]
first_name = first_movie.h3.a.text


问:
String that ends wih a single underscore character
I am trying to find the correct regular expression that detects string that end with a single underscore, e.g. hello_, this_. So far I have re.match("[aA-zZ](_)", string) but detects strings like, day__, ball__, i.e, with two underscores which i do not want. Any ideas how to get string with a single underscore in the end.

Thanks

答:
I know you asked for a regex, but this could be done also by simply:</p>

```<code>s = "hello__"

s.endswith("_") and not s[:-1].endswith("_")
# False
</code>```

Body:
I know you asked for a regex, but this could be done also by simply:

s = "hello__"

s.endswith("_") and not s[:-1].endswith("_")
# False


问:
Flutter set Container background with Text child
in flutter i want to have simple Text inside Container with background color on container, for example:

unfortunately i can't set or make this screen shot with flutter widgets

```<code>Expanded(
  child: Container(
    margin: EdgeInsets.only(top: 10.0),
    child: ListView(
      children: <Widget>[
        Container(
          padding: EdgeInsets.only(right: 1.0, left: 1.0),
          child: Center(
            child: bottomSheetDashBoardItems(
                widget.dashboardItems),
          ),
        ), //container
      ], //list view children
    ), //list view
  ), //container
), //Expanded

Widget bottomSheetDashBoardItems(List<DashboardItems> dashboardItems) {
  return Wrap(
    children: dashboardItems
        .map((item) => Container(
              width: 75.0,
              height: 75.0,
              margin: EdgeInsets.all(5.0),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(5.0)),
                  boxShadow: [
                    BoxShadow(
                      blurRadius: 0.5,
                      color: Colors.black,
                      offset: Offset(0.0, 0.0),
                    )
                  ]),
              child: Center(
                  child: Stack(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(bottom: 12.0),
                    child: Align(
                      alignment: Alignment.center,
                      child: Image.asset(
                        item.icon,
                        width: 40.0,
                        height: 40.0,
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.indigo[400],
                        borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(5.0),
                          bottomRight: Radius.circular(5.0),
                        ),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.only(top: 3.0),
                        child: Text(
                          item.title,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'IranSansLight',
                              fontSize: 9.0),
                        ),
                      ),
                    ),
                  ),
                ],
              )),
            ))
        .toList());
</code>```

}

result:

答:
#1

Do not initiate widget tree through functions. Create a class under StatelessWidget instead. For more info check out this answer.

#2

As for the red bar not auto expanding in width - since you already use Stack, I can suggest a simple solution.

Replace Align (2nd child of Stack) with Positioned like this:

Positioned(
  left: 0,
  right: 0,
  bottom: 0,
  height: 19,
  child: // ...
)
```

And remove width property of the Container.

Let me know if this helped.

Body:
in flutter i want to have simple Text inside Container with background color on container, for example:

unfortunately i can't set or make this screen shot with flutter widgets

Expanded(
  child: Container(
    margin: EdgeInsets.only(top: 10.0),
    child: ListView(
      children: <Widget>[
        Container(
          padding: EdgeInsets.only(right: 1.0, left: 1.0),
          child: Center(
            child: bottomSheetDashBoardItems(
                widget.dashboardItems),
          ),
        ), //container
      ], //list view children
    ), //list view
  ), //container
), //Expanded

Widget bottomSheetDashBoardItems(List<DashboardItems> dashboardItems) {
  return Wrap(
    children: dashboardItems
        .map((item) => Container(
              width: 75.0,
              height: 75.0,
              margin: EdgeInsets.all(5.0),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(5.0)),
                  boxShadow: [
                    BoxShadow(
                      blurRadius: 0.5,
                      color: Colors.black,
                      offset: Offset(0.0, 0.0),
                    )
                  ]),
              child: Center(
                  child: Stack(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(bottom: 12.0),
                    child: Align(
                      alignment: Alignment.center,
                      child: Image.asset(
                        item.icon,
                        width: 40.0,
                        height: 40.0,
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.indigo[400],
                        borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(5.0),
                          bottomRight: Radius.circular(5.0),
                        ),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.only(top: 3.0),
                        child: Text(
                          item.title,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'IranSansLight',
                              fontSize: 9.0),
                        ),
                      ),
                    ),
                  ),
                ],
              )),
            ))
        .toList());

}

result:

Body:
#1

Do not initiate widget tree through functions. Create a class under StatelessWidget instead. For more info check out this answer.

#2

As for the red bar not auto expanding in width - since you already use Stack, I can suggest a simple solution.

Replace Align (2nd child of Stack) with Positioned like this:

Positioned(
  left: 0,
  right: 0,
  bottom: 0,
  height: 19,
  child: // ...
)

And remove width property of the Container.

Let me know if this helped.


答:
You can use extended iterable unpacking to get all parts of the remark in a single variable (a list)

```<code>import json

keys = ['date1', 'date2', 'remark', 'credit', 'balance']
foo = '07/08/2018 07/08/2018 IMPS DR-1763308000000116-PYTM0123456-917 592674 5,000.00 39,325.93'
date1, date2, *remarks, credit, balance = foo.split()
remarks = ' '.join(remarks)

#data as dict
data = dict(zip(keys, [date1, date2, remarks, credit, balance]))
print(data)

# if you need json string
my_json = json.dumps(data, indent=4)
print(my_json)
</code>```

as a side note - don't use string as variable name - it's a module from python standard library.

Title: python string convert into json for the bankstatement

Body:
This my input

string = '07/08/2018 07/08/2018 IMPS DR-1763308000000116-PYTM0123456-917 592674 5,000.00 39,325.93'

I need output like

{'date1':'07/08/2018','date2':'07/08/2018','remark':'IMPS DR-1763308000000116-PYTM0123456-917 592674','credit':'5,000.00','balance' : '39,325.93' }

I tried

result = { 'date1': list1[0], 'date2': list1[1], 'balance': list1[-1]}
print(result)

output

{'date1': '07/08/2018', 'date2': '07/08/2018', 'balance': '39,325.93'}

Body:
You can use extended iterable unpacking to get all parts of the remark in a single variable (a list)

import json

keys = ['date1', 'date2', 'remark', 'credit', 'balance']
foo = '07/08/2018 07/08/2018 IMPS DR-1763308000000116-PYTM0123456-917 592674 5,000.00 39,325.93'
date1, date2, *remarks, credit, balance = foo.split()
remarks = ' '.join(remarks)

#data as dict
data = dict(zip(keys, [date1, date2, remarks, credit, balance]))
print(data)

# if you need json string
my_json = json.dumps(data, indent=4)
print(my_json)

as a side note - don't use string as variable name - it's a module from python standard library.


问:
Selenium Python - Wait for Element to load and click on it
I've been trying to figure out how to wait for an element to be loaded and then execute the click function in python.

The website I am talking about is: https://tempail.com/

As soon as I received an e-mail, I want the script to click on it and then execute further tasks.

I tried to solve this problem through the "Try/Except Function", but I always receive error messages.

Source of the site:
https://i.imgur.com/xMrJg5J.png

The problem is that the site uses generated IDs I can't use in the find_element_by function.

This is what I've tried so far:
https://i.imgur.com/zxGMVpf.png

With try, I wanted the script to wait until the site received the mail. As soon as the mail is in the inbox, it should click the link/the mail and open it.

Apart from that, I looked up for more solutions, but nothing really helped out, but with this code I always receive the following error:

```<code>Message: no such element: Unable to locate element: {"method":"css selector","selector":".epostalar ul li.mail a"}
</code>```

Plus it doesn't even wait for the mail.

答:
As soon as you receive an e-mail, to invoke click() on it you have to induce WebDriverWait for the element to be clickable and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul.mailler li.mail a"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='mailler']//li[contains(@class, 'mail')]//a"))).click()
</code>```

Body:
I've been trying to figure out how to wait for an element to be loaded and then execute the click function in python.

The website I am talking about is: https://tempail.com/

As soon as I received an e-mail, I want the script to click on it and then execute further tasks.

I tried to solve this problem through the "Try/Except Function", but I always receive error messages.

Source of the site:
https://i.imgur.com/xMrJg5J.png

The problem is that the site uses generated IDs I can't use in the find_element_by function.

This is what I've tried so far:
https://i.imgur.com/zxGMVpf.png

With try, I wanted the script to wait until the site received the mail. As soon as the mail is in the inbox, it should click the link/the mail and open it.

Apart from that, I looked up for more solutions, but nothing really helped out, but with this code I always receive the following error:

Message: no such element: Unable to locate element: {"method":"css selector","selector":".epostalar ul li.mail a"}

Plus it doesn't even wait for the mail.

Body:
As soon as you receive an e-mail, to invoke click() on it you have to induce WebDriverWait for the element to be clickable and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul.mailler li.mail a"))).click()

Using XPATH:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='mailler']//li[contains(@class, 'mail')]//a"))).click()


问:
Error 1004 application defined or object defined error
Here the code:

```<code>Sub deleterow2()
Dim a As Integer
Dim n As Integer
Dim c As Integer

LastRow = Range("F" & Rows.Count).End(xlUp).Row
For n = 0 To LastRow
a = 1
c = 0
Do Until c = 1
Cells(n + a, 6).Select
If Selection.value = Cells(n, 6) And Selection.value > 30 Then
Selection.EntireRow.Delete
Else
c = 1
End If
a = a + 1
Loop
Next n
End Sub
</code>```

What s wrong with that?

答:
enter image description here

Sub deleterow2()

Dim lastRow As Long, R As Long
Dim ws As Worksheet: Set ws = ActiveWorkbook.ActiveSheet

```<code>lastRow = ws.Range("F" & ws.Rows.Count).End(xlUp).Row
For R = lastRow To 2 Step -1
    With ws
        If .Cells(R, 6).value = .Cells(R - 1, 6) And .Cells(R, 19).value > 30 Then
            .Cells(R, 6).EntireRow.Delete
        End If
    End With
Next R
</code>```

End Sub

Body:
Here the code:

Sub deleterow2()
Dim a As Integer
Dim n As Integer
Dim c As Integer

LastRow = Range("F" & Rows.Count).End(xlUp).Row
For n = 0 To LastRow
a = 1
c = 0
Do Until c = 1
Cells(n + a, 6).Select
If Selection.value = Cells(n, 6) And Selection.value > 30 Then
Selection.EntireRow.Delete
Else
c = 1
End If
a = a + 1
Loop
Next n
End Sub

What s wrong with that?

Body:
enter image description here

Sub deleterow2()

Dim lastRow As Long, R As Long
Dim ws As Worksheet: Set ws = ActiveWorkbook.ActiveSheet

lastRow = ws.Range("F" & ws.Rows.Count).End(xlUp).Row
For R = lastRow To 2 Step -1
    With ws
        If .Cells(R, 6).value = .Cells(R - 1, 6) And .Cells(R, 19).value > 30 Then
            .Cells(R, 6).EntireRow.Delete
        End If
    End With
Next R

End Sub


问:
Maven can't find any test
I copy pom.xml with a similar project were all ok. Add need dependencies. Also, I add Jupiter with scope "compile" otherwise project doesn't compile. I try to find a solution in similar problems but nothing found.

Env: ubuntu 18, idea 2018.3, openjdk8, maven last version.

I try to change more new or old version junit, surefire plugin and junit-platform-surefire-provider but don't find need combination.

```<code><properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <junit.api.version>5.4.0</junit.api.version>
    <junit.jupiter.version>5.4.0</junit.jupiter.version>
    <junit.platform.version>1.3.1</junit.platform.version>
    <aspectj.version>1.9.4</aspectj.version>
    <allure.version>2.12.1</allure.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.jupiter.version}</version>
    </dependency>
    <dependency>
        <groupId>io.qameta.allure</groupId>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-junit5</artifactId>
        <version>${allure.version}</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.4.0</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>
                <testFailureIgnore>false</testFailureIgnore>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                </argLine>
                <systemProperties>
                    <property>
                        <name>junit.jupiter.extensions.autodetection.enabled</name>
                        <value>true</value>
                    </property>
                </systemProperties>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.3.2</version>
                </dependency>
                <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
        </plugin>
        <plugin>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-maven</artifactId>
            <version>LATEST_VERSION</version>
            <configuration>
                <reportVersion>2.4.1</reportVersion>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

答:
By default the maven Surefire Plugin expects your tests filenames to match the following conditions:

**/Test*.java - includes all of its subdirectories and all Java
filenames that start with "Test".

**/*Test.java - includes all of
its subdirectories and all Java filenames that end with "Test".

**/*Tests.java - includes all of its subdirectories and all Java
filenames that end with "Tests".

**/*TestCase.java - includes all
of its subdirectories and all Java filenames that end with
"TestCase".

If you test file names don't match the above criteria you have two options.  First of all modify your test filenames so that they do match the above criteria.  Secondly you can modify the inclusion criteria by configuring the maven-surefire-plugin

```<code><project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M3</version>
        <configuration>
          <includes>
            <include>%regex[.*(Cat|Dog).*Test.*]</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>
</code>```

For more information have a look at the maven-surefire-plugin documentation.

Title: Maven can't find any test

Body:
I copy pom.xml with a similar project were all ok. Add need dependencies. Also, I add Jupiter with scope "compile" otherwise project doesn't compile. I try to find a solution in similar problems but nothing found.

Env: ubuntu 18, idea 2018.3, openjdk8, maven last version.

I try to change more new or old version junit, surefire plugin and junit-platform-surefire-provider but don't find need combination.

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <junit.api.version>5.4.0</junit.api.version>
    <junit.jupiter.version>5.4.0</junit.jupiter.version>
    <junit.platform.version>1.3.1</junit.platform.version>
    <aspectj.version>1.9.4</aspectj.version>
    <allure.version>2.12.1</allure.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.jupiter.version}</version>
    </dependency>
    <dependency>
        <groupId>io.qameta.allure</groupId>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-junit5</artifactId>
        <version>${allure.version}</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.4.0</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>
                <testFailureIgnore>false</testFailureIgnore>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                </argLine>
                <systemProperties>
                    <property>
                        <name>junit.jupiter.extensions.autodetection.enabled</name>
                        <value>true</value>
                    </property>
                </systemProperties>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.3.2</version>
                </dependency>
                <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
        </plugin>
        <plugin>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-maven</artifactId>
            <version>LATEST_VERSION</version>
            <configuration>
                <reportVersion>2.4.1</reportVersion>
            </configuration>
        </plugin>
    </plugins>
</build>

Body:
By default the maven Surefire Plugin expects your tests filenames to match the following conditions:

**/Test*.java - includes all of its subdirectories and all Java
filenames that start with "Test".

**/*Test.java - includes all of
its subdirectories and all Java filenames that end with "Test".

**/*Tests.java - includes all of its subdirectories and all Java
filenames that end with "Tests".

**/*TestCase.java - includes all
of its subdirectories and all Java filenames that end with
"TestCase".

If you test file names don't match the above criteria you have two options.  First of all modify your test filenames so that they do match the above criteria.  Secondly you can modify the inclusion criteria by configuring the maven-surefire-plugin

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M3</version>
        <configuration>
          <includes>
            <include>%regex[.*(Cat|Dog).*Test.*]</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

For more information have a look at the maven-surefire-plugin documentation.


问:
Library initialization -- pthread_once in Win32 implementation
Hello. I am trying to make a fully thread-safe initialization function for my library and I couldn't easily find an alternative to pthread_once, which should solve the problem very easily. I've come to this code:

```<code>
void libInit (void)
{
#ifdef WIN32
    static volatile int initialized = 0;
    static HANDLE mtx;

    if (!initialized)
    {
        if (!mtx)
        {
            HANDLE mymtx;
            mymtx = CreateMutex(NULL, 0, NULL);
            if (InterlockedCompareExchangePointer(&mtx, mymtx, NULL) != NULL)
                CloseHandle(mymtx);
        }

        WaitForSingleObject(mtx);
        if (!initialized)
        {
            libInitInternal();
            initialized = 1;
        }
        ReleaseMutex(mtx);
    }
#else
    static pthread_once_t initialized = PTHREAD_ONCE_INIT;

    pthread_once(&initialized, libInitInternal);
#endif
}
</code>```

The libInitInternal() call leads to a thread-unsafe function, that initializes the library.

I would like to hear any suggestions on what I could be doing wrong or whether you know about a better solution.

答:
When using GCC or clang, you can use constructor and destructor attributes.  These work for both shared and static libraries, and execute code before and after main is run, respectively.  Additionally, you can specify multiple constructor and destructor functions.  Much cleaner than the singleton approach, and doesn't require you to remember to call libInit() from your main().</p>

```<code>static void __attribute__((constructor))
your_lib_init(void)
{
    fprintf(stderr, "library init\n");
}

static void __attribute__((destructor))
vensim_ctx_destroy(void)
{
    fprintf(stderr, "library destroy\n");
}
</code>```

OwnerDisplayName: Přemysl Janouch

ContentLicense: CC BY-SA 2.5

Body:
Hello. I am trying to make a fully thread-safe initialization function for my library and I couldn't easily find an alternative to pthread_once, which should solve the problem very easily. I've come to this code:

void libInit (void)
{
#ifdef WIN32
    static volatile int initialized = 0;
    static HANDLE mtx;

    if (!initialized)
    {
        if (!mtx)
        {
            HANDLE mymtx;
            mymtx = CreateMutex(NULL, 0, NULL);
            if (InterlockedCompareExchangePointer(&mtx, mymtx, NULL) != NULL)
                CloseHandle(mymtx);
        }

        WaitForSingleObject(mtx);
        if (!initialized)
        {
            libInitInternal();
            initialized = 1;
        }
        ReleaseMutex(mtx);
    }
#else
    static pthread_once_t initialized = PTHREAD_ONCE_INIT;

    pthread_once(&initialized, libInitInternal);
#endif
}

The libInitInternal() call leads to a thread-unsafe function, that initializes the library.

I would like to hear any suggestions on what I could be doing wrong or whether you know about a better solution.

Body:
When using GCC or clang, you can use constructor and destructor attributes.  These work for both shared and static libraries, and execute code before and after main is run, respectively.  Additionally, you can specify multiple constructor and destructor functions.  Much cleaner than the singleton approach, and doesn't require you to remember to call libInit() from your main().

static void __attribute__((constructor))
your_lib_init(void)
{
    fprintf(stderr, "library init\n");
}

static void __attribute__((destructor))
vensim_ctx_destroy(void)
{
    fprintf(stderr, "library destroy\n");
}


问:
Automatically obtaining market data from MetaTrader 5 using MatLab
I'm looking for a way to automatically run a script on MatLab which outputs price data from MetaTrader 5. Can anybody provide me a link to someone who has done this before or the best way to go about doing it?

I've researched online and could not find any useful article to deal with this matter.

答:
I've been downloading live Metatrader data, charting it with Matplotlib and developing indicators in Python. There is a user group with links to the code you need to acces the metatrader feed

There's a thread on it here: https://www.mql5.com/en/forum/306742


问:
Converting Excel, PowerPoint, PDF, and Word to Images in .NET using Aspose
so I am looking for a way to convert  Excel, PowerPoint, PDF, and Word to Images. I was wondering if anyone has experience with the Aspose suite and knows if all of this can be done with the Aspose.PDF suite, or would I need to get Aspose.slides, and Aspose.word as well?</p>

答:
I know it's 2019, but if anyone is still wondering, you can do this using Aspose.Words.

The following values (and more) in the SaveFormat enum are available:

```<code>    Tiff = 100,
    //
    // Summary:
    //     Renders a page of the document and saves it as a PNG file.
    Png = 101,
    //
    // Summary:
    //     Renders a page of the document and saves it as a BMP file.
    Bmp = 102,
    //
    // Summary:
    //     Renders a page of the document and saves it as a JPEG file.
    Jpeg = 104,
    //
    // Summary:
    //     Renders a page of the document and saves it as a GIF file.
    Gif = 105
</code>```

You would use them like so:

```<code>    var fileContents = asposeDocument.GenerateDocument(Aspose.Words.SaveFormat.Png);
</code>```

Body:
I know it's 2019, but if anyone is still wondering, you can do this using Aspose.Words.

The following values (and more) in the SaveFormat enum are available:

    Tiff = 100,
    //
    // Summary:
    //     Renders a page of the document and saves it as a PNG file.
    Png = 101,
    //
    // Summary:
    //     Renders a page of the document and saves it as a BMP file.
    Bmp = 102,
    //
    // Summary:
    //     Renders a page of the document and saves it as a JPEG file.
    Jpeg = 104,
    //
    // Summary:
    //     Renders a page of the document and saves it as a GIF file.
    Gif = 105

You would use them like so:

    var fileContents = asposeDocument.GenerateDocument(Aspose.Words.SaveFormat.Png);


问:
ld: entry point (_main) undefined. for architecture x86_64 : Xcode 9
Recently I downloaded Xcode 9 and created one sample iPhone app but the app is not able to build as it shows the following error:

ld: entry point (_main) undefined. for architecture x86_64

I searched on net about same and tried few ways like deleting derived data, restarting Xcode but still not fix the problem.

Anybody has faced similar issue?

答:
Add @UIApplicationMain to fix the issue. As well as what it does internally you can do the same by your own. In that case, you don't need to add @UIApplicationMain. Simply create one swift file name it main and put the below code inside it. It will work as expected.

```<code>import UIKit

UIApplicationMain(CommandLine.argc,
    UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(to: UnsafeMutablePointer<Int8>.self, capacity: Int(CommandLine.argc)), nil, NSStringFromClass(AppDelegate.self))
</code>```

Body:
Add @UIApplicationMain to fix the issue. As well as what it does internally you can do the same by your own. In that case, you don't need to add @UIApplicationMain. Simply create one swift file name it main and put the below code inside it. It will work as expected.

import UIKit

UIApplicationMain(CommandLine.argc,
    UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(to: UnsafeMutablePointer<Int8>.self, capacity: Int(CommandLine.argc)), nil, NSStringFromClass(AppDelegate.self))


问:
Display text in jtextarea with newline and spacing
I have set the text of JTextArea with setText function

```<code>abc="PREFIX table: <http://www.daml.org/2003/01/periodictable/PeriodicTable#> " +
            "SELECT ?name " +
            "FROM <http://www.daml.org/2003/01/periodictable/PeriodicTable.owl>" +
            "WHERE {" +
            "      ?element table:name ?name. " +
            "      FILTER(str(?name)=\"sodium\") " +
            "      }"
texta.setText(abc);//abc is very long string
</code>```

How do I display the string with newlines and spacing in the JTextArea.

答:
```<code>abc="PREFIX table: <http://www.daml.org/2003/01/periodictable/PeriodicTable#>\n" +
        "SELECT ?name\n" +
        "FROM <http://www.daml.org/2003/01/periodictable/PeriodicTable.owl>\n" +
        "WHERE {\n" +
        "      ?element table:name ?name.\n" +
        "      FILTER(str(?name)=\"sodium\")\n" +
        "      }"
</code>```

That should work.

Body:
I have set the text of JTextArea with setText function

abc="PREFIX table: <http://www.daml.org/2003/01/periodictable/PeriodicTable#> " +
            "SELECT ?name " +
            "FROM <http://www.daml.org/2003/01/periodictable/PeriodicTable.owl>" +
            "WHERE {" +
            "      ?element table:name ?name. " +
            "      FILTER(str(?name)=\"sodium\") " +
            "      }"
texta.setText(abc);//abc is very long string

How do I display the string with newlines and spacing in the JTextArea.

Body:
abc="PREFIX table: <http://www.daml.org/2003/01/periodictable/PeriodicTable#>\n" +
        "SELECT ?name\n" +
        "FROM <http://www.daml.org/2003/01/periodictable/PeriodicTable.owl>\n" +
        "WHERE {\n" +
        "      ?element table:name ?name.\n" +
        "      FILTER(str(?name)=\"sodium\")\n" +
        "      }"

That should work.


问:
Android detect webview URL change
I have a webview in my android app and would like to detect when the url changes.

I want to use this to hide the info button in the top bar when the user is on the info.php page and show it again when he is not on the info.php page.

I googled but can't find any working code, can anybody help me?

答:
I know I'm late to the game but I ran into this issue over and over ... I finally found a sloution which is pretty straight forward. Just override WebViewClient.doUpdateVisitedHistory

```<code>override fun doUpdateVisitedHistory(view: WebView?, url: String?, isReload: Boolean) {
    // your code here
    super.doUpdateVisitedHistory(view, url, isReload)
}
</code>```

It works with all url changes even the javascript ones!

If this does not make you happy then I don't know what will :)

Title: Android detect webview URL change

Body:
I know I'm late to the game but I ran into this issue over and over ... I finally found a sloution which is pretty straight forward. Just override WebViewClient.doUpdateVisitedHistory

override fun doUpdateVisitedHistory(view: WebView?, url: String?, isReload: Boolean) {
    // your code here
    super.doUpdateVisitedHistory(view, url, isReload)
}

It works with all url changes even the javascript ones!

If this does not make you happy then I don't know what will :)


问:
printf in bash: "09" and "08" are invalid numbers, "07" and "06" are fine
This is my bash script - I just want to left-pad a set of numbers with zeroes:

```<code>printf "%04d" "09"
printf "%04d" "08"
printf "%04d" "07"
printf "%04d" "06"
</code>```

Output:

```<code>./rename.sh: line 3: printf: 09: invalid number
0000
./rename.sh: line 4: printf: 08: invalid number
0000
0007
0006
</code>```

What...?

Only 09 and 08 are causing the problem: every other number in my sequence seems to be OK.

答:
Much simpler to convert from octal to decimal:</p>

```<code>nm=$((10#$nm))
</code>```

Body:
This is my bash script - I just want to left-pad a set of numbers with zeroes:

printf "%04d" "09"
printf "%04d" "08"
printf "%04d" "07"
printf "%04d" "06"

Output:

./rename.sh: line 3: printf: 09: invalid number
0000
./rename.sh: line 4: printf: 08: invalid number
0000
0007
0006

What...?

Only 09 and 08 are causing the problem: every other number in my sequence seems to be OK.

Body:
Much simpler to convert from octal to decimal:

nm=$((10#$nm))


问:
Replace all occurrences of a string in JSON object regardless of key
I have a JSON object in Python created through requests built in .json() function.

Here is a simplified sample of what I'm doing:

```<code>data = session.get(url)

obj = data.json()

s3object = s3.Object(s3_bucket, output_file)
s3object.put(Body=(bytes(json.dumps(obj).encode('UTF-8'))))
</code>```

Example obj:

```<code>{'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': null, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}
</code>```

I need to replace any occurrence of the string "N/A" with "Not Applicable" anywhere it appears regardless of its key or location before I upload the JSON to S3. I cannot use local disk writes hence the reason this is done this way.

Is this possible?

My original plan was to turn it to a string and just replace before turning back, is this inefficient?

Thanks,

答:
Although @Devesh Kumar Singh's answer works with the sample json data in your question, converting the whole thing to a string, and then doing a wholesale bulk replace of the substring seems possibly error-prone because potentially  it might change it in portions other than only in the values associated with dictionary keys.

To avoid that I would suggest using the following, which is more selective even though it takes a few more lines of code:

```<code>import json

def replace_NA(obj):

    def decode_dict(a_dict):
        for key, value in a_dict.items():
            try:
                a_dict[key] = value.replace('N/A', 'Not Applicable')
            except AttributeError:
                pass
        return a_dict

    return json.loads(json.dumps(obj), object_hook=decode_dict)

obj = {'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': None, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}
obj = replace_NA(obj)
</code>```

Body:
I have a JSON object in Python created through requests built in .json() function.

Here is a simplified sample of what I'm doing:

data = session.get(url)

obj = data.json()

s3object = s3.Object(s3_bucket, output_file)
s3object.put(Body=(bytes(json.dumps(obj).encode('UTF-8'))))

Example obj:

{'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': null, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}

I need to replace any occurrence of the string "N/A" with "Not Applicable" anywhere it appears regardless of its key or location before I upload the JSON to S3. I cannot use local disk writes hence the reason this is done this way.

Is this possible?

My original plan was to turn it to a string and just replace before turning back, is this inefficient?

Thanks,

Body:
Although @Devesh Kumar Singh's answer works with the sample json data in your question, converting the whole thing to a string, and then doing a wholesale bulk replace of the substring seems possibly error-prone because potentially  it might change it in portions other than only in the values associated with dictionary keys.

To avoid that I would suggest using the following, which is more selective even though it takes a few more lines of code:

import json

def replace_NA(obj):

    def decode_dict(a_dict):
        for key, value in a_dict.items():
            try:
                a_dict[key] = value.replace('N/A', 'Not Applicable')
            except AttributeError:
                pass
        return a_dict

    return json.loads(json.dumps(obj), object_hook=decode_dict)

obj = {'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': None, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}
obj = replace_NA(obj)


问:
Unable to put BoxSizer inside Notebook in wxpython
I am trying to put a login/password page inside one tab of a wx.Notebook. But wx.BoxSizer doesn't work - it piles the labels and buttons.

Here is my code.

```<code>    # Define the tab content as classes:
 class TabOne(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        # USERNAME LABEL
        user_sizer = wx.BoxSizer(wx.HORIZONTAL)
        user_lbl = wx.StaticText(self, label="Username:")
        user_sizer.Add(user_lbl, 0, wx.ALL | wx.CENTER, 5)

        # USERNAME CONTROL TEXT
        self.user = wx.TextCtrl(self)
        user_sizer.Add(self.user, 0, wx.ALL | wx.CENTER, 5)

        # Password LABEL
        password_sizer = wx.BoxSizer(wx.HORIZONTAL)

        pass_lbl = wx.StaticText(self, label="Password:")
        password_sizer.Add(pass_lbl, 0, wx.ALL | wx.CENTER, 5)

        # PASSWORD CONTROL TEXT
        self.password = wx.TextCtrl(self, style=wx.TE_PASSWORD | wx.TE_PROCESS_ENTER)
        password_sizer.Add(self.password, 0, wx.ALL, 5)

        # MAIN SIZER FOR TAB A
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(user_sizer, 0, wx.ALL, 5)
        main_sizer.Add(password_sizer, 0, wx.ALL, 5)

        login_btn = wx.Button(self, label="Login")
        login_btn.Bind(wx.EVT_BUTTON,
                       handler=self.onLogin)

        wx.Panel.SetSizer(main_sizer)

    def onLogin(self):
        return self.bot.login(username=self.user, password=self.password, use_cookie=True)
</code>```

答: The problem is that you are assigning the main_sizer in a wrong way. Change the line wx.Panel.SetSizer(main_sizer) to self.SetSizer(main_sizer). Your TabOne class comes from a wx.Panel so in the same way you are making your widgets children of self, you will assign the main_sizer to self.

Body:
I am trying to put a login/password page inside one tab of a wx.Notebook. But wx.BoxSizer doesn't work - it piles the labels and buttons.

Here is my code.

    # Define the tab content as classes:
 class TabOne(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        # USERNAME LABEL
        user_sizer = wx.BoxSizer(wx.HORIZONTAL)
        user_lbl = wx.StaticText(self, label="Username:")
        user_sizer.Add(user_lbl, 0, wx.ALL | wx.CENTER, 5)

        # USERNAME CONTROL TEXT
        self.user = wx.TextCtrl(self)
        user_sizer.Add(self.user, 0, wx.ALL | wx.CENTER, 5)

        # Password LABEL
        password_sizer = wx.BoxSizer(wx.HORIZONTAL)

        pass_lbl = wx.StaticText(self, label="Password:")
        password_sizer.Add(pass_lbl, 0, wx.ALL | wx.CENTER, 5)

        # PASSWORD CONTROL TEXT
        self.password = wx.TextCtrl(self, style=wx.TE_PASSWORD | wx.TE_PROCESS_ENTER)
        password_sizer.Add(self.password, 0, wx.ALL, 5)

        # MAIN SIZER FOR TAB A
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(user_sizer, 0, wx.ALL, 5)
        main_sizer.Add(password_sizer, 0, wx.ALL, 5)

        login_btn = wx.Button(self, label="Login")
        login_btn.Bind(wx.EVT_BUTTON,
                       handler=self.onLogin)

        wx.Panel.SetSizer(main_sizer)

    def onLogin(self):
        return self.bot.login(username=self.user, password=self.password, use_cookie=True)


问:
VB Await an asyc call that also awaits a call
I'm new to VB and not very familiar with async functions.
I need to fix a bug in existing code where some code is building a report before the data has finished loading.

The problem is that BuildReport() is getting called before the loadOption1(data) has been called. I need the application to wait for all of LoadAsync() to complete before running, but when it waits for GetData(), the application is returning to start() and running BuildReport() too early.

The code looks roughly like this:

```<code>Public Async Sub start()

    await LoadAsync()

    BuildReport() ' this must not run until everything in Load is complete

End Sub

Public Async Function LoadAsync() As System.Threading.Tasks.Task
'this is called from other locations, not just from Start()

    dim data = await GetData() 'call to database
    ' at this point start() continues to run
    ' but we need it to keep waiting for these next calls to complete

    'these calls are synchronous, builds objects needed for the report
    loadOption1(data)
    loadOption2(data)
    loadOption3(data)

    'now we want to return to start()
End Function

Public Async Function GetData(s As Scenario) As Task(Of DataResults)

    ...

    Dim resp = Await Task.Run(Function() ConfigWebService.FetchIncentives(req)) ' soap call

End Function
</code>```

(each function is in separate classes within the same project)

I have tried removing the await from the start function; the options load after BuildReport() is called.

if I remove the await from the GetData() call, passing data.result to the loadoptions functions, the whole application just hangs forever.

I'm stumped. Any tips would be greatly appreciated!

edit: updated the sample to correctly reflect the actual code

Update:
I have tried everything I can think of, from .ContinueWith(False), to attaching to the parent task, to using .ContinueWith(), but nothing has worked so far.
As soon as the code hits the await inside the LoadAsync(), the task in Start() is considered complete

答:
the only thing that seemed to work was to making a isLoading flag that gets set to true at the start of LoadAsync(), then set to false after the LoadOptions3() finished. Then checking if the flag's value has changed in a loop with a delay</p>

```<code>Public Async Sub start()

    await LoadAsync()

    For i As Integer = 1 To 50
        If Not IsLoading Then Exit For
        Await System.Threading.Tasks.Task.Delay(100)
    Next

    BuildReport()

End Sub
</code>```

Body:
I'm new to VB and not very familiar with async functions.
I need to fix a bug in existing code where some code is building a report before the data has finished loading.

The problem is that BuildReport() is getting called before the loadOption1(data) has been called. I need the application to wait for all of LoadAsync() to complete before running, but when it waits for GetData(), the application is returning to start() and running BuildReport() too early.

The code looks roughly like this:

Public Async Sub start()

    await LoadAsync()

    BuildReport() ' this must not run until everything in Load is complete

End Sub

Public Async Function LoadAsync() As System.Threading.Tasks.Task
'this is called from other locations, not just from Start()

    dim data = await GetData() 'call to database
    ' at this point start() continues to run
    ' but we need it to keep waiting for these next calls to complete

    'these calls are synchronous, builds objects needed for the report
    loadOption1(data)
    loadOption2(data)
    loadOption3(data)

    'now we want to return to start()
End Function

Public Async Function GetData(s As Scenario) As Task(Of DataResults)

    ...

    Dim resp = Await Task.Run(Function() ConfigWebService.FetchIncentives(req)) ' soap call

End Function

(each function is in separate classes within the same project)

I have tried removing the await from the start function; the options load after BuildReport() is called.

if I remove the await from the GetData() call, passing data.result to the loadoptions functions, the whole application just hangs forever.

I'm stumped. Any tips would be greatly appreciated!

edit: updated the sample to correctly reflect the actual code

Update:
I have tried everything I can think of, from .ContinueWith(False), to attaching to the parent task, to using .ContinueWith(), but nothing has worked so far.
As soon as the code hits the await inside the LoadAsync(), the task in Start() is considered complete

Body:
the only thing that seemed to work was to making a isLoading flag that gets set to true at the start of LoadAsync(), then set to false after the LoadOptions3() finished. Then checking if the flag's value has changed in a loop with a delay

Public Async Sub start()

    await LoadAsync()

    For i As Integer = 1 To 50
        If Not IsLoading Then Exit For
        Await System.Threading.Tasks.Task.Delay(100)
    Next

    BuildReport()

End Sub


问:
tfs: how to unlock changes
I originally edited a file, which did a checkout.  I received a new computer, and now I want to edit the file.  I don't care about the original edit.

TFS reports that another user has an exclusive lock on the file.  It's not actually another user, it's me, but the machine is different, so the workspace is different.

I tried unlocking with the tf commandline using the following command:

tf lock /lock:none /workspace:oldmachinename;domain\me /recursive $/projectname/directory /s:http:tfs:8080/tfs/project

I get no errors, but when I go into Visual studio 2010 (We're using tfs 2010 as well)  The files remain locked.

What am I doing wrong?

答:
Try something like this:

The following example unlocks and makes all files in the src/ Team Foundation version control server folder available for check-out and check-in by other users.

c:\projects>tf lock /lock:none src/

More documentation here:
http://msdn.microsoft.com/en-us/library/47b0c7w9.aspx

Title: tfs: how to unlock changes


问:
java.text.ParseException: Unparseable date: "" cant parse Date
I am trying to parse a String to a date but it shows that the String is empty, although System.out.println gives back "09-11-0013" a line before

```<code>XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)));
String value = (String) d.readObject();
value = value.replace("[", "");
value = value.replace("]", "");
String[] splitted = value.split(",");
for (int i = 0; i < splitted.length; i++) {
    String[] finallysplitted = splitted[i].split(" ");
    finallysplitted[1] = finallysplitted[1].replace(":", "");
    addmemo(new Memo(sdf.parse(finallysplitted[0]) , Category.valueOf(finallysplitted[1]), finallysplitted[2]));
}
</code>```

Expected output is a Date but instead it gives me an error

答:
Your exception :

```<code>java.text.ParseException: Unparseable date: “” cant parse Date
</code>```

Let me assume your split doesn't return what you expect. Since you split using a space, have a space after a comma would explain the problem.

You can check simply by printing the array you create.

To solve it, simply trim the value before splitting it : splitted[i].trim().split(" ");.

Body:
I am trying to parse a String to a date but it shows that the String is empty, although System.out.println gives back "09-11-0013" a line before

XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)));
String value = (String) d.readObject();
value = value.replace("[", "");
value = value.replace("]", "");
String[] splitted = value.split(",");
for (int i = 0; i < splitted.length; i++) {
    String[] finallysplitted = splitted[i].split(" ");
    finallysplitted[1] = finallysplitted[1].replace(":", "");
    addmemo(new Memo(sdf.parse(finallysplitted[0]) , Category.valueOf(finallysplitted[1]), finallysplitted[2]));
}

Expected output is a Date but instead it gives me an error

Body:
Your exception :

java.text.ParseException: Unparseable date: “” cant parse Date

Let me assume your split doesn't return what you expect. Since you split using a space, have a space after a comma would explain the problem.

You can check simply by printing the array you create.

To solve it, simply trim the value before splitting it : splitted[i].trim().split(" ");.


问:
PHP generate random directory for fileupload
I need to generate random directories for user file uploads.
Is it wise to use the following function for this?

```<code>hash('md5', time())
</code>```

I don't want PHP to tamper with the filenames, that's why I thought about using directories for this.

答:
Maybe you could use auto-increment to be sure you never get the same directory name twice:</p>

```<code>$i = file_get_contents('increment.txt');
file_put_contents( $i + 1, 'increment.txt' );

// Then use $i as the directory name

// Or if you want the dirname to be less easily guessed:
$dirname = md5(microtime(true) . $filename) . $i;
</code>```

Body:
I need to generate random directories for user file uploads.
Is it wise to use the following function for this?

hash('md5', time())

I don't want PHP to tamper with the filenames, that's why I thought about using directories for this.

Body:
Maybe you could use auto-increment to be sure you never get the same directory name twice:

$i = file_get_contents('increment.txt');
file_put_contents( $i + 1, 'increment.txt' );

// Then use $i as the directory name

// Or if you want the dirname to be less easily guessed:
$dirname = md5(microtime(true) . $filename) . $i;


问:
PHP MySQL query to find closest match in database
I have a database of dealerships who are allocated the outward element of UK postcodes as their "patch". That is, typically, 1 or 2 characters, so for example a dealership in Andover will look after any enquiry from a postcode beginning DT. However some dealerships share a patch, for example, one dealership might look after GU25 where another looks after GU26.

I need to be able to identify the correct dealership using a query.

So far I've managed to extract the outward element of the postcode from an enquiry form submission.

Now I need to search through the database. However an exact match is not going to work as I need to retain the full outward element in case a patch is split.

Examples.

1) A customer enters DT1 1XL. I extract "DT1" but I need to match this with "DT".

2) A customer enters GU25 4QF. I extract "GU25" and I need to match this with GU25.

$sql = "SELECT * FROM table WHERE outward='DT1'";
```

I'd like this to essentially return, "there's no exact match but we did find DT".

Or if we searched for GU25, "there's an exact match!".

So I need to find the closest match essentially. Any ideas would be hugely appreciated.

答:
There will be many, many ways to skin this cat.  No matter what you settle on, you should employ the best practice of making minimal trips to the database.  I mean, a single trip that makes a UNION of two queries is better than two separate trips.

Here is one query that you could use: (Demo)

Schema (MySQL v5.7)

```<code>CREATE TABLE `test` (
    `outward` varchar(255)
);

INSERT INTO `test` VALUES
('AB5 8YU'),
('DT1 1XL'),
('DT2 9XL'),
('DT25 1XL'),
('DT11 4XL'),
('GU25 4QF'),
('GU2 3RN');
</code>```

Query

```<code>SELECT outward,
FROM test
WHERE outward LIKE 'DT%'
ORDER BY
    IF(LOCATE('DT1 ', outward), 0, 1),
    CAST(SUBSTRING_INDEX(REPLACE(outward, 'DT', ''), ' ', 1) AS UNSIGNED);
</code>```

Result set:

```<code>| outward  |
| -------- |
| DT1 1XL  |
| DT2 9XL  |
| DT11 4XL |
| DT25 1XL |
</code>```

The result set always orders the exact matches before the close matches.  As you iterate the result set rows, you can perform a quick check for an exact match with strpos(). Or you can pass a "matchType" flag in the result set to make processing even easier.
(https://www.db-fiddle.com/f/mWHgBHDTCJ7uyseovygtRe/1)

Be sure to validate/sanitise your user input before feeding those variables into your query.  And use prepared statements with placeholders.

You will need two separate substrings for your query:

The leading letters

The characters up to and including the first encountered space. (Notice the space included in the LOCATE() call.)

In the future, when you have mysql question, please provide a dbfiddle link in your question.  This clarifies the schema, gives volunteers an instant and accurate playground to test on, and this will inevitably yield better, faster, and more correct answers for you.

Body:
I have a database of dealerships who are allocated the outward element of UK postcodes as their "patch". That is, typically, 1 or 2 characters, so for example a dealership in Andover will look after any enquiry from a postcode beginning DT. However some dealerships share a patch, for example, one dealership might look after GU25 where another looks after GU26.

I need to be able to identify the correct dealership using a query.

So far I've managed to extract the outward element of the postcode from an enquiry form submission.

Now I need to search through the database. However an exact match is not going to work as I need to retain the full outward element in case a patch is split.

Examples.

1) A customer enters DT1 1XL. I extract "DT1" but I need to match this with "DT".

2) A customer enters GU25 4QF. I extract "GU25" and I need to match this with GU25.

$sql = "SELECT * FROM table WHERE outward='DT1'";

I'd like this to essentially return, "there's no exact match but we did find DT".

Or if we searched for GU25, "there's an exact match!".

So I need to find the closest match essentially. Any ideas would be hugely appreciated.

Body:
There will be many, many ways to skin this cat.  No matter what you settle on, you should employ the best practice of making minimal trips to the database.  I mean, a single trip that makes a UNION of two queries is better than two separate trips.

Here is one query that you could use: (Demo)

Schema (MySQL v5.7)

CREATE TABLE `test` (
    `outward` varchar(255)
);

INSERT INTO `test` VALUES
('AB5 8YU'),
('DT1 1XL'),
('DT2 9XL'),
('DT25 1XL'),
('DT11 4XL'),
('GU25 4QF'),
('GU2 3RN');

Query

SELECT outward,
FROM test
WHERE outward LIKE 'DT%'
ORDER BY
    IF(LOCATE('DT1 ', outward), 0, 1),
    CAST(SUBSTRING_INDEX(REPLACE(outward, 'DT', ''), ' ', 1) AS UNSIGNED);

Result set:

| outward  |
| -------- |
| DT1 1XL  |
| DT2 9XL  |
| DT11 4XL |
| DT25 1XL |

The result set always orders the exact matches before the close matches.  As you iterate the result set rows, you can perform a quick check for an exact match with strpos(). Or you can pass a "matchType" flag in the result set to make processing even easier.
(https://www.db-fiddle.com/f/mWHgBHDTCJ7uyseovygtRe/1)

Be sure to validate/sanitise your user input before feeding those variables into your query.  And use prepared statements with placeholders.

You will need two separate substrings for your query:

The leading letters

The characters up to and including the first encountered space. (Notice the space included in the LOCATE() call.)

In the future, when you have mysql question, please provide a dbfiddle link in your question.  This clarifies the schema, gives volunteers an instant and accurate playground to test on, and this will inevitably yield better, faster, and more correct answers for you.


问:
Why does Boost property tree write_json save everything as string? Is it possible to change that?
I'm trying to serialize using boost property tree write_json, it saves everything as strings, it's not that data are wrong, but I need to cast them explicitly every time and I want to use them somewhere else. (like in python or other C++ json (non boost) library)

here is some sample code and what I get depending on locale:

```<code>boost::property_tree::ptree root, arr, elem1, elem2;
elem1.put<int>("key0", 0);
elem1.put<bool>("key1", true);
elem2.put<float>("key2", 2.2f);
elem2.put<double>("key3", 3.3);
arr.push_back( std::make_pair("", elem1) );
arr.push_back( std::make_pair("", elem2) );
root.put_child("path1.path2", arr);

std::stringstream ss;
write_json(ss, root);
std::string my_string_to_send_somewhare_else = ss.str();
</code>```

and my_string_to_send_somewhere_else is sth. like this:

```<code>{
    "path1" :
    {
       "path2" :
       [
            {
                 "key0" : "0",
                 "key1" : "true"
            },
            {
                 "key2" : "2.2",
                 "key3" : "3.3"
            }
       ]
    }
}
</code>```

Is there anyway to save them as the values, like:
"key1" : true or "key2" : 2.2?

答:
I ended up adding another function to my utils to solve this:

```<code>#include <string>
#include <regex>
#include <boost/property_tree/json_parser.hpp>

namespace bpt = boost::property_tree;
typedef bpt::ptree JSON;
namespace boost { namespace property_tree {
    inline void write_jsonEx(const std::string & path, const JSON & ptree)
    {
        std::ostringstream oss;
        bpt::write_json(oss, ptree);
        std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\"");
        std::string result = std::regex_replace(oss.str(), reg, "$1");

        std::ofstream file;
        file.open(path);
        file << result;
        file.close();
    }
} }
</code>```

Hope that helps.

Body:
I'm trying to serialize using boost property tree write_json, it saves everything as strings, it's not that data are wrong, but I need to cast them explicitly every time and I want to use them somewhere else. (like in python or other C++ json (non boost) library)

here is some sample code and what I get depending on locale:

boost::property_tree::ptree root, arr, elem1, elem2;
elem1.put<int>("key0", 0);
elem1.put<bool>("key1", true);
elem2.put<float>("key2", 2.2f);
elem2.put<double>("key3", 3.3);
arr.push_back( std::make_pair("", elem1) );
arr.push_back( std::make_pair("", elem2) );
root.put_child("path1.path2", arr);

std::stringstream ss;
write_json(ss, root);
std::string my_string_to_send_somewhare_else = ss.str();

and my_string_to_send_somewhere_else is sth. like this:

{
    "path1" :
    {
       "path2" :
       [
            {
                 "key0" : "0",
                 "key1" : "true"
            },
            {
                 "key2" : "2.2",
                 "key3" : "3.3"
            }
       ]
    }
}

Is there anyway to save them as the values, like:
"key1" : true or "key2" : 2.2?

Body:
I ended up adding another function to my utils to solve this:

#include <string>
#include <regex>
#include <boost/property_tree/json_parser.hpp>

namespace bpt = boost::property_tree;
typedef bpt::ptree JSON;
namespace boost { namespace property_tree {
    inline void write_jsonEx(const std::string & path, const JSON & ptree)
    {
        std::ostringstream oss;
        bpt::write_json(oss, ptree);
        std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\"");
        std::string result = std::regex_replace(oss.str(), reg, "$1");

        std::ofstream file;
        file.open(path);
        file << result;
        file.close();
    }
} }

Hope that helps.


问:
convert a key value pair into 2 different objects
Let me explain here

```<code>let obj = {manager:XYZ}
//output:[{position:"manager",name:"XYZ"}]
</code>```

you can also use lodash to find the solution

答:
Use Object.entries() to get each key/value pair from the object, and map() to iterate over each key:

let obj = {manager:'XYZ'}

let arr = Object.entries(obj).map(([key, val]) => ({position: key, name: val}))

console.log(arr)```

Body:
Let me explain here

let obj = {manager:XYZ}
//output:[{position:"manager",name:"XYZ"}]

you can also use lodash to find the solution


问:
Skipping NULL values in column assignment
There is a database table containing address information like

```<code>+--------------------------------------------------------------+
| name1       | name2 | name3 | street        | zip     | city |
+--------------------------------------------------------------+
| 'Some name' | NULL  | ''    | 'Some street' | '12345' | NULL |
+--------------------------------------------------------------+
</code>```

so some fields may be NULL or empty.

Now I'd like to select

```<code>SELECT
  name1,  /* 'Some name' */
  name2,  /* NULL */
  name3,  /* '' */
  street, /* 'Some street' */
  zip,    /* '12345' */
  city,   /* NULL */

  adr1,   /* Should contain 'Some name' */
  adr2,   /* Should contain 'Some street' */
  adr3,   /* Should contain '12345' */
  adr4,   /* NULL */
  adr5,   /* NULL */
  adr6    /* NULL */
FROM
 adr
</code>```

where adr1 to 6 represent letterhead rows, which should be fillen in order of name1, name2, name3, street, zip, city but should skip NULL or empty values while assinging them.

Does anyone have an idea how to achieve this?

答:
This is a little messy, and relies you have an ID column, however, I think this is what you are after:</p>

```<code>WITH CTE AS(
    SELECT S.YourID,
           S.name1,
           S.name2,
           S.name3,
           S.street,
           S.zip,
           S.city,
           NULLIF(V.Adr,'') AS Adr,
           Line,
           ROW_NUMBER() OVER (PARTITION BY YourID, CASE WHEN NULLIF(V.Adr,'') IS NULL THEN 1 ELSE 0 END ORDER BY Line) AS RN
    FROM (VALUES(1, 'Some name',CONVERT(varchar(10),NULL),'','Some street','12345',CONVERT(varchar(10),NULL))) S(YourID,name1,name2,name3,street,zip,city)
         CROSS APPLY(VALUES(name1,1),(name2,2),(name3,3),(street,3),(zip,4),(city,5)) V(Adr,Line))
SELECT C.YourID,
       MAX(C.name1) AS name1,
       MAX(C.name2) AS name2,
       MAX(C.name3) AS name3,
       MAX(C.street) AS street,
       MAX(C.zip) AS zip,
       MAX(C.city) AS city,
       MAX(CASE WHEN C.RN = 1 THEN C.Adr END) AS Adr1,
       MAX(CASE WHEN C.RN = 2 THEN C.Adr END) AS Adr2,
       MAX(CASE WHEN C.RN = 3 THEN C.Adr END) AS Adr3,
       MAX(CASE WHEN C.RN = 4 THEN C.Adr END) AS Adr4,
       MAX(CASE WHEN C.RN = 5 THEN C.Adr END) AS Adr5,
       MAX(CASE WHEN C.RN = 6 THEN C.Adr END) AS Adr6
FROM CTE C
WHERE C.Adr IS NOT NULL
GROUP BY C.YourID;
</code>```

Body:
There is a database table containing address information like

+--------------------------------------------------------------+
| name1       | name2 | name3 | street        | zip     | city |
+--------------------------------------------------------------+
| 'Some name' | NULL  | ''    | 'Some street' | '12345' | NULL |
+--------------------------------------------------------------+

so some fields may be NULL or empty.

Now I'd like to select

SELECT
  name1,  /* 'Some name' */
  name2,  /* NULL */
  name3,  /* '' */
  street, /* 'Some street' */
  zip,    /* '12345' */
  city,   /* NULL */

  adr1,   /* Should contain 'Some name' */
  adr2,   /* Should contain 'Some street' */
  adr3,   /* Should contain '12345' */
  adr4,   /* NULL */
  adr5,   /* NULL */
  adr6    /* NULL */
FROM
 adr

where adr1 to 6 represent letterhead rows, which should be fillen in order of name1, name2, name3, street, zip, city but should skip NULL or empty values while assinging them.

Does anyone have an idea how to achieve this?

Body:
This is a little messy, and relies you have an ID column, however, I think this is what you are after:

WITH CTE AS(
    SELECT S.YourID,
           S.name1,
           S.name2,
           S.name3,
           S.street,
           S.zip,
           S.city,
           NULLIF(V.Adr,'') AS Adr,
           Line,
           ROW_NUMBER() OVER (PARTITION BY YourID, CASE WHEN NULLIF(V.Adr,'') IS NULL THEN 1 ELSE 0 END ORDER BY Line) AS RN
    FROM (VALUES(1, 'Some name',CONVERT(varchar(10),NULL),'','Some street','12345',CONVERT(varchar(10),NULL))) S(YourID,name1,name2,name3,street,zip,city)
         CROSS APPLY(VALUES(name1,1),(name2,2),(name3,3),(street,3),(zip,4),(city,5)) V(Adr,Line))
SELECT C.YourID,
       MAX(C.name1) AS name1,
       MAX(C.name2) AS name2,
       MAX(C.name3) AS name3,
       MAX(C.street) AS street,
       MAX(C.zip) AS zip,
       MAX(C.city) AS city,
       MAX(CASE WHEN C.RN = 1 THEN C.Adr END) AS Adr1,
       MAX(CASE WHEN C.RN = 2 THEN C.Adr END) AS Adr2,
       MAX(CASE WHEN C.RN = 3 THEN C.Adr END) AS Adr3,
       MAX(CASE WHEN C.RN = 4 THEN C.Adr END) AS Adr4,
       MAX(CASE WHEN C.RN = 5 THEN C.Adr END) AS Adr5,
       MAX(CASE WHEN C.RN = 6 THEN C.Adr END) AS Adr6
FROM CTE C
WHERE C.Adr IS NOT NULL
GROUP BY C.YourID;


问:
How to cancel a promise with $q in angular js
I have a service below. I will call this service every time when I open a model and when I close the model and then open another one the previous values are getting reflected and in this case I want to cancel the promise every time I close the model.

I have tried the following code,

Model closing.js

```<code>$scope.closeButton = function() {
    DetailDataSvc.storeDefer().resolve()
}
</code>```

My Service, (DetailDataSvc)

```<code>self.storeDefer = function() {
    return self.deferReturn;
};

self.getDetailReportData = function(postData, functionName) {
    var promises = {};

    var d = $q.defer(),
        metricDataType;
    self.deferReturn = $q.defer();
    promises = {
        detailReport: metricDataType,
        recommendedMetrics: DataSvc.getData(_logPrefix + functionName, recommendedMetricUrl),
        metricInfo: DataSvc.getData(_logPrefix + functionName, metricInfoUrl)
    };
    $q.all(promises).then(function(res) {
        $log.debug(_logPrefix + 'getDetailReportData(). Called from %s. $q.all Response (raw): ', functionName, res);
        else {
            if (response && !_.isEmpty(_.get(response, 'largeCard.chartData.dataValues.rows')) && response.overlayEnabled) {
                self.getMetricOverLay(pdata, functionName).then(function(overlayData) {
                    response.largeCard.chartData.overlay = overlayData;
                    d.resolve(response);
                }, function(msg, code) {
                    d.reject(msg);
                    $log.error(_logPrefix + 'getDetailReportData().   Error code: %s.  Error: ', code, msg);
                });
            } else {
                d.resolve(response);
            }
        }

    }, function(msg, code) {
        d.reject(msg);
        $log.error(_logPrefix + 'getDetailReportData().   Error code: %s.  Error: ', code, msg);
    });

    return d.promise;

};
</code>```

Can anyone please help me whether the process I followed is the right one.

答:
Assign already created deferred.
Try and change this line:

<s>self.deferReturn =  $q.defer();</s>

self.deferReturn = d;

Body:
I have a service below. I will call this service every time when I open a model and when I close the model and then open another one the previous values are getting reflected and in this case I want to cancel the promise every time I close the model.

I have tried the following code,

Model closing.js

$scope.closeButton = function() {
    DetailDataSvc.storeDefer().resolve()
}

My Service, (DetailDataSvc)

self.storeDefer = function() {
    return self.deferReturn;
};

self.getDetailReportData = function(postData, functionName) {
    var promises = {};

    var d = $q.defer(),
        metricDataType;
    self.deferReturn = $q.defer();
    promises = {
        detailReport: metricDataType,
        recommendedMetrics: DataSvc.getData(_logPrefix + functionName, recommendedMetricUrl),
        metricInfo: DataSvc.getData(_logPrefix + functionName, metricInfoUrl)
    };
    $q.all(promises).then(function(res) {
        $log.debug(_logPrefix + 'getDetailReportData(). Called from %s. $q.all Response (raw): ', functionName, res);
        else {
            if (response && !_.isEmpty(_.get(response, 'largeCard.chartData.dataValues.rows')) && response.overlayEnabled) {
                self.getMetricOverLay(pdata, functionName).then(function(overlayData) {
                    response.largeCard.chartData.overlay = overlayData;
                    d.resolve(response);
                }, function(msg, code) {
                    d.reject(msg);
                    $log.error(_logPrefix + 'getDetailReportData().   Error code: %s.  Error: ', code, msg);
                });
            } else {
                d.resolve(response);
            }
        }

    }, function(msg, code) {
        d.reject(msg);
        $log.error(_logPrefix + 'getDetailReportData().   Error code: %s.  Error: ', code, msg);
    });

    return d.promise;

};

Can anyone please help me whether the process I followed is the right one.


问:
How to display the Project Version as Release name in Azure DevOps
I have the release version in pom.xml. For Example, xyz-0.0.1 is the version in my pom.xml. Azure Build creating the package.

I want to use the version xyz-0.0.1 as a release name in the release pipeline. How can I pass the version to release pipeline and set "Release name format" in options?

答:
Because the version is in a file (pom.xml) you can't put the version in the "Release name format", you need during the release to extract the version from the file and assign the release number.

You can do it with a PowerShell script (I write the concept, you need to find out how exactly to get the xml node):

```<code>$file = Get-Content th/to/pom.xml
# Read the version with something like this:
# $version = Select-Xml -Content $file -XPath "//version"
# Then update the Release name:
Write-Host "##vso[release.updatereleasename]$version"
</code>```

Body:
Because the version is in a file (pom.xml) you can't put the version in the "Release name format", you need during the release to extract the version from the file and assign the release number.

You can do it with a PowerShell script (I write the concept, you need to find out how exactly to get the xml node):

$file = Get-Content th/to/pom.xml
# Read the version with something like this:
# $version = Select-Xml -Content $file -XPath "//version"
# Then update the Release name:
Write-Host "##vso[release.updatereleasename]$version"


问:
why using Myarray.size() returns error : " int object is not callable " but Myarray.size is Ok?
I have a wierd Problem which is when i use .size() i get error but using .size is ok.
look at below :

a = np.zeros([5,5])
a.size # returns 25
a.size() # returns error : "int obj is not callable "
a.shape # returns (5,5)

```

<p>The problem is that i must have .size() working because I'm defining an embedding layer "emb_layer" in Pytorch and trying to load its state using a matrix called " weights_matrix " :</p>

```emb_layer.load_state_dict({'weight': weights_matrix})

```

<p>and it seems .load_state_dict() uses .size() inside !</p>

<pre class="lang-py prettyprint-override"><code>
~\Anaconda3\lib\site-packages\torch\nn\modules\module.py in _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
    709                                       'whose dimensions in the model are {} and '
    710                                       'whose dimensions in the checkpoint are {}.'
--> 711                                       .format(key, param.size(), input_param.size()))
    712             elif strict:
    713                 missing_keys.append(key)

TypeError: 'int' object is not callable

</code>```

what should i do ?

答:
ndarray.size is an attribute, not a function. You can't call it because it is actually just a number:

ndarray.size

Number of elements in the array.

Equal to np.prod(a.shape), i.e., the product of the array’s dimensions.

Notes

a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested np.prod(a.shape), which returns an instance of np.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.

Body:
I have a wierd Problem which is when i use .size() i get error but using .size is ok.
look at below :

a = np.zeros([5,5])
a.size # returns 25
a.size() # returns error : "int obj is not callable "
a.shape # returns (5,5)

The problem is that i must have .size() working because I'm defining an embedding layer "emb_layer" in Pytorch and trying to load its state using a matrix called " weights_matrix " :

emb_layer.load_state_dict({'weight': weights_matrix})

and it seems .load_state_dict() uses .size() inside !

~\Anaconda3\lib\site-packages\torch\nn\modules\module.py in _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
    709                                       'whose dimensions in the model are {} and '
    710                                       'whose dimensions in the checkpoint are {}.'
--> 711                                       .format(key, param.size(), input_param.size()))
    712             elif strict:
    713                 missing_keys.append(key)

TypeError: 'int' object is not callable

what should i do ?


问:
how I can skip passing optional parameter to stored procedure in Linq to SQL
I am using Linq to SQL with stored procedures.

I have to pass parameters to stored procedures even if they are optional (where I have set the default value for parameters in stored procedures). Is there any way that I may skip passing default parameters.

Thanks

答:
You can do this: http://challadotnetfaq.blogspot.com/2009/05/stored-procedure-optional-parameters.html

you can if you map the sp to a method with optional parameters


问:
Add string prefix and string end to dataframe column
I want to add steing prefix and string end to all values of my column of dataframe.
In the beginning i want to add r'\b
In the end i want to add \b
I did This but it doesn't give what i want.
A sample of my dataframe is
enter image description here

```<code> df['col'] = r'r\b' + df['col'].astype(str) + r'\b'
</code>```

答:
This should be the thing you seek:

```<code>df['col'] = '\\b' + df['col'] + '\\b'
</code>```

Your r'' is only notation that the string is raw.

Body:
I want to add steing prefix and string end to all values of my column of dataframe.
In the beginning i want to add r'\b
In the end i want to add \b
I did This but it doesn't give what i want.
A sample of my dataframe is
enter image description here

 df['col'] = r'r\b' + df['col'].astype(str) + r'\b'

Body:
This should be the thing you seek:

df['col'] = '\\b' + df['col'] + '\\b'

Your r'' is only notation that the string is raw.