问:
How can I use another mapping from different class in mapstruct
I would like to mapping a model object to dto model. I already have mapper for one of the object.
How can I reuse this mapper in another mapper which is in another class?

I have below as model

```<code>    @Getter
    @AllArgsConstructor
    @ToString
    public class History {

      @JsonProperty("identifier")
      private final Identifier identifier;

    @JsonProperty("submitTime")
    private final ZonedDateTime submitTime;

    @JsonProperty("method")
    private final String method;

    @JsonProperty("reason")
    private final String reason;

    @JsonProperty("dataList")
    private final List<Data> dataList;
   }

     @DynamoDBTable(tableName = "history")
     @Data
     @NoArgsConstructor
     public class HistoryDynamo {
        @DynamoDBRangeKey(attributeName = "submitTime")
        @DynamoDBTypeConverted(converter = ZonedDateTimeType.Converter.class)
        private ZonedDateTime submitTime;

        @DynamoDBAttribute(attributeName = "identifier")
        @NonNull
        private Identifier identifier;

        @DynamoDBAttribute(attributeName = "method")
        private String method;

         @DynamoDBAttribute(attributeName = "reason")
         private String reason;

         @DynamoDBAttribute(attributeName = "dataList")
         private List<Data> dataList;
     }

        @Data
        @DynamoDBDocument
        @NoArgsConstructor
        public class Identifier implements Serializable {

            @DynamoDBAttribute(attributeName = "number")
            private String number;

        @DynamoDBAttribute(attributeName = "cityCode")
        @NonNull
        private String cityCode;

        @DynamoDBAttribute(attributeName = "countryCode")
        @NonNull
        private String countryCode;

        @DynamoDBTypeConverted(converter = LocalDateType.Converter.class)
        private LocalDate mydate;
    }

         @Data
         @EqualsAndHashCode
         @NoArgsConstructor
         @RequiredArgsConstructor
         @JsonInclude(JsonInclude.Include.NON_NULL)
         public class Identifier implements Serializable {

        @NonNull
        @lombok.NonNull
        @NotNull
        private String number;

        @NonNull
        @lombok.NonNull
        @NotNull
        private City city;

        @NonNull
        @lombok.NonNull
        @NotNull
        private Country country;

        @JsonDeserialize(using = LocalDateDeserializer.class)
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'Z'")
        @DateTimeFormat(pattern = "yyyy-MM-dd'Z'")
        @NonNull
        @lombok.NonNull
        @NotNull
        private LocalDate mydate;
    }
</code>```

And here is my mapping

```<code>    @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN, injectionStrategy = InjectionStrategy.CONSTRUCTOR, nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL)
    public interface IdentifierMapper {

        IdentifierMapper MAPPER = Mappers.getMapper(IdentifierMapper.class);

        @Mappings({@Mapping(source = "identifier.number", target = "number"),
                   @Mapping(source = "identifier.city.code", target = "cityCode"),
                   @Mapping(source = "identifier.country.code", target = "countryCode"),
                   @Mapping(source = "identifier.mydate", target = "mydate")})
        @Named("toIdentifierDynamo")
        myproject.entity.dynamo.Identifier toIdentifierDynamo(myproject.model.Identifier identifier);
    }

    @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN, injectionStrategy = InjectionStrategy.CONSTRUCTOR,
            nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL, uses = {IdentifierMapper.class})
    public interface HistoryMapper {

        HistoryMapper MAPPER = Mappers.getMapper(HistoryMapper.class);

        @Mappings({@Mapping(source = "identifier", target = "identifier", qualifiedByName = "toIdentifierDynamo"),
                  @Mapping(source = "method", target = "method"),
                  @Mapping(source = "reason", target = "reason"),
                  @Mapping(source = "timestamp", target = "timestamp")})
        HistoryDynamo toHistoryDynamo(History history);
    }
</code>```

I would like to map History to HistoryDynamo and reuse IdentifierMapper to map one of the object in HistoryDynamo.
How can I use toIdentifierDynamo in toHistoryDynamo?

答:
Using spring dependency can be injected easily as

```<code>private final HistoryMapper
 historyMapper;
</code>```

Also for fields with same name in target and source no need to use @Mapping, so in above case below mapper definition is enough to acheive desired result.

```<code>@Mapper(
    componentModel = "spring",
    injectionStrategy = InjectionStrategy.CONSTRUCTOR,
    uses = {IdentifierMapper.class})
public interface HistoryMapper {

  HistoryDynamo toHistoryDynamo(History history);

}
</code>```

Refer github sample here https://github.com/rakesh-singh-samples/map-struct-samples/tree/stack-question-60523230/src/sample/mapstruct/mapper

Body:
I would like to mapping a model object to dto model. I already have mapper for one of the object.
How can I reuse this mapper in another mapper which is in another class?

I have below as model

    @Getter
    @AllArgsConstructor
    @ToString
    public class History {

      @JsonProperty("identifier")
      private final Identifier identifier;

    @JsonProperty("submitTime")
    private final ZonedDateTime submitTime;

    @JsonProperty("method")
    private final String method;

    @JsonProperty("reason")
    private final String reason;

    @JsonProperty("dataList")
    private final List<Data> dataList;
   }

     @DynamoDBTable(tableName = "history")
     @Data
     @NoArgsConstructor
     public class HistoryDynamo {
        @DynamoDBRangeKey(attributeName = "submitTime")
        @DynamoDBTypeConverted(converter = ZonedDateTimeType.Converter.class)
        private ZonedDateTime submitTime;

        @DynamoDBAttribute(attributeName = "identifier")
        @NonNull
        private Identifier identifier;

        @DynamoDBAttribute(attributeName = "method")
        private String method;

         @DynamoDBAttribute(attributeName = "reason")
         private String reason;

         @DynamoDBAttribute(attributeName = "dataList")
         private List<Data> dataList;
     }

        @Data
        @DynamoDBDocument
        @NoArgsConstructor
        public class Identifier implements Serializable {

            @DynamoDBAttribute(attributeName = "number")
            private String number;

        @DynamoDBAttribute(attributeName = "cityCode")
        @NonNull
        private String cityCode;

        @DynamoDBAttribute(attributeName = "countryCode")
        @NonNull
        private String countryCode;

        @DynamoDBTypeConverted(converter = LocalDateType.Converter.class)
        private LocalDate mydate;
    }

         @Data
         @EqualsAndHashCode
         @NoArgsConstructor
         @RequiredArgsConstructor
         @JsonInclude(JsonInclude.Include.NON_NULL)
         public class Identifier implements Serializable {

        @NonNull
        @lombok.NonNull
        @NotNull
        private String number;

        @NonNull
        @lombok.NonNull
        @NotNull
        private City city;

        @NonNull
        @lombok.NonNull
        @NotNull
        private Country country;

        @JsonDeserialize(using = LocalDateDeserializer.class)
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'Z'")
        @DateTimeFormat(pattern = "yyyy-MM-dd'Z'")
        @NonNull
        @lombok.NonNull
        @NotNull
        private LocalDate mydate;
    }

And here is my mapping

    @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN, injectionStrategy = InjectionStrategy.CONSTRUCTOR, nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL)
    public interface IdentifierMapper {

        IdentifierMapper MAPPER = Mappers.getMapper(IdentifierMapper.class);

        @Mappings({@Mapping(source = "identifier.number", target = "number"),
                   @Mapping(source = "identifier.city.code", target = "cityCode"),
                   @Mapping(source = "identifier.country.code", target = "countryCode"),
                   @Mapping(source = "identifier.mydate", target = "mydate")})
        @Named("toIdentifierDynamo")
        myproject.entity.dynamo.Identifier toIdentifierDynamo(myproject.model.Identifier identifier);
    }

    @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN, injectionStrategy = InjectionStrategy.CONSTRUCTOR,
            nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL, uses = {IdentifierMapper.class})
    public interface HistoryMapper {

        HistoryMapper MAPPER = Mappers.getMapper(HistoryMapper.class);

        @Mappings({@Mapping(source = "identifier", target = "identifier", qualifiedByName = "toIdentifierDynamo"),
                  @Mapping(source = "method", target = "method"),
                  @Mapping(source = "reason", target = "reason"),
                  @Mapping(source = "timestamp", target = "timestamp")})
        HistoryDynamo toHistoryDynamo(History history);
    }

I would like to map History to HistoryDynamo and reuse IdentifierMapper to map one of the object in HistoryDynamo.
How can I use toIdentifierDynamo in toHistoryDynamo?

Body:
Using spring dependency can be injected easily as

private final HistoryMapper
 historyMapper;

Also for fields with same name in target and source no need to use @Mapping, so in above case below mapper definition is enough to acheive desired result.

@Mapper(
    componentModel = "spring",
    injectionStrategy = InjectionStrategy.CONSTRUCTOR,
    uses = {IdentifierMapper.class})
public interface HistoryMapper {

  HistoryDynamo toHistoryDynamo(History history);

}

Refer github sample here https://github.com/rakesh-singh-samples/map-struct-samples/tree/stack-question-60523230/src/sample/mapstruct/mapper


来源: stackexchange

问:
Pythonic way to find duplicate and unique values in a list of dictonaries
I have a list of dictonaries:

```<code>[
{'name' : 'product a', 'sku': 'p100', 'price: 1.2},
{'name' : 'product x', 'sku': 'p120', 'price: 1.3},
{'name' : 'product x', 'sku': 'p100', 'price: 2.2},
{'name' : 'product a', 'sku': 'p100', 'price: 4.1},
{'name' : 'product a', 'sku': 'p20', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 2.2}]
</code>```

And I want to find duplicate and unique values of sku and return them as two new lists. (Duplicate in my case means 3 or more times. Triplicate)

This is a working solution:

```<code>def find_dict_duplicates(lines, key, times=2):
    duplicate = []
    unique = []
    for line in lines:
        count = 0
        for l in lines:
            if line[key] == l[key]:
                count += 1
        if count > times:
            duplicates.append(line)
        else:
            unique.append(line)
return duplicate, unique
</code>```

Results:

```<code>duplicates =
[
{'name' : 'product a', 'sku': 'p100', 'price: 1.2},
{'name' : 'product a', 'sku': 'p100', 'price: 2.2},
{'name' : 'product a', 'sku': 'p100', 'price: 4.1}]

unique =
[
{'name' : 'product a', 'sku': 'p120', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 2.2}]    # The critiria is more than 2 times to be consider duplicate so this is correct
</code>```

But is super slow and ugly.
Is slow because if a list contains 50.000 products then the comparison needed is 50.000^2 = 2.500.000.000 (5+ minutes waiting)
And ugly since this is more like c than python.

Can you sudgest a better way?

答:
EDIT: After Getting Rid of Threading it's even faster

Because There's alot going on I recommend First Trying to figure out what's happening by visualizing in a debugger

def find_dict_duplicates(lines, key, times=2):
    duplicate = []
    unique = []
    added_values = {}

    def add_to_list(add_into, index_of_items_to_add):
        for ind in index_of_items_to_add:
            add_into.append(lines[ind])

    # Loops Through All The lines and saves Them with their index and Value
    values = {ind: line[key] for ind, line in enumerate(lines)}

    # Loops Through the index and values line by line created above
    for ind, val in values.items():
        # Adds the current Index to the added_values dict
        # and stores them like this item: [indexes]

        if val not in added_values:
            added_values[val] = [ind]

        # If the item was already added in the dict we just append the new index to it
        else:
            added_values[val].append(ind)

    # Now loops Through all The Indexes Created By Above Loop
    for item in added_values.values():
        if len(item) > times:
            list_to_add_to = duplicate

        else:
            list_to_add_to = unique

        # Does some checking above and Adds the current Item to the correct dictionary
        add_to_list(list_to_add_to, item)

    return duplicate, unique
```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of dictonaries:

[
{'name' : 'product a', 'sku': 'p100', 'price: 1.2},
{'name' : 'product x', 'sku': 'p120', 'price: 1.3},
{'name' : 'product x', 'sku': 'p100', 'price: 2.2},
{'name' : 'product a', 'sku': 'p100', 'price: 4.1},
{'name' : 'product a', 'sku': 'p20', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 2.2}]

And I want to find duplicate and unique values of sku and return them as two new lists. (Duplicate in my case means 3 or more times. Triplicate)

This is a working solution:

def find_dict_duplicates(lines, key, times=2):
    duplicate = []
    unique = []
    for line in lines:
        count = 0
        for l in lines:
            if line[key] == l[key]:
                count += 1
        if count > times:
            duplicates.append(line)
        else:
            unique.append(line)
return duplicate, unique

Results:

duplicates =
[
{'name' : 'product a', 'sku': 'p100', 'price: 1.2},
{'name' : 'product a', 'sku': 'p100', 'price: 2.2},
{'name' : 'product a', 'sku': 'p100', 'price: 4.1}]

unique =
[
{'name' : 'product a', 'sku': 'p120', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 2.2}]    # The critiria is more than 2 times to be consider duplicate so this is correct

But is super slow and ugly.
Is slow because if a list contains 50.000 products then the comparison needed is 50.000^2 = 2.500.000.000 (5+ minutes waiting)
And ugly since this is more like c than python.

Can you sudgest a better way?


问:
Convert JSON date in the "mm dd yyyy" format
In my application the Date Fiend JSON response comes as this type:

```<code> "CreatedOn": "\/Date(1313572467987+0000)\/"
</code>```

I want to convert this date in the "MM DD YYYY" format. How can I convert this?

答:
you can use SimpleDateFormat, so just try to search on the same.

Detailed example is here: http://www.helloandroid.com/tutorials/date-handling-android-development

ContentLicense: CC BY-SA 3.0

Body:
In my application the Date Fiend JSON response comes as this type:

 "CreatedOn": "\/Date(1313572467987+0000)\/"

I want to convert this date in the "MM DD YYYY" format. How can I convert this?


问:
Remove insignificant trailing zeros from a number?
Have I missed a standard API call that removes trailing insignificant zeros from a number?

```<code>var x = 1.234000; // to become 1.234
var y = 1.234001; // stays 1.234001
</code>```

Number.toFixed() and Number.toPrecision() are not quite what I'm looking for.

答:
So you want

```<code>var x = 1.234000; // to become 1.234
var y = 1.234001; // stays 1.234001
</code>```

No strings attached, just try Number().

var x  = 1.234000, // to become 1.234
    y  = 1.234001, // stays 1.234001
    x_ = Number(x),
    y_ = Number(y);

console.log(x_,y_);```

Body:
Have I missed a standard API call that removes trailing insignificant zeros from a number?

var x = 1.234000; // to become 1.234
var y = 1.234001; // stays 1.234001

Number.toFixed() and Number.toPrecision() are not quite what I'm looking for.

Body:
So you want

var x = 1.234000; // to become 1.234
var y = 1.234001; // stays 1.234001

No strings attached, just try Number().

var x  = 1.234000, // to become 1.234
    y  = 1.234001, // stays 1.234001
    x_ = Number(x),
    y_ = Number(y);

console.log(x_,y_);


问:
Buttons are not spaced with css present
I'm having a problem with buttons in CSS.

Between the first two I get the right distance, but between the second and the third I get two buttons joined (attached) (as in the picture).

How can I solve this problem?

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="buttons">
  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />
</div></code>```

答: You selector is faulty, u have selected 'bottom form, INSTEAD of botto. The later would have selected all the 3 buttons n have applied the CSS rules to all the 3.</p>

Title: Buttons are not spaced with css present

Body:
I'm having a problem with buttons in CSS.

Between the first two I get the right distance, but between the second and the third I get two buttons joined (attached) (as in the picture).

How can I solve this problem?

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}

  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />


问:
Why is the Vue app div not filling the whole width?
Just created my first view project and having trouble setting the width of #app to max width of screen. Are HTML objects not supposed to inherit their parents w/h?

I've tried setting width to 100vw and other solutions suggested on google/stackoverflow.

The index.html only consists of a body with a div with id="app".

Inspect element

```<code>
<style>

@font-face {
    font-family: "Gotham";
    src: local("Gotham Medium"),
    url(./fonts/gotham/GothamRoundedMedium_21022.ttf) format("truetype");

    font-family: "Gotham";
    src: local("Gotham Bold"),
    url(./fonts/gotham/GothamRoundedBold_21016.ttf) format("truetype");

}

body {
  max-width: 1980px;
}

#app {
  font-family: Gotham,Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  max-width: inherit;
  color: #2c3e50;
}

</style>```
```

答:
Try checking margins and paddings. By default, it is not 0. Setting the margin and padding is not the best option, but here it should help.

*,*::before,*:;after{
margin: 0;
padding:0;
}```


问:
What is Azure Redis Cache?
What is Azure REDIS Cache? How to use it? When to use and when not to use it? Can I use it for a simple c# application which accesses data from MS-SQL server?
What is best source to get started with Azure Redis cache?</p>

答:
Azure Cache for Redis provides an in-memory data store based on the Redis software. Redis improves the performance and scalability of an application that uses backend data stores heavily
In my application I have stored around 5 millions key/value data with each key containing around 800 records in json format under Redis cache. Called the Redis using stackexchange library(1.2.6) since the application does not support the latest version

You can go through the below links

https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-overview

https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-redis-samples

Title: What is Azure Redis Cache?


问:
how to call derived function using base class object
```<code>class Parent
{
    public int GetNo()
    {
        return 1;
    }
}

class Child : Parent
{
    public Child()
    {

    }

    public int GetNo()
    {
        return 2;
    }
}

Parent p = new Child();
p.GetNo();
</code>```

But it calls Base.GetNo(). I know if I use virutal in base it will call Child.GetNo()
But i can't use virutal in Base becuase i have to derive my class from base which is already distributed in DLL.So there's no way i can modify the existing functions of base class.

Any sugguestions are valued.
Thanks

答:
Without virtual declared on the method, the base method will always be called because you declared your variable as Parent. If you can't append virtual to the base class, then you can only either declare the variable as Child, or cast it to Child and call your GetNo method:

```<code>Child p = new Child();
p.GetNo();
</code>```

Or:

```<code>Parent p = new Child();
((Child)p).GetNo();
</code>```

Body:
class Parent
{
    public int GetNo()
    {
        return 1;
    }
}

class Child : Parent
{
    public Child()
    {

    }

    public int GetNo()
    {
        return 2;
    }
}

Parent p = new Child();
p.GetNo();

But it calls Base.GetNo(). I know if I use virutal in base it will call Child.GetNo()
But i can't use virutal in Base becuase i have to derive my class from base which is already distributed in DLL.So there's no way i can modify the existing functions of base class.

Any sugguestions are valued.
Thanks

Body:
Without virtual declared on the method, the base method will always be called because you declared your variable as Parent. If you can't append virtual to the base class, then you can only either declare the variable as Child, or cast it to Child and call your GetNo method:

Child p = new Child();
p.GetNo();

Or:

Parent p = new Child();
((Child)p).GetNo();


问:
scrollbar does not appear
So the scrollbar is not showing when entering the page, it only appears if using mouse scroll
I already tried to put:
z index: 10

overflow: roll

!important

But none worked, it still has the same bug, I don't know what it could be. I'm using plugin-perfect-scrollbar.scss in version 1.4.0

Container

.ps {
  background-color: aqua;
}
```
<p>scrollbar</p>
<pre class="lang-css prettyprint-override"><code>.ps__rail-x {
  display: none;
  opacity: 1 !important;
  transition: background-color .2s linear, opacity .2s linear;
  -webkit-transition: background-color .2s linear, opacity .2s linear;
  height: 15px;
  /* there must be 'bottom' or 'top' for ps__rail-x */
  bottom: 0px;
  /* please don't change 'position' */
  position: absolute;
}

.ps__rail-y {
  display: none;
  opacity: 1 !important;
  transition: background-color .2s linear, opacity .2s linear;
  -webkit-transition: background-color .2s linear, opacity .2s linear;
  width: 15px;
  /* there must be 'right' or 'left' for ps__rail-y */
  right: 0;
  /* please don't change 'position' */
  position: absolute;
}
</code>```

答:
You have to set overflow: scroll; then you can insert a manual scrollbar by adding ::-webkit-scrollbar in your CSS. Meaning - wherever there is a scrollbar or an overflow: scroll; these styles will take effect.

Mini demonstration below:

div {
  border: solid black 1px;
  width: 300px;
  height: 40px;
  overflow: scroll;
}

::-webkit-scrollbar {
    width: 10px;
}

::-webkit-scrollbar-track {
    box-shadow: inset 0 0 10px 10px #ffd110;
}

::-webkit-scrollbar-thumb {
    box-shadow: inset 0 0 10px 10px black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>DIVDIVDIVDIVDIVDIVDIVDIVDIV<br>DIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIV</p>
</div></code>```

Title: scrollbar does not appear

Body:
So the scrollbar is not showing when entering the page, it only appears if using mouse scroll
I already tried to put:
z index: 10

overflow: roll

!important

But none worked, it still has the same bug, I don't know what it could be. I'm using plugin-perfect-scrollbar.scss in version 1.4.0

Container

.ps {
  background-color: aqua;
}

scrollbar

.ps__rail-x {
  display: none;
  opacity: 1 !important;
  transition: background-color .2s linear, opacity .2s linear;
  -webkit-transition: background-color .2s linear, opacity .2s linear;
  height: 15px;
  /* there must be 'bottom' or 'top' for ps__rail-x */
  bottom: 0px;
  /* please don't change 'position' */
  position: absolute;
}

.ps__rail-y {
  display: none;
  opacity: 1 !important;
  transition: background-color .2s linear, opacity .2s linear;
  -webkit-transition: background-color .2s linear, opacity .2s linear;
  width: 15px;
  /* there must be 'right' or 'left' for ps__rail-y */
  right: 0;
  /* please don't change 'position' */
  position: absolute;
}

Body:
You have to set overflow: scroll; then you can insert a manual scrollbar by adding ::-webkit-scrollbar in your CSS. Meaning - wherever there is a scrollbar or an overflow: scroll; these styles will take effect.

Mini demonstration below:

div {
  border: solid black 1px;
  width: 300px;
  height: 40px;
  overflow: scroll;
}

::-webkit-scrollbar {
    width: 10px;
}

::-webkit-scrollbar-track {
    box-shadow: inset 0 0 10px 10px #ffd110;
}

::-webkit-scrollbar-thumb {
    box-shadow: inset 0 0 10px 10px black;
}

<div>
  <p>DIVDIVDIVDIVDIVDIVDIVDIVDIV<br>DIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIVDIV</p>
</div>


问:
remove duplicated rows and convert it to list or tuple
I have dataframe as follows (Name is index):

Name
Age
year

Tom
20
2020

Tom
20
2021

Nick
19
2019

Jack
18
2018

my goal is to remove duplicate and convert the column year to tuple or list, like below

Name
Age
year

Tom
20
(2020, 2019)

Nick
19
2019

Jack
18
2018

how can I do that efficiently since my df has more than 800,000 rows

答:
Use np.unique on groupby. Assuming Name is already the index:

```<code>>>> df.groupby(level=0).agg(np.unique)
      Age          year
Name
Jack   18          2018
Nick   19          2019
Tom    20  [2020, 2021]
</code>```

Body:
Use np.unique on groupby. Assuming Name is already the index:

>>> df.groupby(level=0).agg(np.unique)
      Age          year
Name
Jack   18          2018
Nick   19          2019
Tom    20  [2020, 2021]


问:
bash execute functions based on certain word in arguments
i have the following bash script contains multiple functions

```<code>#!/usr/bin/bash

#checks if the arguments is directory and extract the domain name from it
if [[ -d "$1" ]]; then
    domain=$(echo "$1" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
    WORKING_DIR="$1"
else
    domain="$1"
    echo "it is domain name"
fi

example_fun1(){
    ping -c 4 $domain
}

example_fun2(){
    nslookup $domain
}

for x in "$@" ;do
    example_fun1 $x
    example_fun2 $x
done
</code>```

and run as following

```<code>./script.sh ./pathtofolder/example.com/ ./pathtofolder/test.com/
</code>```

Or

```<code>./script.sh example.com test.com
</code>```

and working probably BUT i need to add more feature which is check if certain word based in arguments like fun1 it will execute function example_fun1 only

desired execution

```<code>./script.sh fun1 ./pathtofolder/example.com/ ./pathtofolder/test.com/
</code>```

OR

```<code>./script.sh fun1 example.com test.com
</code>```

Thanks

答:
Assign the first parameter to a variable, then use that when calling the function.

```<code>func="example_$1"
shift

for x in "$@"; do
    "$func" "$x"
done
</code>```

And your functions need to use their parameters, not a variable that's set in the main script:

```<code>example_fun1(){
    ping -c 4 "$1"
}

example_fun2(){
    nslookup "$1"
}
</code>```

Body:
i have the following bash script contains multiple functions

#!/usr/bin/bash

#checks if the arguments is directory and extract the domain name from it
if [[ -d "$1" ]]; then
    domain=$(echo "$1" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
    WORKING_DIR="$1"
else
    domain="$1"
    echo "it is domain name"
fi

example_fun1(){
    ping -c 4 $domain
}

example_fun2(){
    nslookup $domain
}

for x in "$@" ;do
    example_fun1 $x
    example_fun2 $x
done

and run as following

./script.sh ./pathtofolder/example.com/ ./pathtofolder/test.com/

Or

./script.sh example.com test.com

and working probably BUT i need to add more feature which is check if certain word based in arguments like fun1 it will execute function example_fun1 only

desired execution

./script.sh fun1 ./pathtofolder/example.com/ ./pathtofolder/test.com/

OR

./script.sh fun1 example.com test.com

Thanks

Body:
Assign the first parameter to a variable, then use that when calling the function.

func="example_$1"
shift

for x in "$@"; do
    "$func" "$x"
done

And your functions need to use their parameters, not a variable that's set in the main script:

example_fun1(){
    ping -c 4 "$1"
}

example_fun2(){
    nslookup "$1"
}


问:
Fluent Validation does not work as expected in child components
I'm trying to set up fluent validation for my application. Validation works fine for parent component. It shows messages as leave a field. However, it does not work in same way with child components. Validation messages do not appear.

It works only if I execute EditContext.Validate method.

Any ideas how to fix this? Thank you.

Models:

```<code>namespace Application.Models
{
    public class Company
    {
        ...
        public string Name { get; set; }

        public int headquartersId { get; set; }
        public Address Headquarters { get; set; }
        ...
    }
    public class Address
    {
        ...
        public string Street { get; set; }
        ...
    }
}
</code>```

Validators:

```<code>using Application.Models
using FluentValidation

namespace Application.Validators
{
   public class CompanyValidator: AbstractValidator<Company>
   {
      public CompanyValidator()
      {
         RuleFor(fields => fields.Name)
         .MinimumLength(5)
         .WithMessage("---");

         RuleFor(field => field.Headquarters).SetValidator(new AddressValidator());
      }
   }
   public class AddressValidator: AbstractValidator<Address>
   {
      public AddressValidator()
      {
          RuleFor(fields => fields.Street)
          .MinimumLength(5)
          .WithMessage("---");
      }
   }
}
</code>```

Parent Component:

```<code>@using Application.Models.Cards.Customers
@using Application.Models
@using FluentValidation

<EditForm EditContext="editContext" OnSubmit="Submit">

    <FluentValidationValidator />

    <div class="form-group">
        <label for="fname">Business Entity Name</label>
        <InputText name="fname" @bind-Value="Customer.Name" class="form-control"></InputText>
        <ValidationMessage For="@(() => Customer.Name)" />
    </div>
    <div class="form-group">
        <label for="fname">Business Entity Code</label>
        <InputText name="fname" @bind-Value="Customer.Code" class="form-control"></InputText>
        <ValidationMessage For="@(() => Customer.Code)"></ValidationMessage>
    </div>
    <div class="form-group">
        <label for="fname">Business Entity VAT</label>
        <InputText name="fname" @bind-Value="Customer.VAT" class="form-control"></InputText>
        <ValidationMessage For="@(() => Customer.VAT)"></ValidationMessage>
    </div>
    **<AddressComponent Address="Customer.Headquarters" SetCurrentAddress="GetAddress"/>**

    <button type="submit" class="btn btn-primary">Save</button>

</EditForm>

@code {
    [Parameter]
    public Company Customer { get; set; }

    #nullable enable
    private EditContext? editContext;

    protected override Task OnInitializedAsync()
    {
        editContext = new EditContext(Customer);
        return base.OnInitializedAsync();
    }

    private void GetAddress(Address address)
    {
        Customer.Headquarters = address;
    }

    private void Submit()
    {
        editContext?.Validate();
    }
}
</code>```

Address Component:

```<code>@using Application.Models

<div class="row">
    <div class="form-group col-3">
        <label for="house">House</label>
        <input type="number" name="house" @bind-Value="Address.House" @bind-Value:event="oninput"  class="form-control" />
        <ValidationMessage For="@(() => Address.House)" />
    </div>
    <div class="form-group col-9">
        <label for="street">Street</label>
        <input type="text" name="street" @bind="Address.Street" @bind:event ="oninput" @onkeyup="OnAddressChange" class="form-control" />
        <ValidationMessage For="@(() => Address.Street)" />
    </div>
</div>
<div class="row">
    <div class="form-group col-3">
        <label for="postCode">Post Code</label>
        <input type="text" name="postCode" @bind="Address.PostCode" @bind:event="oninput" @onkeyup="OnAddressChange" class="form-control" />
        <ValidationMessage For="@(() => Address.PostCode)" />
    </div>
    <div class="form-group col-9">
        <label for="county">County</label>
        <input type="text" name="county" @bind="@Address.County" @bind:event="oninput" @onkeyup="OnAddressChange" class="form-control" />
        <ValidationMessage For="@(() => Address.County)" />
    </div>
</div>
<div class="row">
    <div class="form-group col-12">
        <label for="country">Country</label>
        <input type="text" name="country" @bind="Address.Country" @bind:event="oninput" @onkeyup="OnAddressChange" class="form-control" />
        <ValidationMessage For="@(() => Address.Country)" />
    </div>
</div>

@code {

    [Parameter]
    public Address Address { get; set; }

    [Parameter]
    public EventCallback<Address> SetCurrentAddress { get; set; }

    private async Task OnAddressChange()
    {
        await SetCurrentAddress.InvokeAsync(Address);
    }
}

</code>```

答:
Not sure if this will solve your problem, but it works for me. I use FluentValidationValidator in a different way:

My editform would look like:

```<code><EditForm Model="@Customer" OnSubmit="Submit">
...
</code>```

Where "@Customer" is an instance of the model.
Then I setup my validator with a reference:

```<code><FluentValidationValidator @ref="fluentValidationValidator" />
</code>```

And define a variable to handle it:

```<code>private FluentValidationValidator fluentValidationValidator;
</code>```

Then when I want to validate:

```<code>var validationResults = fluentValidationValidator.Validate(opts => opts.IncludeAllRuleSets());
if (!validationResults) return;
// model is valid, save, etc.
</code>```

Chris lays out some of the behind the scenes stuff here: https://chrissainty.com/using-fluentvalidation-for-forms-validation-in-razor-components/

Body:
I'm trying to set up fluent validation for my application. Validation works fine for parent component. It shows messages as leave a field. However, it does not work in same way with child components. Validation messages do not appear.

It works only if I execute EditContext.Validate method.

Any ideas how to fix this? Thank you.

Models:

namespace Application.Models
{
    public class Company
    {
        ...
        public string Name { get; set; }

        public int headquartersId { get; set; }
        public Address Headquarters { get; set; }
        ...
    }
    public class Address
    {
        ...
        public string Street { get; set; }
        ...
    }
}

Validators:

using Application.Models
using FluentValidation

namespace Application.Validators
{
   public class CompanyValidator: AbstractValidator<Company>
   {
      public CompanyValidator()
      {
         RuleFor(fields => fields.Name)
         .MinimumLength(5)
         .WithMessage("---");

         RuleFor(field => field.Headquarters).SetValidator(new AddressValidator());
      }
   }
   public class AddressValidator: AbstractValidator<Address>
   {
      public AddressValidator()
      {
          RuleFor(fields => fields.Street)
          .MinimumLength(5)
          .WithMessage("---");
      }
   }
}

Parent Component:

@using Application.Models.Cards.Customers
@using Application.Models
@using FluentValidation

<EditForm EditContext="editContext" OnSubmit="Submit">

    <FluentValidationValidator />

        Business Entity Name
        <InputText name="fname" @bind-Value="Customer.Name" class="form-control"></InputText>
        <ValidationMessage For="@(() => Customer.Name)" />

        Business Entity Code
        <InputText name="fname" @bind-Value="Customer.Code" class="form-control"></InputText>
        <ValidationMessage For="@(() => Customer.Code)"></ValidationMessage>

        Business Entity VAT
        <InputText name="fname" @bind-Value="Customer.VAT" class="form-control"></InputText>
        <ValidationMessage For="@(() => Customer.VAT)"></ValidationMessage>

    **<AddressComponent Address="Customer.Headquarters" SetCurrentAddress="GetAddress"/>**

    <button type="submit" class="btn btn-primary">Save</button>

</EditForm>

@code {
    [Parameter]
    public Company Customer { get; set; }

    #nullable enable
    private EditContext? editContext;

    protected override Task OnInitializedAsync()
    {
        editContext = new EditContext(Customer);
        return base.OnInitializedAsync();
    }

    private void GetAddress(Address address)
    {
        Customer.Headquarters = address;
    }

    private void Submit()
    {
        editContext?.Validate();
    }
}

Address Component:

@using Application.Models

        House
        <input type="number" name="house" @bind-Value="Address.House" @bind-Value:event="oninput"  class="form-control" />
        <ValidationMessage For="@(() => Address.House)" />

        Street
        <input type="text" name="street" @bind="Address.Street" @bind:event ="oninput" @onkeyup="OnAddressChange" class="form-control" />
        <ValidationMessage For="@(() => Address.Street)" />

        Post Code
        <input type="text" name="postCode" @bind="Address.PostCode" @bind:event="oninput" @onkeyup="OnAddressChange" class="form-control" />
        <ValidationMessage For="@(() => Address.PostCode)" />

        County
        <input type="text" name="county" @bind="@Address.County" @bind:event="oninput" @onkeyup="OnAddressChange" class="form-control" />
        <ValidationMessage For="@(() => Address.County)" />

        Country
        <input type="text" name="country" @bind="Address.Country" @bind:event="oninput" @onkeyup="OnAddressChange" class="form-control" />
        <ValidationMessage For="@(() => Address.Country)" />

@code {

    [Parameter]
    public Address Address { get; set; }

    [Parameter]
    public EventCallback<Address> SetCurrentAddress { get; set; }

    private async Task OnAddressChange()
    {
        await SetCurrentAddress.InvokeAsync(Address);
    }
}

Body:
Not sure if this will solve your problem, but it works for me. I use FluentValidationValidator in a different way:

My editform would look like:

<EditForm Model="@Customer" OnSubmit="Submit">
...

Where "@Customer" is an instance of the model.
Then I setup my validator with a reference:

<FluentValidationValidator @ref="fluentValidationValidator" />

And define a variable to handle it:

private FluentValidationValidator fluentValidationValidator;

Then when I want to validate:

var validationResults = fluentValidationValidator.Validate(opts => opts.IncludeAllRuleSets());
if (!validationResults) return;
// model is valid, save, etc.

Chris lays out some of the behind the scenes stuff here: https://chrissainty.com/using-fluentvalidation-for-forms-validation-in-razor-components/


问:
Replace every occurrence inside function with value
I would like to replace every occurrence of @attribute2 with a value x if the occurrence is within two curly braces. In the example below the two occurrences each in e2 and e3 should be replaced but not in e1.
How would I go about this?

```<code><div class="alert">
    <h1>e1 @attribute1,@attribute2,@attribute1,@attribute2</h1>
    <h1>e2 {{ @attribute1,@attribute2,@attribute1,@attribute2 }}</h1>
    <h1>e3 {{ addone(@attribute1,@attribute2,@attribute1,@attribute2) }}</h1>
<div>
</code>```

答:
I see three possibilities:

you assume that double closing curly brackets means that there are  double opening brackets before. You check that you are between them with a lookahead that forbids all double opening curly brackets until the closing double curly brackets:

```<code>$pattern = '~@attribute2 (?= [^{}]* (?: {(?!{) [^{}]* | }(?!}) [^{}]* )* }} )~x';
$text = preg_replace($pattern, 'whatever', $text);
</code>```

This time you check that for opening brackets there are closing brackets. You look for a double curly bracket enclosed substring and use contiguity with \G to ensure you are always inside them:

```<code>$pattern = <<<'REGEX'
~
(?: (?!\A)\G | {{ (?= (?:(?! }} | {{ ).)* }} ) )
(?: (?! }} | @attribute2 ) . )* \K @attribute2
~xs
REGEX;
$text = preg_replace($pattern, 'whatever', $text);
</code>```

You search the whole bracketed part and you search inside it using preg_replace_callback in the callback function. (the most simple solution).

```<code>$text = preg_replace_callback(
    '~{{.*?}}~s',
    fn($m) => str_replace('@attribute2', 'whatever', $m[0]),
    $text
);
</code>```

Body:
I would like to replace every occurrence of @attribute2 with a value x if the occurrence is within two curly braces. In the example below the two occurrences each in e2 and e3 should be replaced but not in e1.
How would I go about this?

e1 @attribute1,@attribute2,@attribute1,@attribute2

e2 {{ @attribute1,@attribute2,@attribute1,@attribute2 }}

e3 {{ addone(@attribute1,@attribute2,@attribute1,@attribute2) }}

Body:
I see three possibilities:

you assume that double closing curly brackets means that there are  double opening brackets before. You check that you are between them with a lookahead that forbids all double opening curly brackets until the closing double curly brackets:

$pattern = '~@attribute2 (?= [^{}]* (?: {(?!{) [^{}]* | }(?!}) [^{}]* )* }} )~x';
$text = preg_replace($pattern, 'whatever', $text);

This time you check that for opening brackets there are closing brackets. You look for a double curly bracket enclosed substring and use contiguity with \G to ensure you are always inside them:

$pattern = <<<'REGEX'
~
(?: (?!\A)\G | {{ (?= (?:(?! }} | {{ ).)* }} ) )
(?: (?! }} | @attribute2 ) . )* \K @attribute2
~xs
REGEX;
$text = preg_replace($pattern, 'whatever', $text);

You search the whole bracketed part and you search inside it using preg_replace_callback in the callback function. (the most simple solution).

$text = preg_replace_callback(
    '~{{.*?}}~s',
    fn($m) => str_replace('@attribute2', 'whatever', $m[0]),
    $text
);


问:
How to turn these C# foreach loops into LINQ to Objects and return a bool?
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

```<code>private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }
</code>```

答:
```<code>return videoTracks.Any(track =>
  track.Events.Any(pumpkin =>
    pumpkin.Start == currentEvent.Start));
</code>```

Body:
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }


问:
Create a default vhost to serve http request in uwsgi
I've uwsgi 2.0.19 on Linux running with the python plugin. I serve http(s) traffic with different applications each for a specific record of my managed domain using such kind of configuration to register them to the front uwsgi servers.

```<code>subscribe2 = server=x.x.x.x:4443,key=domain.com,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
subscribe2 = server=x.x.x.x:4443,key=domain.com:443,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
subscribe2 = server=y.y.y.y:4443,key=domain.com,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
subscribe2 = server=y.y.y.y:4443,key=domain.com:443,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
</code>```

Now when I reach one of the front servers to access a not-existing host, I received such  error (the TCP connexion is closed I assume)

```<code>curl: (52) Empty reply from server
</code>```

I would like to be able to have a default/catchall key for such case, that permits to return an HTTP status 404 as I would do in Apache using the _default_ vhost. is it possible.

答:
In order to implement this, you need to define a fallback application using the http-subscription-fallback-key on the front uwsgi server

```<code>http-subscription-fallback-key=default
</code>```

default is a standard application registered on the frontal uwsgi like any other application

```<code>subscribe2 = server=x.x.x.x:4443,key=default
subscribe2 = server=x.x.x.x:4443,key=default:80
</code>```

Body:
I've uwsgi 2.0.19 on Linux running with the python plugin. I serve http(s) traffic with different applications each for a specific record of my managed domain using such kind of configuration to register them to the front uwsgi servers.

subscribe2 = server=x.x.x.x:4443,key=domain.com,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
subscribe2 = server=x.x.x.x:4443,key=domain.com:443,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
subscribe2 = server=y.y.y.y:4443,key=domain.com,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
subscribe2 = server=y.y.y.y:4443,key=domain.com:443,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt

Now when I reach one of the front servers to access a not-existing host, I received such  error (the TCP connexion is closed I assume)

curl: (52) Empty reply from server

I would like to be able to have a default/catchall key for such case, that permits to return an HTTP status 404 as I would do in Apache using the _default_ vhost. is it possible.

Body:
In order to implement this, you need to define a fallback application using the http-subscription-fallback-key on the front uwsgi server

http-subscription-fallback-key=default

default is a standard application registered on the frontal uwsgi like any other application

subscribe2 = server=x.x.x.x:4443,key=default
subscribe2 = server=x.x.x.x:4443,key=default:80


问:
How to open a a dialog within the adapter? App keeps crashing once the onClickListener is run
I have an application that's supposed to open a popup dialog when the user clicks on the item but crashes when clicked.
It started crashing as I added the (this as AppCompatActivity).supportFragmentManager line.
Heres the code for the adapter pls help!!

```<code>class CategoryAdapter(var context: Context ,private val workoutList: ArrayList<CategoryModel?>): RecyclerView.Adapter<CategoryAdapter.ViewHolder>() {
    inner class ViewHolder(private val itemBinding: WorkoutsListRowBinding): RecyclerView.ViewHolder(itemBinding.root) {

        fun bindItem(item: CategoryModel, position: Int) {
            itemBinding.workoutItem.text = item.name
            (this as AppCompatActivity).supportFragmentManager

            if (position % 2 == 0) {
                itemBinding.workoutItem.setBackgroundColor(Color.parseColor("#072227"))
                itemBinding.workoutItem.setTextColor(Color.parseColor("#FFFFFF"))
            }
            else {
                itemBinding.workoutItem.setBackgroundColor(Color.parseColor("#FFFFFF"))
                itemBinding.workoutItem.setTextColor(Color.parseColor("#000000"))
            }
            itemBinding.workoutItem.setOnClickListener{
                var dialog = CustomDialogFragment()

                dialog.show(supportFragmentManager, "customDialog")

                Snackbar.make(itemView, "${item.name}", Snackbar.LENGTH_SHORT).show()
            }

        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemBinding = WorkoutsListRowBinding
            .inflate(LayoutInflater.from(parent.context), parent, false)

        return ViewHolder(itemBinding)
    }

    override fun getItemCount() = workoutList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindItem(workoutList[position]!!, position)
    }

}
</code>```

Here's the code for the fragment

```<code>class WorkoutListFragment : Fragment() {
    private lateinit var categoryAdapter: CategoryAdapter
    private lateinit var binding: FragmentWorkoutListBinding
    var workoutList = ArrayList<CategoryModel?>()
    var workoutDAO: CategoryDAO = CategoryDaoArrayList()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentWorkoutListBinding.inflate(inflater, container, false)
        val view = binding.root

        populateList()

        categoryAdapter = CategoryAdapter(requireActivity()!!.getApplicationContext()
            ,workoutList)

        binding.workoutListView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        binding.workoutListView.adapter = categoryAdapter

        return view
    }

    fun populateList() {
        workoutList = workoutDAO.getWorkouts()!!
    }
}
</code>```

As well as the code for the custom dialog

```<code>class CustomDialogFragment: DialogFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView: View = inflater.inflate(R.layout.custom_popup_dialogue, container, false)

        return rootView
    }
}
</code>```

Error messages found in the logcat

```<code>2022-02-09 01:32:18.137 7210-7210/com.mobdeve.s11.mco2.deleon.coronel.grnd E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mobdeve.s11.mco2.deleon.coronel.grnd, PID: 7210
    java.lang.ClassCastException: com.mobdeve.s11.mco2.deleon.coronel.grnd.adapters.CategoryAdapter$ViewHolder cannot be cast to androidx.appcompat.app.AppCompatActivity
        at com.mobdeve.s11.mco2.deleon.coronel.grnd.adapters.CategoryAdapter$ViewHolder.bindItem(CategoryAdapter.kt:26)
        at com.mobdeve.s11.mco2.deleon.coronel.grnd.adapters.CategoryAdapter.onBindViewHolder(CategoryAdapter.kt:57)
        at com.mobdeve.s11.mco2.deleon.coronel.grnd.adapters.CategoryAdapter.onBindViewHolder(CategoryAdapter.kt:20)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1873)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at androidx.viewpager.widget.ViewPager.onLayout(ViewPager.java:1775)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1873)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1873)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
2022-02-09 01:32:18.137 7210-7210/com.mobdeve.s11.mco2.deleon.coronel.grnd E/AndroidRuntime:     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:727)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6338)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
        at android.view.Choreographer.doCallbacks(Choreographer.java:686)
        at android.view.Choreographer.doFrame(Choreographer.java:621)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6138)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
</code>```

答:
this as AppCompatActivity doesn't make sense. Your adapter is not an activity, so you cannot cast your adapter as an activity and this will cause a ClassCastException crash.

If you need access to your fragment manager in this class, you need to add it as a property.

```<code>class CategoryAdapter(
    val context: Context,
    private val workoutList: List<CategoryModel>,
    private val fragmentManager: FragmentManager
): RecyclerView.Adapter<CategoryAdapter.ViewHolder>() {

    //...

}
</code>```

Then you can use it in this class freely. The Fragment that instantiates this class can pass the fragment manager to the constructor, like this:

```<code>categoryAdapter = CategoryAdapter(requireActivity(), workoutList, requireActivity().supportFragmentManager)
</code>```

However, following the OOP concept of separation of concerns, I think a better strategy is to expose a callback for your Activity to use. A view adapter shouldn't have to know about specific fragments and fragment transactions, etc.

```<code>class CategoryAdapter(
    val context: Context,
    private val workoutList: List<CategoryModel>,
    private val onItemClicked: (CategoryModel)->Unit
): RecyclerView.Adapter<CategoryAdapter.ViewHolder>() {

    //...

        fun bindItem(item: CategoryModel, position: Int) {
            itemBinding.workoutItem.text = item.name

            if (position % 2 == 0) {
                itemBinding.workoutItem.setBackgroundColor(Color.parseColor("#072227"))
                itemBinding.workoutItem.setTextColor(Color.parseColor("#FFFFFF"))
            }
            else {
                itemBinding.workoutItem.setBackgroundColor(Color.parseColor("#FFFFFF"))
                itemBinding.workoutItem.setTextColor(Color.parseColor("#000000"))
            }
            itemBinding.workoutItem.setOnClickListener{
                onItemClicked(item)
            }

        }
    }

//...
</code>```

and then in your Fragment that instantiates the adapter you can pass a listener that does the fragment transaction work, such as like this:

```<code>categoryAdapter = CategoryAdapter(requireActivity(), workoutList) { clickedItem ->
    val dialog = CustomDialogFragment()
    dialog.show(requireActivity().supportFragmentManager, "customDialog")
    Snackbar.make(itemView, "${item.name}", Snackbar.LENGTH_SHORT).show()
}
</code>```

Note I changed ArrayList to List. An ArrayList implies it will be mutated, but mutating a List that's being used by an adapter will cause bugs and crashes.

Body:
I have an application that's supposed to open a popup dialog when the user clicks on the item but crashes when clicked.
It started crashing as I added the (this as AppCompatActivity).supportFragmentManager line.
Heres the code for the adapter pls help!!

class CategoryAdapter(var context: Context ,private val workoutList: ArrayList<CategoryModel?>): RecyclerView.Adapter<CategoryAdapter.ViewHolder>() {
    inner class ViewHolder(private val itemBinding: WorkoutsListRowBinding): RecyclerView.ViewHolder(itemBinding.root) {

        fun bindItem(item: CategoryModel, position: Int) {
            itemBinding.workoutItem.text = item.name
            (this as AppCompatActivity).supportFragmentManager

            if (position % 2 == 0) {
                itemBinding.workoutItem.setBackgroundColor(Color.parseColor("#072227"))
                itemBinding.workoutItem.setTextColor(Color.parseColor("#FFFFFF"))
            }
            else {
                itemBinding.workoutItem.setBackgroundColor(Color.parseColor("#FFFFFF"))
                itemBinding.workoutItem.setTextColor(Color.parseColor("#000000"))
            }
            itemBinding.workoutItem.setOnClickListener{
                var dialog = CustomDialogFragment()

                dialog.show(supportFragmentManager, "customDialog")

                Snackbar.make(itemView, "${item.name}", Snackbar.LENGTH_SHORT).show()
            }

        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemBinding = WorkoutsListRowBinding
            .inflate(LayoutInflater.from(parent.context), parent, false)

        return ViewHolder(itemBinding)
    }

    override fun getItemCount() = workoutList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindItem(workoutList[position]!!, position)
    }

}

Here's the code for the fragment

class WorkoutListFragment : Fragment() {
    private lateinit var categoryAdapter: CategoryAdapter
    private lateinit var binding: FragmentWorkoutListBinding
    var workoutList = ArrayList<CategoryModel?>()
    var workoutDAO: CategoryDAO = CategoryDaoArrayList()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentWorkoutListBinding.inflate(inflater, container, false)
        val view = binding.root

        populateList()

        categoryAdapter = CategoryAdapter(requireActivity()!!.getApplicationContext()
            ,workoutList)

        binding.workoutListView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        binding.workoutListView.adapter = categoryAdapter

        return view
    }

    fun populateList() {
        workoutList = workoutDAO.getWorkouts()!!
    }
}

As well as the code for the custom dialog

class CustomDialogFragment: DialogFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView: View = inflater.inflate(R.layout.custom_popup_dialogue, container, false)

        return rootView
    }
}

Error messages found in the logcat

2022-02-09 01:32:18.137 7210-7210/com.mobdeve.s11.mco2.deleon.coronel.grnd E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mobdeve.s11.mco2.deleon.coronel.grnd, PID: 7210
    java.lang.ClassCastException: com.mobdeve.s11.mco2.deleon.coronel.grnd.adapters.CategoryAdapter$ViewHolder cannot be cast to androidx.appcompat.app.AppCompatActivity
        at com.mobdeve.s11.mco2.deleon.coronel.grnd.adapters.CategoryAdapter$ViewHolder.bindItem(CategoryAdapter.kt:26)
        at com.mobdeve.s11.mco2.deleon.coronel.grnd.adapters.CategoryAdapter.onBindViewHolder(CategoryAdapter.kt:57)
        at com.mobdeve.s11.mco2.deleon.coronel.grnd.adapters.CategoryAdapter.onBindViewHolder(CategoryAdapter.kt:20)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1873)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at androidx.viewpager.widget.ViewPager.onLayout(ViewPager.java:1775)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1873)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1873)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
2022-02-09 01:32:18.137 7210-7210/com.mobdeve.s11.mco2.deleon.coronel.grnd E/AndroidRuntime:     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:727)
        at android.view.View.layout(View.java:17651)
        at android.view.ViewGroup.layout(ViewGroup.java:5575)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6338)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
        at android.view.Choreographer.doCallbacks(Choreographer.java:686)
        at android.view.Choreographer.doFrame(Choreographer.java:621)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6138)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)

Body:
this as AppCompatActivity doesn't make sense. Your adapter is not an activity, so you cannot cast your adapter as an activity and this will cause a ClassCastException crash.

If you need access to your fragment manager in this class, you need to add it as a property.

class CategoryAdapter(
    val context: Context,
    private val workoutList: List<CategoryModel>,
    private val fragmentManager: FragmentManager
): RecyclerView.Adapter<CategoryAdapter.ViewHolder>() {

    //...

}

Then you can use it in this class freely. The Fragment that instantiates this class can pass the fragment manager to the constructor, like this:

categoryAdapter = CategoryAdapter(requireActivity(), workoutList, requireActivity().supportFragmentManager)

However, following the OOP concept of separation of concerns, I think a better strategy is to expose a callback for your Activity to use. A view adapter shouldn't have to know about specific fragments and fragment transactions, etc.

class CategoryAdapter(
    val context: Context,
    private val workoutList: List<CategoryModel>,
    private val onItemClicked: (CategoryModel)->Unit
): RecyclerView.Adapter<CategoryAdapter.ViewHolder>() {

    //...

        fun bindItem(item: CategoryModel, position: Int) {
            itemBinding.workoutItem.text = item.name

            if (position % 2 == 0) {
                itemBinding.workoutItem.setBackgroundColor(Color.parseColor("#072227"))
                itemBinding.workoutItem.setTextColor(Color.parseColor("#FFFFFF"))
            }
            else {
                itemBinding.workoutItem.setBackgroundColor(Color.parseColor("#FFFFFF"))
                itemBinding.workoutItem.setTextColor(Color.parseColor("#000000"))
            }
            itemBinding.workoutItem.setOnClickListener{
                onItemClicked(item)
            }

        }
    }

//...

and then in your Fragment that instantiates the adapter you can pass a listener that does the fragment transaction work, such as like this:

categoryAdapter = CategoryAdapter(requireActivity(), workoutList) { clickedItem ->
    val dialog = CustomDialogFragment()
    dialog.show(requireActivity().supportFragmentManager, "customDialog")
    Snackbar.make(itemView, "${item.name}", Snackbar.LENGTH_SHORT).show()
}

Note I changed ArrayList to List. An ArrayList implies it will be mutated, but mutating a List that's being used by an adapter will cause bugs and crashes.


问:
How can I import an HTML file within my HTML file?
How can I import an HTML file within my HTML file? I will prepare header.html and footer.html files separately and every file that I want to include them I want to import them into my HTML file.,

EDIT: I see that solution based on SSI technique. I use Ubuntu and Tomcat 7.0.11. How can I enable SSI at tomcat?

答: You can include html files using frames or iframes. If you're using a server side language such as PHP or ASP you can do this without frames using includes.


问:
Retaining matrix dimensions when performing lookup via character subsetting
I would like to use a named vector lookup to map the elements of a matrix to their integer index counterparts. I currently do the lookup via character subsetting but this drops the dimensions of the matrix. Specifying drop = FALSE does not help in this instance.

How can I return an elementwise-mapped matrix using a lookup whilst retaining the matrix dimensions, as per the desired output indicated?

cd3cd28 <- structure(c(26.4, 35.9, 59.4, 73, 33.7, 13.2, 16.5, 44.1, 82.8,
                       19.8, 8.82, 12.3, 14.6, 23.1, 5.19, 18.3, 16.8, 10.2, 13.5, 9.73,
                       58.8, 8.13, 13, 1.29, 24.8, 6.61, 18.6, 14.9, 5.83, 21.1, 17,
                       32.5, 32.5, 11.8, 46.1, 414, 352, 403, 528, 305, 17, 3.37, 11.4,
                       13.7, 4.66, 44.9, 16.5, 31.9, 28.6, 25.7, 40, 61.5, 19.5, 23.1,
                       81.3),
                     .Dim = c(5L, 11L), .Dimnames = list(NULL, c("praf", "pmek", "plcg",
                                                                 "PIP2", "PIP3", "p44.42",
                                                                 "pakts473", "PKA", "PKC",
                                                                 "P38", "pjnk")))

protein_to_idx <- setNames(1:ncol(cd3cd28), colnames(cd3cd28))

proteins <- matrix(c("PKC", "PKA",
                     "PKA", "P38",
                     "PKA", "pjnk"),
                   ncol = 2)

protein_to_idx[proteins]

# Current output
# PKC  PKA  PKA  P38  PKA pjnk
#   9    8    8   10    8   11

# Desired output
matrix(protein_to_idx[proteins], ncol = 2)

#      [,1] [,2]
# [1,]    9   10
# [2,]    8    8
# [3,]    8   11
```
<p>Note: Specifying <code>drop = FALSE</code> does not work here (single dimension indexing), i.e. the following</p>
<pre class="lang-r prettyprint-override"><code>protein_to_idx[proteins, drop = FALSE]
</code>```

答:
The 'protein_to_idx' is a vector whereas 'proteins' is a matrix (which is also a vector with dim attributes).  As the input object to be subset is a named vector, it returns the values based on the matching names from the 'prtoteins' as a named vector itself.  If we want to get the matrix dimensions, use dim and do the assignment

```<code>"dim<-"(protein_to_idx[proteins], dim(proteins))
      [,1] [,2]
[1,]    9   10
[2,]    8    8
[3,]    8   11
</code>```

Or another option is to loop over the columns with apply (MARGIN = 2) which returns the matrix dimensions

```<code> apply(proteins, 2, \(x) protein_to_idx[x])
     [,1] [,2]
[1,]    9   10
[2,]    8    8
[3,]    8   11
</code>```

Usually, if we want to preserve the dimensions, we can do an assignment with [] i.e.

```<code>out <- proteins
out[] <- protein_to_idx[proteins]
</code>```

But, here the type is character for the input matrix and thus it retains it.  We may have to convert the type late

```<code>out <- type.convert(out, as.is = TRUE)
out
     [,1] [,2]
[1,]    9   10
[2,]    8    8
[3,]    8   11
</code>```

Body:
I would like to use a named vector lookup to map the elements of a matrix to their integer index counterparts. I currently do the lookup via character subsetting but this drops the dimensions of the matrix. Specifying drop = FALSE does not help in this instance.

How can I return an elementwise-mapped matrix using a lookup whilst retaining the matrix dimensions, as per the desired output indicated?

cd3cd28 <- structure(c(26.4, 35.9, 59.4, 73, 33.7, 13.2, 16.5, 44.1, 82.8,
                       19.8, 8.82, 12.3, 14.6, 23.1, 5.19, 18.3, 16.8, 10.2, 13.5, 9.73,
                       58.8, 8.13, 13, 1.29, 24.8, 6.61, 18.6, 14.9, 5.83, 21.1, 17,
                       32.5, 32.5, 11.8, 46.1, 414, 352, 403, 528, 305, 17, 3.37, 11.4,
                       13.7, 4.66, 44.9, 16.5, 31.9, 28.6, 25.7, 40, 61.5, 19.5, 23.1,
                       81.3),
                     .Dim = c(5L, 11L), .Dimnames = list(NULL, c("praf", "pmek", "plcg",
                                                                 "PIP2", "PIP3", "p44.42",
                                                                 "pakts473", "PKA", "PKC",
                                                                 "P38", "pjnk")))

protein_to_idx <- setNames(1:ncol(cd3cd28), colnames(cd3cd28))

proteins <- matrix(c("PKC", "PKA",
                     "PKA", "P38",
                     "PKA", "pjnk"),
                   ncol = 2)

protein_to_idx[proteins]

# Current output
# PKC  PKA  PKA  P38  PKA pjnk
#   9    8    8   10    8   11

# Desired output
matrix(protein_to_idx[proteins], ncol = 2)

#      [,1] [,2]
# [1,]    9   10
# [2,]    8    8
# [3,]    8   11

Note: Specifying drop = FALSE does not work here (single dimension indexing), i.e. the following

protein_to_idx[proteins, drop = FALSE]

Body:
The 'protein_to_idx' is a vector whereas 'proteins' is a matrix (which is also a vector with dim attributes).  As the input object to be subset is a named vector, it returns the values based on the matching names from the 'prtoteins' as a named vector itself.  If we want to get the matrix dimensions, use dim and do the assignment

"dim<-"(protein_to_idx[proteins], dim(proteins))
      [,1] [,2]
[1,]    9   10
[2,]    8    8
[3,]    8   11

Or another option is to loop over the columns with apply (MARGIN = 2) which returns the matrix dimensions

 apply(proteins, 2, \(x) protein_to_idx[x])
     [,1] [,2]
[1,]    9   10
[2,]    8    8
[3,]    8   11

Usually, if we want to preserve the dimensions, we can do an assignment with [] i.e.

out <- proteins
out[] <- protein_to_idx[proteins]

But, here the type is character for the input matrix and thus it retains it.  We may have to convert the type late

out <- type.convert(out, as.is = TRUE)
out
     [,1] [,2]
[1,]    9   10
[2,]    8    8
[3,]    8   11


问:
How to parse multiline response of 09 04 PID from OBD adapter in Android
I am getting raw data from OBD adapter, It is getting parsed for single line but for multiline response I am not able to parse.
I used below code to parse

```<code>    String hexaData = getResult(); // getResult is here the raw data("4904014A4D422A490402333637364904033135303049040400000000") after parsing I am getting parsed value(JMB*36761500) which is correct and only working for single line
        Log.i("CalID_hexa", hexaData);
        final String result = getResult();
        String workingData;
        if (result.contains(":")) {//CAN(ISO-15765) protocol.
            workingData = result.replaceAll(".:", "").substring(9);//9 is xxx49040701, xxx is bytes of information to follow.
            Matcher m = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE).matcher(convertHexToString(workingData));
            if(m.find()) workingData = result.replaceAll("0:49", "").replaceAll(".:", "");
        } else {//ISO9141-2, KWP2000 Fast and KWP2000 5Kbps (ISO15031) protocols.
            workingData = result.replaceAll("49040.", "");
        }
         calId = convertHexToString(workingData).replaceAll("[\u0000-\u001f]", "");
        L.stringStringHashMap.put("CAL_ID",calId);

public String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);
        }
        return sb.toString();
    }
</code>```

How to parse multiline response like  below response on PID 09 04 from OBD Adapter:

```<code>18 DA F1 11 10 13 49 04 01 33 37 38
18 DA F1 1D 10 13 49 04 01 33 37 38
18 DA F1 11 21 30 35 2D 52 59 45 2D
18 DA F1 11 22 41 37 34 30 00 00 55
18 DA F1 1D 21 30 36 2D 52 59 45 2D
18 DA F1 1D 22 41 37 37 30 00 00 55
</code>```

How can I parse the above?

答: If you want to parse multiple line responses as single line responses then you can first form the array from the multiple line response separating the lines by character \n. After forming the array of responses, you can join the strings in one single line.

Body:
I am getting raw data from OBD adapter, It is getting parsed for single line but for multiline response I am not able to parse.
I used below code to parse

    String hexaData = getResult(); // getResult is here the raw data("4904014A4D422A490402333637364904033135303049040400000000") after parsing I am getting parsed value(JMB*36761500) which is correct and only working for single line
        Log.i("CalID_hexa", hexaData);
        final String result = getResult();
        String workingData;
        if (result.contains(":")) {//CAN(ISO-15765) protocol.
            workingData = result.replaceAll(".:", "").substring(9);//9 is xxx49040701, xxx is bytes of information to follow.
            Matcher m = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE).matcher(convertHexToString(workingData));
            if(m.find()) workingData = result.replaceAll("0:49", "").replaceAll(".:", "");
        } else {//ISO9141-2, KWP2000 Fast and KWP2000 5Kbps (ISO15031) protocols.
            workingData = result.replaceAll("49040.", "");
        }
         calId = convertHexToString(workingData).replaceAll("[\u0000-\u001f]", "");
        L.stringStringHashMap.put("CAL_ID",calId);

public String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);
        }
        return sb.toString();
    }

How to parse multiline response like  below response on PID 09 04 from OBD Adapter:

18 DA F1 11 10 13 49 04 01 33 37 38
18 DA F1 1D 10 13 49 04 01 33 37 38
18 DA F1 11 21 30 35 2D 52 59 45 2D
18 DA F1 11 22 41 37 34 30 00 00 55
18 DA F1 1D 21 30 36 2D 52 59 45 2D
18 DA F1 1D 22 41 37 37 30 00 00 55

How can I parse the above?


问:
Grails Audit Logging: unable to resolve class grails.plugins.orm.auditable.AuditEventType in application.groovy
grails compile is failing to resolve grails.plugins.orm.auditable.AuditEventType in application.groovy.

I have included the plugin in build.gradle

build.gradle

```<code>dependencies {
    // ... other dependencies ...
    compile 'org.grails.plugins:audit-logging:4.0.3'
    // ... other dependencies ...
}
</code>```

application.groovy

```<code>import grails.plugins.orm.auditable.AuditEventType

// ... other config ...

grails.plugin.auditLog.auditDomainClassName = "us.cloudcard.api.AuditLogEvent"
grails.plugin.auditLog.logFullClassName = false
grails.plugin.auditLog.defaultActor = "foo"
grails.plugin.auditLog.verbose = false
grails.plugin.auditLog.verboseEvents = [AuditEventType.UPDATE]
</code>```

grails compile

```<code>user@host dir % grails compile
| Error Error occurred running Grails CLI: startup failed:
script1644337921704582166752.groovy: 1: unable to resolve class grails.plugins.orm.auditable.AuditEventType
 @ line 1, column 1.
   import grails.plugins.orm.auditable.AuditEventType
   ^

1 error
</code>```

答:
I found a workaround.  If you remove the import and instead put the fully qualified class name in the config item, it works fine. I don't really like this because I don't understand why it works when the import doesn't.

application.groovy

```<code>// don't import AuditEventType

grails.plugin.auditLog.auditDomainClassName = "us.cloudcard.api.AuditLogEvent"
grails.plugin.auditLog.logFullClassName = false
grails.plugin.auditLog.defaultActor = "foo"
grails.plugin.auditLog.verbose = false
grails.plugin.auditLog.verboseEvents = [grails.plugins.orm.auditable.AuditEventType.UPDATE]

</code>```

Body:
grails compile is failing to resolve grails.plugins.orm.auditable.AuditEventType in application.groovy.

I have included the plugin in build.gradle

build.gradle

dependencies {
    // ... other dependencies ...
    compile 'org.grails.plugins:audit-logging:4.0.3'
    // ... other dependencies ...
}

application.groovy

import grails.plugins.orm.auditable.AuditEventType

// ... other config ...

grails.plugin.auditLog.auditDomainClassName = "us.cloudcard.api.AuditLogEvent"
grails.plugin.auditLog.logFullClassName = false
grails.plugin.auditLog.defaultActor = "foo"
grails.plugin.auditLog.verbose = false
grails.plugin.auditLog.verboseEvents = [AuditEventType.UPDATE]

grails compile

user@host dir % grails compile
| Error Error occurred running Grails CLI: startup failed:
script1644337921704582166752.groovy: 1: unable to resolve class grails.plugins.orm.auditable.AuditEventType
 @ line 1, column 1.
   import grails.plugins.orm.auditable.AuditEventType
   ^

1 error

Body:
I found a workaround.  If you remove the import and instead put the fully qualified class name in the config item, it works fine. I don't really like this because I don't understand why it works when the import doesn't.

application.groovy

// don't import AuditEventType

grails.plugin.auditLog.auditDomainClassName = "us.cloudcard.api.AuditLogEvent"
grails.plugin.auditLog.logFullClassName = false
grails.plugin.auditLog.defaultActor = "foo"
grails.plugin.auditLog.verbose = false
grails.plugin.auditLog.verboseEvents = [grails.plugins.orm.auditable.AuditEventType.UPDATE]


问:
Web Scraping: How to click a specific href link in selenium python?
I wanted to automate a web page using webdriver(Python) wherein the script will click on the href link directly in order to navigate to other page. Couple of details in the specific tag:</p>
```<code><span class = "xyz", ui-sref ="abc", href= "/letters/letters_number/">
"hdf"
<i class = 'icons'>letters</i>
</span>
</code>```

答:
To click() on a the element with the href attribute you need 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, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span[href=/letters/letters_number/] i.icons"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@href='/letters/letters_number/']//i[@class='icons']"))).click()
</code>```

Note: You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
I wanted to automate a web page using webdriver(Python) wherein the script will click on the href link directly in order to navigate to other page. Couple of details in the specific tag:

"hdf"
letters

Body:
To click() on a the element with the href attribute you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span[href=/letters/letters_number/] i.icons"))).click()

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@href='/letters/letters_number/']//i[@class='icons']"))).click()

Note: You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
Running a Python from Excel Macro
I have seen a couple posts instructing people on how to run a Python script through an Excel macro. I'm still having trouble with it - all I'm looking to do for the moment is see how I can get a Python script titled main.py to print 40 when I run an Excel macro. I've posted a couple filepaths below, with ellipses to replace the names of certain folders.

For background, my python.exe file is located:

```<code>R:\TRADING\...\Anders\python3.9 - Copy\3.9.7\python.exe
</code>```

And the python script that I want to run is located:

```<code>R:\TRADING\...\Anders\Python\main.py
</code>```

When I run print(sys.executable) on Python, it produces the location //Naeast.../.../.../.../TRADING/.../Anders/Python/main.py where //Naeast.../.../.../.../ is the location of the R: drive.

Per the response (with about 16 upvotes) to this post here, I implemented and ran this code below from my test Excel file to run main.py but it failed:

```<code>Sub RunPython1()

Dim objShell As Object
Dim PythonExe, PythonScript As String

    Set objShell = VBA.CreateObject("Wscript.Shell")

    PythonExe = """R:\TRADING\...\Anders\python3.9 - Copy\3.9.7\python.exe"""
    PythonScript = "R:\TRADING\...\Anders\Python\main.py"

    objShell.Run PythonExe & PythonScript

End Sub
</code>```

I was careful to include triple quotes for PythonExe.

When I try replicating the answer to the question here, I get an error saying that the Method 'Run' of object 'IwshShell3' failed.

答:
My python code was originally geared to edit an Excel spreadsheet directly. The use case in general was that whenever I received an email with a certain subject line - let's say blah for example,  I wanted a python file main.py to automatically execute and edit an excel file main.xlsx accordingly.

Something to note is that main.xlsx cannot be open at the time the email arrives. If anyone has any guidance on how to have main.xlsx be modified on the chance that the email arrives while it is open, I'd greatly appreciate it.

The below code solved my issue exactly:

```<code>Private Sub inboxItems_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Dim MessageInfo
Dim Result
If TypeName(Item) = "MailItem" Then
    Debug.Print "Arrived"
    If Item.Subject = "Blah" Then
        Const PyExe = """C:\...\...\...\...\...\python3.9\latest\python.exe"""
        Const PyScript = "R:\...\...\Anders\Python\main.py"

        Dim objShell As Object, cmd As String
        Set objShell = CreateObject("Wscript.Shell")

        cmd = PyExe & " " & PyScript
        Debug.Print cmd

        objShell.Run cmd
        objShell.exec cmd

        MsgBox objShell.exec(cmd).StdOut.ReadAll
    End If
End If
ExitNewItem:
    Exit Sub
ErrorHandler:
    MsgBox Err.Number & " - " & Err.Description
    Resume ExitNewItem
End Sub
</code>```

Title: Running a Python from Excel Macro

Body:
I have seen a couple posts instructing people on how to run a Python script through an Excel macro. I'm still having trouble with it - all I'm looking to do for the moment is see how I can get a Python script titled main.py to print 40 when I run an Excel macro. I've posted a couple filepaths below, with ellipses to replace the names of certain folders.

For background, my python.exe file is located:

R:\TRADING\...\Anders\python3.9 - Copy\3.9.7\python.exe

And the python script that I want to run is located:

R:\TRADING\...\Anders\Python\main.py

When I run print(sys.executable) on Python, it produces the location //Naeast.../.../.../.../TRADING/.../Anders/Python/main.py where //Naeast.../.../.../.../ is the location of the R: drive.

Per the response (with about 16 upvotes) to this post here, I implemented and ran this code below from my test Excel file to run main.py but it failed:

Sub RunPython1()

Dim objShell As Object
Dim PythonExe, PythonScript As String

    Set objShell = VBA.CreateObject("Wscript.Shell")

    PythonExe = """R:\TRADING\...\Anders\python3.9 - Copy\3.9.7\python.exe"""
    PythonScript = "R:\TRADING\...\Anders\Python\main.py"

    objShell.Run PythonExe & PythonScript

End Sub

I was careful to include triple quotes for PythonExe.

When I try replicating the answer to the question here, I get an error saying that the Method 'Run' of object 'IwshShell3' failed.

Body:
My python code was originally geared to edit an Excel spreadsheet directly. The use case in general was that whenever I received an email with a certain subject line - let's say blah for example,  I wanted a python file main.py to automatically execute and edit an excel file main.xlsx accordingly.

Something to note is that main.xlsx cannot be open at the time the email arrives. If anyone has any guidance on how to have main.xlsx be modified on the chance that the email arrives while it is open, I'd greatly appreciate it.

The below code solved my issue exactly:

Private Sub inboxItems_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Dim MessageInfo
Dim Result
If TypeName(Item) = "MailItem" Then
    Debug.Print "Arrived"
    If Item.Subject = "Blah" Then
        Const PyExe = """C:\...\...\...\...\...\python3.9\latest\python.exe"""
        Const PyScript = "R:\...\...\Anders\Python\main.py"

        Dim objShell As Object, cmd As String
        Set objShell = CreateObject("Wscript.Shell")

        cmd = PyExe & " " & PyScript
        Debug.Print cmd

        objShell.Run cmd
        objShell.exec cmd

        MsgBox objShell.exec(cmd).StdOut.ReadAll
    End If
End If
ExitNewItem:
    Exit Sub
ErrorHandler:
    MsgBox Err.Number & " - " & Err.Description
    Resume ExitNewItem
End Sub


问:
How to visualize a time series in react with hooks
I went through different tutorials on how to show a simple time series on React. Most of them don't use hook, so I tried to adapt the code. I got stuck when tried to retrieve data with Axios from an open API. The error I got are ERROR in ./src/App.js Module build failed (from ./node_modules/babel-loader/lib/index.js) and ERROR in src/App.js Line 27:  Parsing error: Unexpected token, expected "," (27:0)

I am encountered these errors even before to try to show something. It seems something linked with the axios.get or there is something wrong with my useEffect hook.
Could you please help me with this?
Many thanks

```<code>import React , { useState, useEffect} from 'react';
import logo from './logo.svg';
import axios from 'axios';
import './App.css';

const  App =()=> {

  useEffect(() => {
    let x = [];
    let y = [];

    axios.get('https://data.cityofnewyork.us/resource/rc75-m7u3.json').then(response=>{
      console.log('response',response)
      response.map(each => {
      x.push(each.date_of_interest)
      y.push(each.case_count)

      .catch((error) => {console.log(error)})
        }, [])

    return (
      <div>Hello </div>
    )}

export default App;
</code>```

答:
loop on response.data:

```<code>import React, { useEffect } from "react";
import axios from "axios";

export default function App() {
  useEffect(() => {
    let x = [];
    let y = [];

    axios
      .get("https://data.cityofnewyork.us/resource/rc75-m7u3.json")
      .then((response) => {
        response.data.forEach((each) => {
          x.push(each.date_of_interest);
          y.push(each.case_count);
        });
      })
      .catch((err) => console.log(err));
  }, []);

  return <div>Hello </div>;
}
</code>```

Demo

Body:
I went through different tutorials on how to show a simple time series on React. Most of them don't use hook, so I tried to adapt the code. I got stuck when tried to retrieve data with Axios from an open API. The error I got are ERROR in ./src/App.js Module build failed (from ./node_modules/babel-loader/lib/index.js) and ERROR in src/App.js Line 27:  Parsing error: Unexpected token, expected "," (27:0)

I am encountered these errors even before to try to show something. It seems something linked with the axios.get or there is something wrong with my useEffect hook.
Could you please help me with this?
Many thanks

import React , { useState, useEffect} from 'react';
import logo from './logo.svg';
import axios from 'axios';
import './App.css';

const  App =()=> {

  useEffect(() => {
    let x = [];
    let y = [];

    axios.get('https://data.cityofnewyork.us/resource/rc75-m7u3.json').then(response=>{
      console.log('response',response)
      response.map(each => {
      x.push(each.date_of_interest)
      y.push(each.case_count)

      .catch((error) => {console.log(error)})
        }, [])

    return (

Hello

    )}

export default App;

Body:
loop on response.data:

import React, { useEffect } from "react";
import axios from "axios";

export default function App() {
  useEffect(() => {
    let x = [];
    let y = [];

    axios
      .get("https://data.cityofnewyork.us/resource/rc75-m7u3.json")
      .then((response) => {
        response.data.forEach((each) => {
          x.push(each.date_of_interest);
          y.push(each.case_count);
        });
      })
      .catch((err) => console.log(err));
  }, []);

  return <div>Hello </div>;
}

Demo


问:
TypeError: Mean() missing 1 required positional argument: 'data'
I'm trying to program a basic mean calculator using classes. However, I'm getting the error

```<code>TypeError: Mean() missing 1 required positional argument: 'data'
</code>```

I have two files: one which contains the class with the mean function and then one which calls it, and that is when I'm getting the error. My code is:

```<code>class Statistics:
    def __init__(self,mean_x,mean_y,var,covar):
        self.mean_x=mean_x
        self.mean_y=mean_y
        self.var=var
        self.covar=covar

    def Mean(self,data):
        return sum(data)/float(len(data))
</code>```

And the code which throws the error is:

```<code>from Statistics import Statistics
X=(0,1,3,5)
mean_x=Statistics.Mean(X)
print(mean_x)
</code>```

答:
Mean is an instance method, so you need to call it on an instance (which will become the self argument for the method invocation).

```<code>statistics = Statistics(None, None, None, None)
mean_x = statistics.Mean((0, 1, 3, 5))
</code>```

Since the parameters on Statistics.__init__ aren't used I'd suggest removing them (or just removing the __init__ altogether):

```<code>class Statistics:

    def mean(self, data):
        return sum(data)/float(len(data))
</code>```
```<code>from Statistics import Statistics
X = (0,1,3,5)
statistics = Statistics()
mean_x = statistics.mean(X)
print(mean_x)
</code>```

Note that Python comes with a statistics module that has a mean function built in:

```<code>import statistics

X = (0,1,3,5)
mean_x = statistics.mean(X)
print(mean_x)
</code>```

Body:
I'm trying to program a basic mean calculator using classes. However, I'm getting the error

TypeError: Mean() missing 1 required positional argument: 'data'

I have two files: one which contains the class with the mean function and then one which calls it, and that is when I'm getting the error. My code is:

class Statistics:
    def __init__(self,mean_x,mean_y,var,covar):
        self.mean_x=mean_x
        self.mean_y=mean_y
        self.var=var
        self.covar=covar

    def Mean(self,data):
        return sum(data)/float(len(data))

And the code which throws the error is:

from Statistics import Statistics
X=(0,1,3,5)
mean_x=Statistics.Mean(X)
print(mean_x)

Body:
Mean is an instance method, so you need to call it on an instance (which will become the self argument for the method invocation).

statistics = Statistics(None, None, None, None)
mean_x = statistics.Mean((0, 1, 3, 5))

Since the parameters on Statistics.__init__ aren't used I'd suggest removing them (or just removing the __init__ altogether):

class Statistics:

    def mean(self, data):
        return sum(data)/float(len(data))

from Statistics import Statistics
X = (0,1,3,5)
statistics = Statistics()
mean_x = statistics.mean(X)
print(mean_x)

Note that Python comes with a statistics module that has a mean function built in:

import statistics

X = (0,1,3,5)
mean_x = statistics.mean(X)
print(mean_x)