问:
MatSort is not sorting the but data got populated
Data is getting displayed but sort is not working

If I use sample example it works but not with my data... Here is my code...

HTML:

```<code><table class="query-table"  #table mat-table [dataSource]="dataSource"  matSort>

  <!-- Start Column -->
  <ng-container matColumnDef="start">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Starts </th>
    <td mat-cell *matCellDef="let overtime">
      <span *ngIf="!this.globalOvertimeVarService.summaryState" class="status_circle" [ngClass]="{'status-green': overtime.type.approvalStatus == 'Approved'}"></span>
      {{overtime.startDate | date:'d/M/yyyy'}} ({{overtime.startDate | date:'hh:mm'}})</td>
  </ng-container>

  <!-- Date Column -->
  <ng-container matColumnDef="end">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Ends </th>
    <td mat-cell *matCellDef="let overtime"> {{overtime.endDate | date:'d/M/yyyy'}} ({{overtime.endDate | date:'hh:mm'}}) </td>
  </ng-container>

  <!-- Time Column -->
  <ng-container matColumnDef="time">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Time </th>
    <td mat-cell *matCellDef="let overtime"> {{overtime.totalTime | hoursMinutes}}</td>
  </ng-container>

  <!-- Type Column -->
  <ng-container matColumnDef="type" *ngIf="!this.globalOvertimeVarService.summaryState">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Type </th>
    <td mat-cell *matCellDef="let overtime"> {{overtime.type.name}} </td>
  </ng-container>

  <!-- Edit/View Column -->
  <ng-container matColumnDef="view">
    <th mat-header-cell *matHeaderCellDef>  </th>
    <td mat-cell *matCellDef="let overtime">
      <i class="material-icons edit" (click)="editOvertime(overtime);">edit</i>
      <i class="material-icons view" (click)="viewOvertime(overtime.id);">visibility</i>
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="globalOvertimeVarService.summaryState ? queryColumns : detailColumns; sticky: true"></tr>
  <tr mat-row *matRowDef="let row; columns: (globalOvertimeVarService.summaryState ? queryColumns : detailColumns);"  [ngClass]="{'highlight': globalOvertimeVarService.selectedOvertimeId  == row.id}" [class.hidden]="!globalOvertimeVarService.summaryState ? (row.type.hideSelected || row.type.hideBasedOnDates) : (row.approvalStatus !== 'inQuery')"></tr>
</table>
</code>```

Component:

```<code>    ...
    detailColumns =['start', 'end', 'time', 'type', 'view'];
    queryColumns =['start', 'end', 'time', 'view'];
    dataSource = new MatTableDataSource<UserModel>();
    @ViewChild(MatSort, { static: true }) sort: MatSort;
    ...
this.userService.getUserList()
            .subscribe(
                success => {
                  this.globalOvertimeVarService.overtimeList = success;
                  this.dataSource = new MatTableDataSource(this.globalOvertimeVarService.overtimeList);
                  this.dataSource.sort = this.sort;
                }
            );
</code>```

Model is like:

```<code>id: 2
startDate: "2020-01-14"
endDate: "2020-01-14"
totalTime: 120
totalTimeTimeUnit: "minute"
dateRequested: "0001-01-01"
notes: "test"
dateApproved: null
userId: "9-XXX"
ownerId: 1
approvalStatus: "inQuery"
type: {id: 1, name: "test type 1", startTime: "15:00:00", endTime: "17:00:00", rate: 2,…}
deleted: false
</code>```

答:
Your matColumnDef definition column name must match model property name. If they are different, you need to set mat-sort-header value. For example:

```<code><!-- Start Column -->
<ng-container matColumnDef="start">
  <th mat-header-cell *matHeaderCellDef mat-sort-header="startDate"> Starts </th>
</code>```

mat-sort-header="startDate" tells MatTableDataSource to sort by startDate property of your rows.

For nested objects, you must implement SortingDataAccessor:

```<code>this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (item, property) => {
  switch(property) {
    case 'type.name': return item.type.name;
    default: return item[property];
  }
};
</code>```

Body:
Data is getting displayed but sort is not working

If I use sample example it works but not with my data... Here is my code...

HTML:

  <ng-container matColumnDef="start">
     Starts

      {{overtime.startDate | date:'d/M/yyyy'}} ({{overtime.startDate | date:'hh:mm'}})
  </ng-container>

  <ng-container matColumnDef="end">
     Ends
     {{overtime.endDate | date:'d/M/yyyy'}} ({{overtime.endDate | date:'hh:mm'}})
  </ng-container>

  <ng-container matColumnDef="time">
     Time
     {{overtime.totalTime | hoursMinutes}}
  </ng-container>

  <ng-container matColumnDef="type" *ngIf="!this.globalOvertimeVarService.summaryState">
     Type
     {{overtime.type.name}}
  </ng-container>

  <ng-container matColumnDef="view">

      edit
      visibility

  </ng-container>

Component:

    ...
    detailColumns =['start', 'end', 'time', 'type', 'view'];
    queryColumns =['start', 'end', 'time', 'view'];
    dataSource = new MatTableDataSource<UserModel>();
    @ViewChild(MatSort, { static: true }) sort: MatSort;
    ...
this.userService.getUserList()
            .subscribe(
                success => {
                  this.globalOvertimeVarService.overtimeList = success;
                  this.dataSource = new MatTableDataSource(this.globalOvertimeVarService.overtimeList);
                  this.dataSource.sort = this.sort;
                }
            );

Model is like:

id: 2
startDate: "2020-01-14"
endDate: "2020-01-14"
totalTime: 120
totalTimeTimeUnit: "minute"
dateRequested: "0001-01-01"
notes: "test"
dateApproved: null
userId: "9-XXX"
ownerId: 1
approvalStatus: "inQuery"
type: {id: 1, name: "test type 1", startTime: "15:00:00", endTime: "17:00:00", rate: 2,…}
deleted: false

Body:
Your matColumnDef definition column name must match model property name. If they are different, you need to set mat-sort-header value. For example:

<!-- Start Column -->
<ng-container matColumnDef="start">
  <th mat-header-cell *matHeaderCellDef mat-sort-header="startDate"> Starts </th>

mat-sort-header="startDate" tells MatTableDataSource to sort by startDate property of your rows.

For nested objects, you must implement SortingDataAccessor:

this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (item, property) => {
  switch(property) {
    case 'type.name': return item.type.name;
    default: return item[property];
  }
};


来源: stackexchange

问:
MERGE command results in gaps in sequence numbers
I was trying to make use of the MERGE command for populating dimensions in Snowflake. To implement surrogate keys, I created a column defaulted to a sequence number that auto increments whenever a new row gets inserted. I tried a similar approach in other data warehousing platforms and it never caused any issues. However, I noticed that whenever I use the MERGE command in Snowflake, the sequence number increments for every single row processed by the MERGE command, regardless of whether it results in an UPDATE or INSERT operation.

The following is a simple example of what I'm referring to:

```<code>-- Sequence
CREATE OR REPLACE SEQUENCE seq1 START=1 INCREMENT=1;

-- Source table
CREATE OR REPLACE TABLE source_table
(
row_key int,
row_value string
);

-- Target table: Column ID uses the sequence
CREATE OR REPLACE TABLE target_table
(
id int DEFAULT seq1.nextval,
row_key int,
row_value string
);

-- Initial data
INSERT INTO source_table VALUES
(1,'One'),
(2,'Two'),
(3,'Three');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);
</code>```

After running these commands, the output table would contain these rows:

ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

Now, let's insert a new row and run the same merge command again:

```<code>INSERT INTO source_table VALUES
(4,'Four');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);
</code>```

This time, the output of the table looks like this:
ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

7,4,Four

If I insert another row, the next MERGE command will insert the new row with its ID set to 12 and the same goes on and on. It looks as if the MERGE command increments the sequence number for each row it reads from the source table, even if they don't end up being inserted into the target table at all.

Is this intentional behaviour? I tried the IDENTITY functionality instead of the sequence and it didn't change the output.

The workaround I came with was to replace the MERGE command with multiple UPDATE and INSERT statements instead, but I'm still keen to know the reason behind this behaviour.

答: This is a known issue which the Snowflake development team is working on it. As you mentioned, the workaround is to replace the MERGE command with multiple UPDATE and INSERT statements.</p>

ContentLicense: CC BY-SA 4.0

Body:
I was trying to make use of the MERGE command for populating dimensions in Snowflake. To implement surrogate keys, I created a column defaulted to a sequence number that auto increments whenever a new row gets inserted. I tried a similar approach in other data warehousing platforms and it never caused any issues. However, I noticed that whenever I use the MERGE command in Snowflake, the sequence number increments for every single row processed by the MERGE command, regardless of whether it results in an UPDATE or INSERT operation.

The following is a simple example of what I'm referring to:

-- Sequence
CREATE OR REPLACE SEQUENCE seq1 START=1 INCREMENT=1;

-- Source table
CREATE OR REPLACE TABLE source_table
(
row_key int,
row_value string
);

-- Target table: Column ID uses the sequence
CREATE OR REPLACE TABLE target_table
(
id int DEFAULT seq1.nextval,
row_key int,
row_value string
);

-- Initial data
INSERT INTO source_table VALUES
(1,'One'),
(2,'Two'),
(3,'Three');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);

After running these commands, the output table would contain these rows:

ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

Now, let's insert a new row and run the same merge command again:

INSERT INTO source_table VALUES
(4,'Four');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);

This time, the output of the table looks like this:
ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

7,4,Four

If I insert another row, the next MERGE command will insert the new row with its ID set to 12 and the same goes on and on. It looks as if the MERGE command increments the sequence number for each row it reads from the source table, even if they don't end up being inserted into the target table at all.

Is this intentional behaviour? I tried the IDENTITY functionality instead of the sequence and it didn't change the output.

The workaround I came with was to replace the MERGE command with multiple UPDATE and INSERT statements instead, but I'm still keen to know the reason behind this behaviour.


问:
Is there any C++ function to sort a Map?
I want to know that how can I sort an ordered_map in C++ on the basis of values. Is there any function to do it?

答:
This answer covers the case that you are referring to values inside the map itself.

First off, the container you want is std::map. There is no ordered_map in the standard library, only map or unordered_map.

You can supply map with your own comparer so that it sorts it like you want. For example:

```<code>struct MyOrder
{
    constexpr bool operator()(MyType a, MyType b) const
    {
        // return true, so that a < b accodring to your definition
    }
};
</code>```

and use it like

```<code>std::map<MyType, MyOrder> myMap;
</code>```

Body:
This answer covers the case that you are referring to values inside the map itself.

First off, the container you want is std::map. There is no ordered_map in the standard library, only map or unordered_map.

You can supply map with your own comparer so that it sorts it like you want. For example:

struct MyOrder
{
    constexpr bool operator()(MyType a, MyType b) const
    {
        // return true, so that a < b accodring to your definition
    }
};

and use it like

std::map<MyType, MyOrder> myMap;


问:
How can I pass more than one enum to a method that receives only one?
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

```<code>RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline
</code>```

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?

答:
See http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx for details.

Don't use &, use | (you want to do a bit-wise Boolean OR).

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?


问:
WCF REST is failing to deserialize class that implements IXMLSerializable
I have WCF project that has been converted to rest.
I am having hard time to receiving the right value for a property which its type implements IXMLSerializable

```<code>[Serializable]
[DataContract]
[XmlType(TypeName = "Dimension")]
[XmlInclude(typeof(SharedDimension))]
public class Dimension
{
    [DataMember]
    public string Id {get;set}

    //[DataMember]
    [XmlElement(ElementName = "Members")]
    public Members Members { get; set; }

    // another properties of Dimension class
}

[Serializable]
 //[XmlSchemaProvider("GetSchema")]
[XmlSerializerFormat]
[XmlRoot]
 public class Members: IXMLSerializable
 public List<Member> Items
 {
    get
    {
    //code that use the IXMLSerializable goes here
    }
    set
    {
    //code that use the IXMLSerializable goes here
    }
}

// another properties of Members class

public System.Xml.Schema.XmlSchema GetSchema()
{
    return null;
}

[Serializable]
[XmlType(TypeName = "Member")]
public class Member : Equatable<Member>, ICodrObject
{
    // properties of Member class
}

public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/ProcessDimensions")]
    bool ProcessDimensions(int productId, List<Dimension> dimensions);

    // another end points
}
public class Service implements IService
{
    bool ProcessDimensions(int productId, List<Dimension> dimensions){
    //  code goes here
}
</code>```

Calling this endd point from post man, productId,Dimension.Id has the right value but Dimension.Members is NULL

```<code>{
    "productId": 000000,
    "dimensions": [{
        "Id": "D1",
        "Members": {
            "ID": "M1.1",
            "Items": [{
                "Id": 1
            }]
        }
    },
    {
        "Id": "D2",
        "Members": {
            "ID": "M2.1",
            "Items": [{
                "Id": 1
            }]
        }
    }]
}
</code>```

I am still using .NET Framework 4.6.1

答:
There is nothing wrong with your JSON data format. Uncomment out the [DataMember]statement will solve the issue.

```<code>//[DataMember]
[XmlElement(ElementName = "Members")]
public Members Members { get; set; }
</code>```

Although you say you are using XmlSerializer, you are actually using the DataContractSerializer throughout the service.
DataContractSerializer is the default serializer in WCF, which includes the class which is without decorating with [DataContract]. If we want to manually switch to the XmlSerializer, we are supposed to use [XmlSerializerFormat] to decorate the service contract.

For details,

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/using-the-xmlserializer-class

Feel free to let me know if there is anything I can help with.

Updated.

Please remove relevant XMlserializer attributes, it might interfere with the DataContractSerializer. Please consider the below definition.

```<code>    [DataContract]
    public class Dimension
    {
        [DataMember]
        public string Id { get; set; }
        [DataMember]
        public Members Members { get; set; }

    }

    //DataContractSerializer is the serializer by default.
    public class Members
    {
        public string ID { get; set; }
        public List<Member> Items { get; set; }
    }
    public class Member
    {
        public int Id { get; set; }
}
</code>```

Body:
I have WCF project that has been converted to rest.
I am having hard time to receiving the right value for a property which its type implements IXMLSerializable

[Serializable]
[DataContract]
[XmlType(TypeName = "Dimension")]
[XmlInclude(typeof(SharedDimension))]
public class Dimension
{
    [DataMember]
    public string Id {get;set}

    //[DataMember]
    [XmlElement(ElementName = "Members")]
    public Members Members { get; set; }

    // another properties of Dimension class
}

[Serializable]
 //[XmlSchemaProvider("GetSchema")]
[XmlSerializerFormat]
[XmlRoot]
 public class Members: IXMLSerializable
 public List<Member> Items
 {
    get
    {
    //code that use the IXMLSerializable goes here
    }
    set
    {
    //code that use the IXMLSerializable goes here
    }
}

// another properties of Members class

public System.Xml.Schema.XmlSchema GetSchema()
{
    return null;
}

[Serializable]
[XmlType(TypeName = "Member")]
public class Member : Equatable<Member>, ICodrObject
{
    // properties of Member class
}

public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/ProcessDimensions")]
    bool ProcessDimensions(int productId, List<Dimension> dimensions);

    // another end points
}
public class Service implements IService
{
    bool ProcessDimensions(int productId, List<Dimension> dimensions){
    //  code goes here
}

Calling this endd point from post man, productId,Dimension.Id has the right value but Dimension.Members is NULL

{
    "productId": 000000,
    "dimensions": [{
        "Id": "D1",
        "Members": {
            "ID": "M1.1",
            "Items": [{
                "Id": 1
            }]
        }
    },
    {
        "Id": "D2",
        "Members": {
            "ID": "M2.1",
            "Items": [{
                "Id": 1
            }]
        }
    }]
}

I am still using .NET Framework 4.6.1

Body:
There is nothing wrong with your JSON data format. Uncomment out the [DataMember]statement will solve the issue.

//[DataMember]
[XmlElement(ElementName = "Members")]
public Members Members { get; set; }

Although you say you are using XmlSerializer, you are actually using the DataContractSerializer throughout the service.
DataContractSerializer is the default serializer in WCF, which includes the class which is without decorating with [DataContract]. If we want to manually switch to the XmlSerializer, we are supposed to use [XmlSerializerFormat] to decorate the service contract.

For details,

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/using-the-xmlserializer-class

Feel free to let me know if there is anything I can help with.

Updated.

Please remove relevant XMlserializer attributes, it might interfere with the DataContractSerializer. Please consider the below definition.

    [DataContract]
    public class Dimension
    {
        [DataMember]
        public string Id { get; set; }
        [DataMember]
        public Members Members { get; set; }

    }

    //DataContractSerializer is the serializer by default.
    public class Members
    {
        public string ID { get; set; }
        public List<Member> Items { get; set; }
    }
    public class Member
    {
        public int Id { get; set; }
}


问:
How to generate bounding box data from heatmap data of an image?
I have a group of images and some separate heatmap data which (imperfectly) explains where subject of the image is. The heatmap data is in a numpy array with shape (224,224,3). I would like to generate bounding box data from this heatmap data.

The heatmaps are not always perfect, So I guess I'm wondering if anyone can think of an intelligent way to do this.

Here are some examples of what happens when I apply the heatmap data to the image:

I found a solution to this in matlab, but I have no idea how to read this code! I am a python programmer, unfortunately.
https://github.com/metalbubble/CAM/tree/master/bboxgenerator

Anyone have any ideas about how to approach something like this?

答:
I'm attempting a similar method for automating the creation of bounding boxes (since, lets face it: creating boxes manually takes along time)

this other stackpost covers a similar idea:
EDIT: (i originally had put a link to the current stack post  - but here is the stack post i was referring to)
Generating bounding boxes from heatmap data

the problem at hand that i recognize is that heatmaps can be fragmented and a bit arbitrary. the solution that comes to mind initially is setting a threshold of the heat map. So in the case of the example heat map images - when applying a bounding box cover all regions that are yellow/orange/red than say green/blue.


问:
How to create azure machine learning resource using terraform resource providers?
I wants to create azure machine learning workspace using terraform scripts.Is there any terraform provider to achieve this.</p>

答:
While Charles gave some valid work around of this, I am working on creating those ML related resources for terraform-provider-azurerm. Please check this PR out: https://github.com/terraform-providers/terraform-provider-azurerm/pull/5696

Once this PR gets approved, merged and released, you will be able to create ML workspaces natively using terraform.
Other ml related resources are also on schedule.


Title: How to sort open weather map API response when you request 2+ days of forecast

Body:
Hello guys this is my first post.
I'm struggling real hard with this.
When you ask for multiple days forecast the array is a real headache
it looks like this:

{
  "city": {
    "id": 261779,
    "name": "Ioannina",
    "coord": {
      "lon": 20.8508,
      "lat": 39.6675
    },
    "country": "GR",
    "population": 64012,
    "timezone": 7200
  },
  "cod": "200",
  "message": 1.6748099,
  "cnt": 3,
  "list": [
    {
      "dt": 1581674400,
      "sunrise": 1581658280,
      "sunset": 1581696629,
      "temp": {
        "day": 5.85,
        "min": 5.34,
        "max": 6.89,
        "night": 6.73,
        "eve": 6.19,
        "morn": 5.34
      },
      "feels_like": {
        "day": 3.07,
        "night": 5.55,
        "eve": 3.59,
        "morn": 3.04
      },
      "pressure": 1019,
      "humidity": 97,
      "weather": [
        {
          "id": 502,
          "main": "Rain",
          "description": "heavy intensity rain",
          "icon": "10d"
        }
      ],
      "speed": 2.49,
      "deg": 197,
      "clouds": 100,
      "rain": 38.63
    },
    {
      "dt": 1581760800,
      "sunrise": 1581744606,
      "sunset": 1581783100,
      "temp": {
        "day": 8.65,
        "min": 3.92,
        "max": 10.93,
        "night": 3.92,
        "eve": 9.52,
        "morn": 5.04
      },
      "feels_like": {
        "day": 5.27,
        "night": 0.66,
        "eve": 6.49,
        "morn": 1.8
      },
      "pressure": 1020,
      "humidity": 67,
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "sky is clear",
          "icon": "01d"
        }
      ],
      "speed": 2.65,
      "deg": 31,
      "clouds": 4
    },
    {
      "dt": 1581847200,
      "sunrise": 1581830931,
      "sunset": 1581869570,
      "temp": {
        "day": 9.25,
        "min": 2.54,
        "max": 11.97,
        "night": 3.2,
        "eve": 10.1,
        "morn": 2.62
      },
      "feels_like": {
        "day": 7.09,
        "night": 0.06,
        "eve": 8.26,
        "morn": -0.71
      },
      "pressure": 1028,
      "humidity": 57,
      "weather": [
        {
          "id": 802,
          "main": "Clouds",
          "description": "scattered clouds",
          "icon": "03d"
        }
      ],
      "speed": 0.5,
      "deg": 59,
      "clouds": 31
    }
  ]
}

I have one week struggling to separate the forecast of each day seperately. and then print some basic values on my program like temp and humidity for example.
Also I'm using tkinter to build a GUI to show every day's forecast.'

If you'd like to see the code of the program: https://github.com/zafalex88/open_weather_project/

Every opinion is welcomed.

Thank you in advance!
Alex

Body:
You can print

print( data['list'][0]['humidity'] )
print( data['list'][1]['humidity'] )

or using loop

for day in data['list']:
    print('humidity:', day['humidity'])

Minimal working example - it also use datetime to convert dt (timestamp) to date

import datetime

data = {"city":{"id":261779,"name":"Ioannina","coord":{"lon":20.8508,"lat":39.6675},"country":"GR","population":64012,"timezone":7200},"cod":"200","message":1.6748099,"cnt":3,"list":[{"dt":1581674400,"sunrise":1581658280,"sunset":1581696629,"temp":{"day":5.85,"min":5.34,"max":6.89,"night":6.73,"eve":6.19,"morn":5.34},"feels_like":{"day":3.07,"night":5.55,"eve":3.59,"morn":3.04},"pressure":1019,"humidity":97,"weather":[{"id":502,"main":"Rain","description":"heavy intensity rain","icon":"10d"}],"speed":2.49,"deg":197,"clouds":100,"rain":38.63},{"dt":1581760800,"sunrise":1581744606,"sunset":1581783100,"temp":{"day":8.65,"min":3.92,"max":10.93,"night":3.92,"eve":9.52,"morn":5.04},"feels_like":{"day":5.27,"night":0.66,"eve":6.49,"morn":1.8},"pressure":1020,"humidity":67,"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01d"}],"speed":2.65,"deg":31,"clouds":4},{"dt":1581847200,"sunrise":1581830931,"sunset":1581869570,"temp":{"day":9.25,"min":2.54,"max":11.97,"night":3.2,"eve":10.1,"morn":2.62},"feels_like":{"day":7.09,"night":0.06,"eve":8.26,"morn":-0.71},"pressure":1028,"humidity":57,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"speed":0.5,"deg":59,"clouds":31}]}

for day in data['list']:

    date = datetime.datetime.fromtimestamp(day['dt'])
    print('date:', date)

    print('humidity:', day['humidity'])

    #print('temp:', day['temp'])
    print('temp day:', day['temp']['day'])
    print('temp min:', day['temp']['min'])
    print('temp max:', day['temp']['max'])

Result:

date: 2020-02-14 11:00:00
humidity: 97
temp day: 5.85
temp min: 5.34
temp max: 6.89
date: 2020-02-15 11:00:00
humidity: 67
temp day: 8.65
temp min: 3.92
temp max: 10.93
date: 2020-02-16 11:00:00
humidity: 57
temp day: 9.25
temp min: 2.54
temp max: 11.97

Minimal example with tkinter

import tkinter as tk
import datetime

data = {"city":{"id":261779,"name":"Ioannina","coord":{"lon":20.8508,"lat":39.6675},"country":"GR","population":64012,"timezone":7200},"cod":"200","message":1.6748099,"cnt":3,"list":[{"dt":1581674400,"sunrise":1581658280,"sunset":1581696629,"temp":{"day":5.85,"min":5.34,"max":6.89,"night":6.73,"eve":6.19,"morn":5.34},"feels_like":{"day":3.07,"night":5.55,"eve":3.59,"morn":3.04},"pressure":1019,"humidity":97,"weather":[{"id":502,"main":"Rain","description":"heavy intensity rain","icon":"10d"}],"speed":2.49,"deg":197,"clouds":100,"rain":38.63},{"dt":1581760800,"sunrise":1581744606,"sunset":1581783100,"temp":{"day":8.65,"min":3.92,"max":10.93,"night":3.92,"eve":9.52,"morn":5.04},"feels_like":{"day":5.27,"night":0.66,"eve":6.49,"morn":1.8},"pressure":1020,"humidity":67,"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01d"}],"speed":2.65,"deg":31,"clouds":4},{"dt":1581847200,"sunrise":1581830931,"sunset":1581869570,"temp":{"day":9.25,"min":2.54,"max":11.97,"night":3.2,"eve":10.1,"morn":2.62},"feels_like":{"day":7.09,"night":0.06,"eve":8.26,"morn":-0.71},"pressure":1028,"humidity":57,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"speed":0.5,"deg":59,"clouds":31}]}

root = tk.Tk()

tk.Label(root, text='humidity').pack()

listbox = tk.Listbox(root)
listbox.pack()

for day in data['list']:
    #listbox.insert('end', day['humidity'])
    date = datetime.datetime.fromtimestamp(day['dt'])
    text = '{}: {}'.format(date.strftime('%Y.%m.%d'), day['humidity'])
    listbox.insert('end', text)

root.mainloop()


问:
How to open native files app in ios?
How do i open the native files app of ios using url scheme or some other way ?
I tried searching url scheme but had no luck.

There seems to be no answer to this question there is thread open for this question in apples forum but it is still unanswered.
https://forums.developer.apple.com/message/257860#257860
Can it be done using the bundle identifier ?

答:
There is the option to open the Files app at a specific location using the shareddocuments:// URL scheme, as described in this article.

If you want the user to select a document, you can use chriswillow's approach with the UIDocumentPickerViewController.
If you want to present the documents or folders in your app, create a Document Browser App.

Title: How to open native files app in ios?


问:
update weblogic application name

Goal:

In picture I want to change app name only "app" strong text

Question:

Can I change or update deployed weblogic application name without stop managed server?

Additional information after a while. If you want to change application name in weblogic wlst console, it takes error message.

This shows us weblogic ApplicationName property is a read only property.

答: No. You cannot change the name even if you stop managed server. You have to redeploy the application specifying the name you want or manipulate config.xml and restart all server(Not recommended as it can cause issues if not done correctly).</p>

Title: update weblogic application name


问:
Given a Timestamp - How to return the nearest Unit and Metric,,, ex: 13 mins, 1 hour
given a timestamp, I could like to have a method that returns the correct unit (secs, hours, minutes) and the correct metric for that unit.

Examples, for a timestamp:

```<code>1 sec ago - Unit: SEC, Metric: 1
20 secs ago - Unit: SECS, Metric: 20
1 hour ago - Unit: HOUR, Metric: 1
3 hour ago - Unit: HOURS, Metric: 3
25 hours ago - Unit: DAY, Metric: 1
50 hours ago - Unit: DAYS, Metric: 2
</code>```

For this method I only need to go support, sec, hours and days. Not months. Ideas?

答:
Most of the logic is already as a helper in Rails: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words

Something like this maybe:

def words_and_units(from_time, to_time = 0)

from_time = from_time.to_time if from_time.respond_to?(:to_time)
  to_time = to_time.to_time if to_time.respond_to?(:to_time)
  distance_in_minutes = (((to_time - from_time).abs)/60).round
  distance_in_seconds = ((to_time - from_time).abs).round

```<code>case distance_in_minutes
  when 0..1

    case distance_in_seconds
      when 0..59   then {:metric => distance_in_seconds, :unit => 'SEC'}
      else             {:metric => 1, :unit => 'MIN'}
    end

  when 2..44           then {:metric => distance_in_minutes, :unit => 'MIN'}
  when 45..89          then {:metric => 1, :unit => 'HOUR'}
  when 90..1439        then {:metric => (distance_in_minutes.to_f / 60.0).round, :unit => 'HOUR'}
  when 1440..2529      then {:metric => 1, :unit => 'DAY'}
  when 2530..43199     then {:metric => (distance_in_minutes.to_f / 1440.0).round, :unit => 'DAY'}
  else
    raise WayToLongError
end
</code>```

end

Body:
given a timestamp, I could like to have a method that returns the correct unit (secs, hours, minutes) and the correct metric for that unit.

Examples, for a timestamp:

1 sec ago - Unit: SEC, Metric: 1
20 secs ago - Unit: SECS, Metric: 20
1 hour ago - Unit: HOUR, Metric: 1
3 hour ago - Unit: HOURS, Metric: 3
25 hours ago - Unit: DAY, Metric: 1
50 hours ago - Unit: DAYS, Metric: 2

For this method I only need to go support, sec, hours and days. Not months. Ideas?

Body:
Most of the logic is already as a helper in Rails: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words

Something like this maybe:

def words_and_units(from_time, to_time = 0)

from_time = from_time.to_time if from_time.respond_to?(:to_time)
  to_time = to_time.to_time if to_time.respond_to?(:to_time)
  distance_in_minutes = (((to_time - from_time).abs)/60).round
  distance_in_seconds = ((to_time - from_time).abs).round

case distance_in_minutes
  when 0..1

    case distance_in_seconds
      when 0..59   then {:metric => distance_in_seconds, :unit => 'SEC'}
      else             {:metric => 1, :unit => 'MIN'}
    end

  when 2..44           then {:metric => distance_in_minutes, :unit => 'MIN'}
  when 45..89          then {:metric => 1, :unit => 'HOUR'}
  when 90..1439        then {:metric => (distance_in_minutes.to_f / 60.0).round, :unit => 'HOUR'}
  when 1440..2529      then {:metric => 1, :unit => 'DAY'}
  when 2530..43199     then {:metric => (distance_in_minutes.to_f / 1440.0).round, :unit => 'DAY'}
  else
    raise WayToLongError
end

end


问:
Is there a way to sort this Google scripts function numerically/opposite direction?
Here is the script that I'm using to pull all the sheet names of a Google Sheet Document into a list on a front sheet.  It is working; however, is there a way to sort this the opposite way?  I have the sheets named by date with the oldest date as the furthest sheet and the newest sheet the closest to the front.  So it is sorting the newest date first but I would like it to sort with the oldest date first.  Also, is there a way to make this function dynamic so it updates as new sheets are added or if the sheet names change?</p>

```<code>function sheetnames() {
  var out = new Array()
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

for (var i=0 ; i<sheets.length ; i++) {
  Logger.log(String(sheets[i].getSheetId()));
 // var sheetId = sheets.getSheetId()
  out.push( [ sheets[i].getName() ] )
}

return out
}
</code>```

答:
You could use an onChange Installable Trigger, but take into consideration its Restrictions. In this way, the code I will be providing you, it will run every time you add a new sheet or you edit a sheet's name:

```<code>// Installable Trigger
function onChange() {
  var dates = sheetNames();
  Logger.log(dates);
}

function sheetNames(){
  try{
    // Get all sheets and then return
    return SpreadsheetApp.getActiveSpreadsheet()
             .getSheets()
             // Get a new array only with the sheet names
             .map(function(sheet){ return sheet.getName() })
             // Sort the array from the oldest date to the newest date
             .sort(
               function (sheet1, sheet2){
                 return new Date(sheet2) - new Date(sheet1);
               });
  } catch(e){
    Logger.log("Not a date");
    return e;
  }
}
</code>```

Now, for setting up the installable trigger, do the following:

1) Go to your Apps Script project

2) Click Edit->Current project's triggers

3) Click "+ Add Trigger"

4) Select :

Choose which function to run ->

Select event source-> From spreadsheet

Select event type -> On change

5) Click Save

Body:
Here is the script that I'm using to pull all the sheet names of a Google Sheet Document into a list on a front sheet.  It is working; however, is there a way to sort this the opposite way?  I have the sheets named by date with the oldest date as the furthest sheet and the newest sheet the closest to the front.  So it is sorting the newest date first but I would like it to sort with the oldest date first.  Also, is there a way to make this function dynamic so it updates as new sheets are added or if the sheet names change?

function sheetnames() {
  var out = new Array()
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

for (var i=0 ; i<sheets.length ; i++) {
  Logger.log(String(sheets[i].getSheetId()));
 // var sheetId = sheets.getSheetId()
  out.push( [ sheets[i].getName() ] )
}

return out
}

Body:
You could use an onChange Installable Trigger, but take into consideration its Restrictions. In this way, the code I will be providing you, it will run every time you add a new sheet or you edit a sheet's name:

// Installable Trigger
function onChange() {
  var dates = sheetNames();
  Logger.log(dates);
}

function sheetNames(){
  try{
    // Get all sheets and then return
    return SpreadsheetApp.getActiveSpreadsheet()
             .getSheets()
             // Get a new array only with the sheet names
             .map(function(sheet){ return sheet.getName() })
             // Sort the array from the oldest date to the newest date
             .sort(
               function (sheet1, sheet2){
                 return new Date(sheet2) - new Date(sheet1);
               });
  } catch(e){
    Logger.log("Not a date");
    return e;
  }
}

Now, for setting up the installable trigger, do the following:

1) Go to your Apps Script project

2) Click Edit->Current project's triggers

3) Click "+ Add Trigger"

4) Select :

Choose which function to run ->

Select event source-> From spreadsheet

Select event type -> On change

5) Click Save


问:
Javascript array search filter
I have the scenario, with provided example JSON data:

```<code>[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]
</code>```

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

```<code>filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});
</code>```

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.

答:
You need use filter function for filtering an array.

We have an array with persons:

```<code>const persons = [
    {
       "name": "Joe",
       "age": "28",
       "hobby": ["Reading", "Chilling", "Cycling"]
    },
    {
       "name": "Beck",
       "age": "25",
       "hobby": ["Drinking", "Cycling"]
    },
    {
       "name": "Candace",
       "age": "24",
       "hobby": ["Reading", "Singing"]
    }
]
</code>```

And then we will filter that array:

```<code>persons.filter((person) => {
    return person.age > 27;
})
</code>```

This code returns us Joe's info:

```<code>[
  {
    "name": "Joe",
    "age": "28",
    "hobby": ["Reading", "Chilling", "Cycling"]
  }
]
</code>```

Title: Javascript array search filter

Body:
I have the scenario, with provided example JSON data:

[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.

Body:
You need use filter function for filtering an array.

We have an array with persons:

const persons = [
    {
       "name": "Joe",
       "age": "28",
       "hobby": ["Reading", "Chilling", "Cycling"]
    },
    {
       "name": "Beck",
       "age": "25",
       "hobby": ["Drinking", "Cycling"]
    },
    {
       "name": "Candace",
       "age": "24",
       "hobby": ["Reading", "Singing"]
    }
]

And then we will filter that array:

persons.filter((person) => {
    return person.age > 27;
})

This code returns us Joe's info:

[
  {
    "name": "Joe",
    "age": "28",
    "hobby": ["Reading", "Chilling", "Cycling"]
  }
]


问:
What is the use case of using @Qualifier in @Bean definition?
I know meaning of @Qualifier and @Bean annotations but what is the point of using it in a code like this? Is this for overriding "loadBalancedRestTemplate" bean or what?</p>

```<code>@Bean
@Qualifier("loadBalancedRestTemplate")
public RestTemplate restTemplate(RestTemplateCustomizer customizer) {
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    customizer.customize(restTemplate);
    return restTemplate;
}
</code>```

答:
You can either use:

```<code>@Bean(name="loadBalancedRestTemplate")
public RestTemplate restTemplate(RestTemplateCustomizer customizer)...
</code>```

Or the one you posted interchangeably.

By default when using @Autowired spring will find a bean of the matching type and inject that bean. The problem is that if you have more than one bean of the same type, it won't know which one to inject. That's where you specify the @Qualifier or the bean name in the configuration, as per your code. In the @Autowired target you will then specify the same @Qualifier to tell Spring which bean is to be used.

A common use-case for RestTemplate is the need to make calls on multiple rest endpoints that work differently for some reason. In such cases it's common for example to use the setErrorHandler or setMessageConverters methods with different arguments based on the endpoint you are trying to call or to use the RestTemplateCustomizer as in your code.

In your specific case the customisations applied to loadBalancedRestTemplate depend on the provided RestTemplateCustomizer. Depending on how that object is created, your specific code may or may not be modified to simply return a new instance of RestTemplate.

As it stands, assuming that everything has been done for a valid reason, I can only speculate that:

different @Service classes will make use of different RestTemplate instances to call different services

there is another @Bean in your codebase that defines RestTemplateCustomizer

other RestTemplate instances won't be using that RestTemplateCustomizer, thus making them differently than the one in the code you provided

Body:
I know meaning of @Qualifier and @Bean annotations but what is the point of using it in a code like this? Is this for overriding "loadBalancedRestTemplate" bean or what?

@Bean
@Qualifier("loadBalancedRestTemplate")
public RestTemplate restTemplate(RestTemplateCustomizer customizer) {
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    customizer.customize(restTemplate);
    return restTemplate;
}

Body:
You can either use:

@Bean(name="loadBalancedRestTemplate")
public RestTemplate restTemplate(RestTemplateCustomizer customizer)...

Or the one you posted interchangeably.

By default when using @Autowired spring will find a bean of the matching type and inject that bean. The problem is that if you have more than one bean of the same type, it won't know which one to inject. That's where you specify the @Qualifier or the bean name in the configuration, as per your code. In the @Autowired target you will then specify the same @Qualifier to tell Spring which bean is to be used.

A common use-case for RestTemplate is the need to make calls on multiple rest endpoints that work differently for some reason. In such cases it's common for example to use the setErrorHandler or setMessageConverters methods with different arguments based on the endpoint you are trying to call or to use the RestTemplateCustomizer as in your code.

In your specific case the customisations applied to loadBalancedRestTemplate depend on the provided RestTemplateCustomizer. Depending on how that object is created, your specific code may or may not be modified to simply return a new instance of RestTemplate.

As it stands, assuming that everything has been done for a valid reason, I can only speculate that:

different @Service classes will make use of different RestTemplate instances to call different services

there is another @Bean in your codebase that defines RestTemplateCustomizer

other RestTemplate instances won't be using that RestTemplateCustomizer, thus making them differently than the one in the code you provided


问:
when call router.post method from url get error 404 not found in express.js
I have got a problem with Express, I am trying to use the app.post() function but it's not working and I don't know why...

Even though I have included the bodyParser()...

It returns 404 page not found error

```<code>var express = require('express');

var MongoClient = require('mongodb').MongoClient;

var router = express.Router();

router.post("/hello",(req, res) => {
        res.send('POST CALL');
    });

/* GET home page. */
router.get('/', function(req, res, next) {
    MongoClient.connect('mongodb://localhost:27017/nicky', function (err, client) {
        if (err) throw err

        var db = client.db('nicky')

        db.collection('student').find().toArray(function (err, result) {
            if (err) throw err
            res.send(JSON.stringify(result));
        })
    })
});
module.exports = router;
</code>```

GET is working properly, but POST is not.

答:
May be you forgot to use
 app.use('/',require('import route here'));
in main app.</p>

Body:
I have got a problem with Express, I am trying to use the app.post() function but it's not working and I don't know why...

Even though I have included the bodyParser()...

It returns 404 page not found error

var express = require('express');

var MongoClient = require('mongodb').MongoClient;

var router = express.Router();

router.post("/hello",(req, res) => {
        res.send('POST CALL');
    });

/* GET home page. */
router.get('/', function(req, res, next) {
    MongoClient.connect('mongodb://localhost:27017/nicky', function (err, client) {
        if (err) throw err

        var db = client.db('nicky')

        db.collection('student').find().toArray(function (err, result) {
            if (err) throw err
            res.send(JSON.stringify(result));
        })
    })
});
module.exports = router;

GET is working properly, but POST is not.


问:
'where' is not valid at this porsition
'where' is not valid at this position
please help
i'not good at english...
please find wrong points..

```<code>    enter code here
select @row_num := @row_num+1  AS RowNumber, a.rawid ,a.codename,
ifnull(group_concat(a.dcname ) ,'-')  AS dcnames ,
    ifnull(group_concat(a.dcrawid) ,'-')  as dcrawids , b.cnt
from (
    SELECT id.codename ,d.dcname,d.rawid as dcrawid , id.rawid,
        @row_number:=CASE
            WHEN @customer_no = id.rawid
              THEN
                  @row_number + 1
              ELSE
                   1
            END AS num,
        @customer_no:=id.rawid CustomerNumber
    FROM
    (SELECT @customer_no:=0,@row_number:=0) as t,
    infocd id
    left JOIN infocddetail il ON id.RAWID = il.infocdrawid
    left JOIN dc d on d.rawid = il.dcrawid
)a
left join (
    select id.rawid , count(f.rawid) cnt from infocd id
    left join form f on f.infocdrawid = id.rawid
    group by id.rawid
) b on b.rawid = a.rawid
group by a.codename ,a.rawid
where a.codename like '%2%';
</code>```

'where' is not valid at this position
please help
i'not good at english...
please find wrong points..

答:
you have to swap where and group by lines like below

where a.codename like '%2%'
group by a.codename ,a.rawid
;
```

Title: 'where' is not valid at this porsition

Body:
'where' is not valid at this position
please help
i'not good at english...
please find wrong points..

    enter code here
select @row_num := @row_num+1  AS RowNumber, a.rawid ,a.codename,
ifnull(group_concat(a.dcname ) ,'-')  AS dcnames ,
    ifnull(group_concat(a.dcrawid) ,'-')  as dcrawids , b.cnt
from (
    SELECT id.codename ,d.dcname,d.rawid as dcrawid , id.rawid,
        @row_number:=CASE
            WHEN @customer_no = id.rawid
              THEN
                  @row_number + 1
              ELSE
                   1
            END AS num,
        @customer_no:=id.rawid CustomerNumber
    FROM
    (SELECT @customer_no:=0,@row_number:=0) as t,
    infocd id
    left JOIN infocddetail il ON id.RAWID = il.infocdrawid
    left JOIN dc d on d.rawid = il.dcrawid
)a
left join (
    select id.rawid , count(f.rawid) cnt from infocd id
    left join form f on f.infocdrawid = id.rawid
    group by id.rawid
) b on b.rawid = a.rawid
group by a.codename ,a.rawid
where a.codename like '%2%';

'where' is not valid at this position
please help
i'not good at english...
please find wrong points..


问:
Regular expression to extract first word + first character of all following words
I am (newbie) using R and regular Regular expression to write the regex for manipulating strings in a data.frame column. My data look like this in R:

```<code>c1
Peter Parker
Hawk & Dove
J Jonah Jameson
3JPX spo
Bruce Wayne
</code>```

What I am trying to get is 2nd column "c2" that consists of the following strings:

```<code>c2
PeterP
Hawk&D
JJJ
3JPXs
BruceW
</code>```

Basically I want the entire first word of the string (regardless of length) and the first alphanumeric element of every word after. I have not been able to find any function or logic for this. Is it possible to do so with regex?

Thanks in Advance

答:
Here is a base R approach using gsub:

```<code>x <- c("Peter Parker", "Hawk & Dove", "J Jonah Jameson", "3JPX spo", "Bruce Wayne")
output <- gsub("\\s+(\\S)\\S*(?!\\S)", "\\1", x, perl=TRUE)
output

[1] "PeterP" "Hawk&D" "JJJ"    "3JPXs"  "BruceW"
</code>```

The regex pattern \s+(\S)\S*(?!\S) matches one or more space characters, then matches and captures the first character of the name component.  It also consumes the remainder of the name component, replacing with only the captured first character.

In case the above still be unclear to you, here is how the regex pattern works, step by step:

```<code>\s+    match one or more space characters
(\S)   then match AND capture the first character of the name-word
\S*    match the remainder of the name-word
(?!\S) assert that what follows the end of the name-word is either a space
       or the end of the string
</code>```

The replacement in the call to gsub is just \1, which is the first and only capture group, corresponding to the first letter of each name, beyond the very first name.

Body:
I am (newbie) using R and regular Regular expression to write the regex for manipulating strings in a data.frame column. My data look like this in R:

c1
Peter Parker
Hawk & Dove
J Jonah Jameson
3JPX spo
Bruce Wayne

What I am trying to get is 2nd column "c2" that consists of the following strings:

c2
PeterP
Hawk&D
JJJ
3JPXs
BruceW

Basically I want the entire first word of the string (regardless of length) and the first alphanumeric element of every word after. I have not been able to find any function or logic for this. Is it possible to do so with regex?

Thanks in Advance

Body:
Here is a base R approach using gsub:

x <- c("Peter Parker", "Hawk & Dove", "J Jonah Jameson", "3JPX spo", "Bruce Wayne")
output <- gsub("\\s+(\\S)\\S*(?!\\S)", "\\1", x, perl=TRUE)
output

[1] "PeterP" "Hawk&D" "JJJ"    "3JPXs"  "BruceW"

The regex pattern \s+(\S)\S*(?!\S) matches one or more space characters, then matches and captures the first character of the name component.  It also consumes the remainder of the name component, replacing with only the captured first character.

In case the above still be unclear to you, here is how the regex pattern works, step by step:

\s+    match one or more space characters
(\S)   then match AND capture the first character of the name-word
\S*    match the remainder of the name-word
(?!\S) assert that what follows the end of the name-word is either a space
       or the end of the string

The replacement in the call to gsub is just \1, which is the first and only capture group, corresponding to the first letter of each name, beyond the very first name.


问:
Grid does not animate from collapsed to visible
I'm currently trying to make a grid that animates from collapsed -> visible to notify the user that the save has been completed.  In Blend 4 I opened the project and created a usercontrol for the SaveNotifier so I can use it in other areas of this project and others.  I created the default to be collapsed and also created another state called "Complete" which has visibility set to Visible and has a timetrigger of 3 seconds which sends it back to the default state.  The transitions are set to transition over 1 second and use fluidlayout to show the animation between the states, but it does not show the animation between states.  Instead it just shows it as if there was no fluidlayout or transition time.

If someone would be so kind as to let me know if there is a problem with trying to do this or even show me how to do this it would be gre

答: Not sure why, but when I put the grid inside of a new grid it started working. Seems as if you need to have a grid to be the full size for the animation to display.</p>


问:
Private/login section of Gatsby + contentful + Netlify
I would like to have a section of my contentful + Gatsby + Netlify site to only be available to certain people. I'm not sure how to set up private routes with these instructions because of contentful--the routines are being dynamically created on the build. I can't figure out how to set just one or two of the sections to login and leave all the other public. Can someone make a suggestion or point me to a guide?</p>

答:
This is the important bit from the tutorial you linked.

I can't figure out how to set just one or two of the sections to login and leave all the others public. Can someone make a suggestion or point me to a guide?

Pick a route you want to make private for example /app/profile. This can be done purely in React:

//src/components/privateRoute.js

import React, { Component } from "react"
import { navigate } from "gatsby"
import { isLoggedIn } from "../services/auth"
const PrivateRoute = ({ component: Component, location, ...rest }) => {
  if (!isLoggedIn() && location.pathname !== `/app/login`) {
    navigate("/app/login")
    return null
  }
  return <Component {...rest} />
}
export default PrivateRoute
```

<p>You need to store login credentials somewhere. I would advise to use React content together with your authentication API. Here is a question that might help you.</p>

<pre class="lang-js prettyprint-override"><code>// AuthContextProvider class:

import React from "react";

export const AuthContext = React.createContext();

export class AuthContextProvider extends React.Component {
  state = {
    authenticated: false,
    toggleLogin: () => {},
    userid: null,
  };

  render() {
    return (
      <AuthContext.Provider
        value={{
          authenticated: this.state.authenticated,
          userid: this.state.userid,
          toggleLogin: () => {
            const previousValueState = this.state.authenticated;
            this.setState(state => ({
              authenticated: !previousValueState,
              userid: 2,
            }));
          },
        }}
      >
        {this.props.children}
      </AuthContext.Provider>
    );
  }
}
</code>```

And now you can edit your Router to use the PrivateRoute component:

//src/pages/app.js

import React from "react"
import { Router } from "@reach/router"
import Layout from "../components/layout"
import PrivateRoute from "../components/privateRoute"
import Profile from "../components/profile"
import Login from "../components/login"
const App = () => (
  <Layout>
    <Router>
      <PrivateRoute path="/app/profile" component={Profile} />
      <Login path="/app/login" />
    </Router>
  </Layout>
)
export default App
```

I would advise to not worry about Contentful. The concept about private routes is handled by Gatsby and React. CMSs like Contentful are irrelevant for private routes. You need to be more specific with your question if you want a more detailed answer for this part.

Body:
This is the important bit from the tutorial you linked.

I can't figure out how to set just one or two of the sections to login and leave all the others public. Can someone make a suggestion or point me to a guide?

Pick a route you want to make private for example /app/profile. This can be done purely in React:

//src/components/privateRoute.js

import React, { Component } from "react"
import { navigate } from "gatsby"
import { isLoggedIn } from "../services/auth"
const PrivateRoute = ({ component: Component, location, ...rest }) => {
  if (!isLoggedIn() && location.pathname !== `/app/login`) {
    navigate("/app/login")
    return null
  }
  return <Component {...rest} />
}
export default PrivateRoute

You need to store login credentials somewhere. I would advise to use React content together with your authentication API. Here is a question that might help you.

// AuthContextProvider class:

import React from "react";

export const AuthContext = React.createContext();

export class AuthContextProvider extends React.Component {
  state = {
    authenticated: false,
    toggleLogin: () => {},
    userid: null,
  };

  render() {
    return (
      <AuthContext.Provider
        value={{
          authenticated: this.state.authenticated,
          userid: this.state.userid,
          toggleLogin: () => {
            const previousValueState = this.state.authenticated;
            this.setState(state => ({
              authenticated: !previousValueState,
              userid: 2,
            }));
          },
        }}
      >
        {this.props.children}
      </AuthContext.Provider>
    );
  }
}

And now you can edit your Router to use the PrivateRoute component:

//src/pages/app.js

import React from "react"
import { Router } from "@reach/router"
import Layout from "../components/layout"
import PrivateRoute from "../components/privateRoute"
import Profile from "../components/profile"
import Login from "../components/login"
const App = () => (
  <Layout>
    <Router>
      <PrivateRoute path="/app/profile" component={Profile} />
      <Login path="/app/login" />
    </Router>
  </Layout>
)
export default App

I would advise to not worry about Contentful. The concept about private routes is handled by Gatsby and React. CMSs like Contentful are irrelevant for private routes. You need to be more specific with your question if you want a more detailed answer for this part.


答:
A map is an associative container. Unlike sequential containers, where you have control over the location of the element, an associative container itself controls the order of the elements. Once the associative container is created, the ordering cannot be changed.

There is no ordered_map in standard C++. There is std::map, which is a tree (and therefore the elements already appear sorted based on the comparator) and std::unordered_map, which is a hash table (the elements are somewhat ordered based on the hash of the key).

Title: Is there any C++ function to sort a Map?

Body: I want to know that how can I sort an ordered_map in C++ on the basis of values. Is there any function to do it?


问:
Set cell color based on current value
How can my code be made shorter?

If a user fills the cell with color yellow then if its value is 0 then it will turn to red and it will popup a message box, then if its value is > 0 it will back again to yellow, then if the user enters value of > 0 in the "no fill up cell" it will turn grey and back to no fill up if I input 0 this code is for column L only I need to make this for column M, N and O also.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Dim ws As Worksheet
    Set ws = ActiveSheet
    On Error GoTo ExitSub

    'WEEK 0
    'For Task Not done
    With ws.Cells(15, 12)
        If Not (Application.Intersect(Range("L15"), Target) Is Nothing) Then
            If .Interior.ColorIndex = 6 And .Value < 1 Then
                MsgBox "Project Delay!"
                Range("L15").Interior.ColorIndex = 3
            Else
                If Range("L15").Interior.ColorIndex = 3 And .Value > 0 Then
                    Range("L15").Interior.ColorIndex = 6
                End If
            End If

            'For overlapped Task
            If .Interior.ColorIndex = -4142 And .Value > 0 Then
                MsgBox "Overlap!"
                Range("L15").Interior.ColorIndex = 16
            Else
                If Range("L15").Interior.ColorIndex = 16 And .Value < 1 Then
                    Range("L15").Interior.ColorIndex = -4142
                End If
            End If
        End If
    End With

    On Error GoTo ExitSub

    'For Task Not done
    With ws.Cells(17, 12)
        If Not (Application.Intersect(Range("L17"), Target) Is Nothing) Then
            If .Interior.ColorIndex = 6 And .Value < 1 Then
                MsgBox "Project Delay!"
                Range("L17").Interior.ColorIndex = 3
            Else
                If Range("L17").Interior.ColorIndex = 3 And .Value > 0 Then
                    Range("L17").Interior.ColorIndex = 6
                End If
            End If

            'For overlapped Task
            If .Interior.ColorIndex = -4142 And .Value > 0 Then
                MsgBox "Overlap!"
                Range("L17").Interior.ColorIndex = 16
            Else
                If Range("L17").Interior.ColorIndex = 16 And .Value < 1 Then
                    Range("L17").Interior.ColorIndex = -4142
                End If
            End If
        End If
    End With
End Sub
</code>```

答:
Please try this code. As far as I understood your intentions it should do what you want.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Tmp As Long

    With Target
        If .Cells.CountLarge > 1 Then Exit Sub
        If (.Column >= Columns("L").Column) And (.Column <= .Columns("O").Column) Then
            Tmp = Val(.Value)
            Select Case .Row
                Case 15
                    .Interior.ColorIndex = IIf(Tmp, 6, 3)
                    If Tmp = 0 Then
                        MsgBox "Project Delay!", _
                               vbCritical, "Attention required!"
                    End If
                Case 17
                    .Interior.ColorIndex = IIf(Tmp, 16, -4142)
                    If Tmp Then
                        MsgBox "Enter a value of zero.", _
                               vbExclamation, "Overlap!"
                    End If
            End Select
        End If
    End With
End Sub
</code>```

I have kept the syntax simple so that you ought to be able to tweak it where it needs tweaking. Good luck!

Title: Set cell color based on current value

Body:
How can my code be made shorter?

If a user fills the cell with color yellow then if its value is 0 then it will turn to red and it will popup a message box, then if its value is > 0 it will back again to yellow, then if the user enters value of > 0 in the "no fill up cell" it will turn grey and back to no fill up if I input 0 this code is for column L only I need to make this for column M, N and O also.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim ws As Worksheet
    Set ws = ActiveSheet
    On Error GoTo ExitSub

    'WEEK 0
    'For Task Not done
    With ws.Cells(15, 12)
        If Not (Application.Intersect(Range("L15"), Target) Is Nothing) Then
            If .Interior.ColorIndex = 6 And .Value < 1 Then
                MsgBox "Project Delay!"
                Range("L15").Interior.ColorIndex = 3
            Else
                If Range("L15").Interior.ColorIndex = 3 And .Value > 0 Then
                    Range("L15").Interior.ColorIndex = 6
                End If
            End If

            'For overlapped Task
            If .Interior.ColorIndex = -4142 And .Value > 0 Then
                MsgBox "Overlap!"
                Range("L15").Interior.ColorIndex = 16
            Else
                If Range("L15").Interior.ColorIndex = 16 And .Value < 1 Then
                    Range("L15").Interior.ColorIndex = -4142
                End If
            End If
        End If
    End With

    On Error GoTo ExitSub

    'For Task Not done
    With ws.Cells(17, 12)
        If Not (Application.Intersect(Range("L17"), Target) Is Nothing) Then
            If .Interior.ColorIndex = 6 And .Value < 1 Then
                MsgBox "Project Delay!"
                Range("L17").Interior.ColorIndex = 3
            Else
                If Range("L17").Interior.ColorIndex = 3 And .Value > 0 Then
                    Range("L17").Interior.ColorIndex = 6
                End If
            End If

            'For overlapped Task
            If .Interior.ColorIndex = -4142 And .Value > 0 Then
                MsgBox "Overlap!"
                Range("L17").Interior.ColorIndex = 16
            Else
                If Range("L17").Interior.ColorIndex = 16 And .Value < 1 Then
                    Range("L17").Interior.ColorIndex = -4142
                End If
            End If
        End If
    End With
End Sub

Body:
Please try this code. As far as I understood your intentions it should do what you want.

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Tmp As Long

    With Target
        If .Cells.CountLarge > 1 Then Exit Sub
        If (.Column >= Columns("L").Column) And (.Column <= .Columns("O").Column) Then
            Tmp = Val(.Value)
            Select Case .Row
                Case 15
                    .Interior.ColorIndex = IIf(Tmp, 6, 3)
                    If Tmp = 0 Then
                        MsgBox "Project Delay!", _
                               vbCritical, "Attention required!"
                    End If
                Case 17
                    .Interior.ColorIndex = IIf(Tmp, 16, -4142)
                    If Tmp Then
                        MsgBox "Enter a value of zero.", _
                               vbExclamation, "Overlap!"
                    End If
            End Select
        End If
    End With
End Sub

I have kept the syntax simple so that you ought to be able to tweak it where it needs tweaking. Good luck!


问:
Set python 3 as default python version in CentOS
I have installed python 3.6 on my CentOS machine by following the guide at https://linuxize.com/post/how-to-install-python-3-on-centos-7/, which installs python 3 with the following:

```<code>sudo yum install rh-python36
</code>```

The default python version, however, is still python 2. The guide mentions I can run python 3 by first running scl enable rh-python36 bash, and then python 3 will be used. However, this only works for that session - logging out and back in will revert back to python 2. According to How to set Python3.5.2 as default Python version on CentOS?, python 3 can be set as the default with the following:

```<code>sudo ln -fs /usr/bin/python3 /usr/bin/python
</code>```

However, this doesn't work for me as for some reason I don't have any python3 file in /usr/bin/ - I only have python, python2, python2.7, python2.7-config, python2-config and python-config (despite installing python 3 with yum as above).

答:
First, run

```<code>$ scl enable rh-python36 bash
</code>```

to switch python version.

Second, run

```<code>$ which python
</code>```

to find out the exact path of python3.6 binary.

Third, edit ~/.bashrc.

```<code>$ vim ~/.bashrc
</code>```

and add below line.

```<code>alias python='/opt....(the path you found by "which python")'
</code>```

and save the file.

Body:
I have installed python 3.6 on my CentOS machine by following the guide at https://linuxize.com/post/how-to-install-python-3-on-centos-7/, which installs python 3 with the following:

sudo yum install rh-python36

The default python version, however, is still python 2. The guide mentions I can run python 3 by first running scl enable rh-python36 bash, and then python 3 will be used. However, this only works for that session - logging out and back in will revert back to python 2. According to How to set Python3.5.2 as default Python version on CentOS?, python 3 can be set as the default with the following:

sudo ln -fs /usr/bin/python3 /usr/bin/python

However, this doesn't work for me as for some reason I don't have any python3 file in /usr/bin/ - I only have python, python2, python2.7, python2.7-config, python2-config and python-config (despite installing python 3 with yum as above).

Body:
First, run

$ scl enable rh-python36 bash

to switch python version.

Second, run

$ which python

to find out the exact path of python3.6 binary.

Third, edit ~/.bashrc.

$ vim ~/.bashrc

and add below line.

alias python='/opt....(the path you found by "which python")'

and save the file.


问:
Combine two datasets, based on POSIXct values
I am struggling with combining two datasets with each other.

Dataset1 is containing a "before time" and a "after time", and a "channel".

Dataset2 is containing just one "time" and a "channel" column as well.

I want to add an binary column (Yes/No) to Dataset1, with this logic:
If there is a row in Dataset2, where the channel == channel, and Time is within the "before" and "after" time, I want to have "YES". Else "NO".

Data1

```<code>ID   Channel   before_time   after_time
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00
</code>```

Data2

```<code>ID_B     Channel_B    Time_B
Hallo       A1        2019-09-02 20:23:00
Hi          B2        2019-09-02 20:05:00
Hoi         C1        2019-09-02 22:23:00
</code>```

Desired Output

```<code>ID   Channel   before_time   after_time                     Available
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00         Yes  # Channel == Channel, Time between before & after
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00          No  # Channel != Channel
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00          No  # Time is not between before & after
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00          No  # There is no matching data where channel is D1
</code>```

Desired Output 2 (comments Solutions)

Adding extra columns from the second data set (Data2).

```<code>ID   Channel   before_time   after_time                     Available   ID_B
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00          Yes        Hallo
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00          No         x
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00          No         x
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00          No         x
</code>```

Reproducible example (the data):

```<code>ID <- c("1", "2", "3", "4")
channel <- c("A1", "B1", "C1", "D1)
#startdate <- as.POSIXct(c("2019-09-02 20:23:00", "2019-09-02 20:13:00", "2019-09-02 20:33:00", "2019-09-02 20:33:00"))
before_time <- as.POSIXct(c("2019-09-02 20:13:00", "2019-09-02 20:03:00", "2019-09-02 20:23:00", "2019-09-02 20:23:00"))
after_time  <- as.POSIXct(c("2019-09-02 20:33:00", "2019-09-02 20:23:00", "2019-09-02 20:43:00","2019-09-02 20:43:00"))
data1 <- data.frame(ID, channel,   before_time, after_time)
View(data1)

ID_B <- c("Hallo", "Hi", "Hoi")
channel_B <- c("A1", "B2", "C1")
Time_B <- as.POSIXct(c("2019-09-02 20:23:00", "2019-09-02 20:05:00", "2019-09-02 22:23:00"))
data2 <- data.frame(ID_B, channel_B, Time_B)
View(data2)
</code>```

Body:
I am struggling with combining two datasets with each other.

Dataset1 is containing a "before time" and a "after time", and a "channel".

Dataset2 is containing just one "time" and a "channel" column as well.

I want to add an binary column (Yes/No) to Dataset1, with this logic:
If there is a row in Dataset2, where the channel == channel, and Time is within the "before" and "after" time, I want to have "YES". Else "NO".

Data1

ID   Channel   before_time   after_time
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00

Data2

ID_B     Channel_B    Time_B
Hallo       A1        2019-09-02 20:23:00
Hi          B2        2019-09-02 20:05:00
Hoi         C1        2019-09-02 22:23:00

Desired Output

ID   Channel   before_time   after_time                     Available
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00         Yes  # Channel == Channel, Time between before & after
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00          No  # Channel != Channel
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00          No  # Time is not between before & after
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00          No  # There is no matching data where channel is D1

Desired Output 2 (comments Solutions)

Adding extra columns from the second data set (Data2).

ID   Channel   before_time   after_time                     Available   ID_B
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00          Yes        Hallo
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00          No         x
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00          No         x
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00          No         x

Reproducible example (the data):

ID <- c("1", "2", "3", "4")
channel <- c("A1", "B1", "C1", "D1)
#startdate <- as.POSIXct(c("2019-09-02 20:23:00", "2019-09-02 20:13:00", "2019-09-02 20:33:00", "2019-09-02 20:33:00"))
before_time <- as.POSIXct(c("2019-09-02 20:13:00", "2019-09-02 20:03:00", "2019-09-02 20:23:00", "2019-09-02 20:23:00"))
after_time  <- as.POSIXct(c("2019-09-02 20:33:00", "2019-09-02 20:23:00", "2019-09-02 20:43:00","2019-09-02 20:43:00"))
data1 <- data.frame(ID, channel,   before_time, after_time)
View(data1)

ID_B <- c("Hallo", "Hi", "Hoi")
channel_B <- c("A1", "B2", "C1")
Time_B <- as.POSIXct(c("2019-09-02 20:23:00", "2019-09-02 20:05:00", "2019-09-02 22:23:00"))
data2 <- data.frame(ID_B, channel_B, Time_B)
View(data2)

Body:
Here is a base R solution, using merge + ifelse, i.e.,

dfout <- subset(within(merge(data1,data2[-1],by.x = "channel",by.y = "channel_B",all.x = T),
                       Available <- ifelse(!is.na(Time_B)& Time_B>=before_time & Time_B<=after_time,"Yes","No")),
                select = -Time_B)

such that

> dfout
  channel ID         before_time          after_time Available
1      A1  1 2019-09-02 20:13:00 2019-09-02 20:33:00       Yes
2      B1  2 2019-09-02 20:03:00 2019-09-02 20:23:00        No
3      C1  3 2019-09-02 20:23:00 2019-09-02 20:43:00        No
4      D1  4 2019-09-02 20:23:00 2019-09-02 20:43:00        No


问:
Pandas groupby ffill zero values at end of the series
I'm trying to replace all the last zeros of a grouped series by the last non-zero value. So hence this code :

```<code>a = pd.DataFrame({'a': [1, 2, 0, 3, 5, 0, 0], 'b': [12,0 ,14, 0, 0, 0, 0]})
a.index = [1, 2, 3, 4, 5, 6, 7]
a = a.unstack()
a = a.reset_index().set_index('level_1')
a.columns = ['item', 'value']
a.sort_index(inplace=True)
</code>```

I'd like to arrive to this result

```<code>    item    value
level_1
1   a   1
1   b   12
2   a   2
2   b   0
3   a   0
3   b   14
4   a   3
4   b   14
5   a   5
5   b   14
6   a   5'
6   b   14
7   a   5
7   b   14
</code>```

Notice how the zeros between 2 and 3, and between 12 and 14 remained, but the ending zeros all were forward filled.

See below how I managed to get the indexes of the last non-zero values cleanly, but can't get the rest done.

```<code>a.groupby('item').apply(lambda x : [x != 0].index[-1])
</code>```

答:
If possible use original DataFrame replace 0 to missing values by DataFrame.mask and then in another mask forward filling only last missing values by ffill, what is tested by back filling with check NaNs:

```<code>df = pd.DataFrame({'a': [1, 2, 0, 3, 5, 0, 0], 'b': [12,0 ,14, 0, 0, 0, 0]})
df.index = [1, 2, 3, 4, 5, 6, 7]
print (df)
   a   b
1  1  12
2  2   0
3  0  14
4  3   0
5  5   0
6  0   0
7  0   0

df1 = df.mask(df.eq(0))
df =  df.mask(df1.bfill().isna(), df1.ffill())
print (df)
   a   b
1  1  12
2  2   0
3  0  14
4  3  14
5  5  14
6  5  14
7  5  14
</code>```

If not, first reshape to original, apply solution aand then reshape back:

```<code>df = a.set_index('item', append=True).unstack()
df1 = df.mask(df.eq(0))
df = df.mask(df1.bfill().isna(), df1.ffill()).stack().reset_index(level=1)
print (df)
        item  value
level_1
1          a      1
1          b     12
2          a      2
2          b      0
3          a      0
3          b     14
4          a      3
4          b     14
5          a      5
5          b     14
6          a      5
6          b     14
7          a      5
7          b     14
</code>```

Per groups similar idea:

```<code>def f(x):
    m = x['value'].eq(0)
    s = x['value'].mask(m)
    x['value'] = s.fillna(0).mask(s.bfill().isna(), s.ffill())
    return x

df = a.reset_index().groupby('item').apply(f)
print (df)
    level_1 item  value
0         1    a    1.0
1         1    b   12.0
2         2    a    2.0
3         2    b    0.0
4         3    a    0.0
5         3    b   14.0
6         4    a    3.0
7         4    b   14.0
8         5    a    5.0
9         5    b   14.0
10        6    a    5.0
11        6    b   14.0
12        7    a    5.0
13        7    b   14.0
</code>```

Body:
I'm trying to replace all the last zeros of a grouped series by the last non-zero value. So hence this code :

a = pd.DataFrame({'a': [1, 2, 0, 3, 5, 0, 0], 'b': [12,0 ,14, 0, 0, 0, 0]})
a.index = [1, 2, 3, 4, 5, 6, 7]
a = a.unstack()
a = a.reset_index().set_index('level_1')
a.columns = ['item', 'value']
a.sort_index(inplace=True)

I'd like to arrive to this result

    item    value
level_1
1   a   1
1   b   12
2   a   2
2   b   0
3   a   0
3   b   14
4   a   3
4   b   14
5   a   5
5   b   14
6   a   5'
6   b   14
7   a   5
7   b   14

Notice how the zeros between 2 and 3, and between 12 and 14 remained, but the ending zeros all were forward filled.

See below how I managed to get the indexes of the last non-zero values cleanly, but can't get the rest done.

a.groupby('item').apply(lambda x : [x != 0].index[-1])

Body:
If possible use original DataFrame replace 0 to missing values by DataFrame.mask and then in another mask forward filling only last missing values by ffill, what is tested by back filling with check NaNs:

df = pd.DataFrame({'a': [1, 2, 0, 3, 5, 0, 0], 'b': [12,0 ,14, 0, 0, 0, 0]})
df.index = [1, 2, 3, 4, 5, 6, 7]
print (df)
   a   b
1  1  12
2  2   0
3  0  14
4  3   0
5  5   0
6  0   0
7  0   0

df1 = df.mask(df.eq(0))
df =  df.mask(df1.bfill().isna(), df1.ffill())
print (df)
   a   b
1  1  12
2  2   0
3  0  14
4  3  14
5  5  14
6  5  14
7  5  14

If not, first reshape to original, apply solution aand then reshape back:

df = a.set_index('item', append=True).unstack()
df1 = df.mask(df.eq(0))
df = df.mask(df1.bfill().isna(), df1.ffill()).stack().reset_index(level=1)
print (df)
        item  value
level_1
1          a      1
1          b     12
2          a      2
2          b      0
3          a      0
3          b     14
4          a      3
4          b     14
5          a      5
5          b     14
6          a      5
6          b     14
7          a      5
7          b     14

Per groups similar idea:

def f(x):
    m = x['value'].eq(0)
    s = x['value'].mask(m)
    x['value'] = s.fillna(0).mask(s.bfill().isna(), s.ffill())
    return x

df = a.reset_index().groupby('item').apply(f)
print (df)
    level_1 item  value
0         1    a    1.0
1         1    b   12.0
2         2    a    2.0
3         2    b    0.0
4         3    a    0.0
5         3    b   14.0
6         4    a    3.0
7         4    b   14.0
8         5    a    5.0
9         5    b   14.0
10        6    a    5.0
11        6    b   14.0
12        7    a    5.0
13        7    b   14.0


问:
Case insensitive file search from s3 bucket
I am using the Spring Boot SDK for aws and I want to check my s3 bucket to check if a file exists or not, ignoring the case of the filename. Right now I am searching if the file exits by:

```<code>s3client.doesObjectExist(bucketname,objectname)
</code>```

objectname is the file key for s3 with complete filename at the end. So, what I want to do is: if the file path is a/b/c/d/car.pdf, the above method should return "true," even though the actual file path in s3 is: a/b/c/d/CAR.pdf, a/b/c/d/caR.pdf or a/b/c/D/car.pdf.

答:
```<code>ObjectListing listObjects(String bucketName) throws SdkClientException, AmazonServiceException
</code>```

Returns a list of summary information about the objects in the
  specified buckets. List results are always returned in lexicographic
  (alphabetical) order.

Because buckets can contain a virtually unlimited number of keys, the
  complete results of a list query can be extremely large. To manage
  large result sets, Amazon S3 uses pagination to split them into
  multiple responses. Always check the ObjectListing.isTruncated()
  method to see if the returned listing is complete or if additional
  calls are needed to get more results. Alternatively, use the
  AmazonS3Client.listNextBatchOfObjects(ObjectListing) method as an easy
  way to get the next page of object listings.

The total number of keys in a bucket doesn't substantially affect list
  performance.

So, you can do something like this:

```<code>ObjectListing objectListing = s3client.listObjects("MyBucketName");
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
    // implement some search algorithm to find matching files using objectSummary.getKey()
}
</code>```

Body:
I am using the Spring Boot SDK for aws and I want to check my s3 bucket to check if a file exists or not, ignoring the case of the filename. Right now I am searching if the file exits by:

s3client.doesObjectExist(bucketname,objectname)

objectname is the file key for s3 with complete filename at the end. So, what I want to do is: if the file path is a/b/c/d/car.pdf, the above method should return "true," even though the actual file path in s3 is: a/b/c/d/CAR.pdf, a/b/c/d/caR.pdf or a/b/c/D/car.pdf.

Body:
ObjectListing listObjects(String bucketName) throws SdkClientException, AmazonServiceException

Returns a list of summary information about the objects in the
  specified buckets. List results are always returned in lexicographic
  (alphabetical) order.

Because buckets can contain a virtually unlimited number of keys, the
  complete results of a list query can be extremely large. To manage
  large result sets, Amazon S3 uses pagination to split them into
  multiple responses. Always check the ObjectListing.isTruncated()
  method to see if the returned listing is complete or if additional
  calls are needed to get more results. Alternatively, use the
  AmazonS3Client.listNextBatchOfObjects(ObjectListing) method as an easy
  way to get the next page of object listings.

The total number of keys in a bucket doesn't substantially affect list
  performance.

So, you can do something like this:

ObjectListing objectListing = s3client.listObjects("MyBucketName");
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
    // implement some search algorithm to find matching files using objectSummary.getKey()
}


问:
How to pass data to layouts without passing data to every page controller?
I have a custom layout blade that have multi level navigation menu and 2 page blade that extends the layout. I want to create a side navigation menu that loop through data. So if I created a new side nav, I don't have to mess the layout.

But the problem is, I don't know to pass the data to the layout itself.

For now, I just pass the data on every page controller that I have. I think it would be better if I just pass the data to the layout and call any page that extends the layout without passing the data again on every page controller.

layout blade (user.blade.php)

```<code><li class="nav-item has-treeview">
   <a href="#" class="nav-link">
      <i class="nav-icon fas fa-wifi"></i>
      <p>
         Hotspot Voucher
         <i class="right fas fa-angle-left"></i>
      </p>
   </a>
   <ul class="nav nav-treeview">
      <li class="nav-item has-treeview">
         <a href="#" class="nav-link">
            <i class="far fa-circle nav-icon"></i>
            <p>
               Floors
               <i class="right fas fa-angle-left"></i>
            </p>
         </a>
         <ul class="nav nav-treeview floorlist">
            @foreach ($floors as $floor)
            <li class="nav-item">
               <a href="{{ route('home.floor.submit', $floor->floor_id) }}" class="nav-link">
                  <i class="far fa-dot-circle nav-icon"></i>
                  <p>{{ ucwords($floor->floor_name) }}</p>
               </a>
            </li>
            @endforeach
         </ul>
       </li>
    </ul>
 </li>
</code>```

Home blade (home.blade.php)

```<code>@extends('layouts.user')

@section('content')
    <!-- Content Header (Page header) -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0 text-dark">Dashboard</h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item">
                            <a href="{{ route('home') }}">Home</a>
                        </li>
                        <li class="breadcrumb-item active">Dashboard</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <div class="panel panel-default">
                        <div class="panel-body">
                            @component('components.who')
                            @endcomponent
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- /.content -->
@endsection
</code>```

Floor Blade (floor.blade.php)

```<code>@extends('layouts.user')

@section('content')
    <!-- Content Header (Page header) -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0 text-dark">{{ ucwords($get_floor_name) }}</h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item">
                            <a href="{{ route('home') }}">Home</a>
                        </li>
                        <li class="breadcrumb-item">
                            <a href="{{ route('home') }}">Dashboard</a>
                        </li>
                        <li class="breadcrumb-item active">{{ ucwords($get_floor_name) }}</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <div class="panel panel-default">
                        <div class="panel-body">
                            @foreach ($get_rooms as $get_room)
                                {{ ucwords($get_room->rooms_name) }}
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- /.content -->
@endsection
</code>```

HomeController

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Floor;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where('floors.co_id', Auth::user()->co_id)
                ->get();

        return view('home')->with('floors', $floors);
    }
}
</code>```

FloorController

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Floor;
use App\Room;

class FloorController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($fid)
    {

       $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where('floors.co_id', Auth::user()->co_id)
                ->get();

        $get_floor_details = Floor::where(['floors.co_id' => Auth::user()->co_id, 'id' => $fid])->get();

        foreach($get_floor_details as $get_floor)
        {
            $get_floor_name = $get_floor->name;
        }

        $get_rooms = Room::select(
            'rooms.id AS room_id',
            'rooms.name AS rooms_name',
            'floors.name AS get_floor_name'
            )
            ->join('floors', 'floors.id', '=', 'rooms.floor_id')
            ->where(['rooms.co_id' => Auth::user()->co_id, 'rooms.floor_id' => $fid])
            ->get();

        $data = [
                'floors' => $floors,
                'get_floor_name' => $get_floor_name,
                'get_rooms' => $get_rooms
        ];

        return view('floor')->with($data);
    }
}
</code>```

@Andy Song solution

```<code><?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use View;
use Auth;
use App\Floor;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer('layouts.user', function ($view)
        {
            $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where(['co_id' => Auth::user()->co_id])
                ->get();
            $view->with('floors', $floors);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
</code>```

答:
Instead of returning variables from everywhere use View::share() at one location (perhaps in index()):

```<code>use View;

//...

View::share('floors', $floors);
</code>```

Body:
I have a custom layout blade that have multi level navigation menu and 2 page blade that extends the layout. I want to create a side navigation menu that loop through data. So if I created a new side nav, I don't have to mess the layout.

But the problem is, I don't know to pass the data to the layout itself.

For now, I just pass the data on every page controller that I have. I think it would be better if I just pass the data to the layout and call any page that extends the layout without passing the data again on every page controller.

layout blade (user.blade.php)

         Hotspot Voucher

               Floors

            @foreach ($floors as $floor)

               floor_id) }}" class="nav-link">

{{ ucwords($floor->floor_name) }}

            @endforeach

Home blade (home.blade.php)

@extends('layouts.user')

@section('content')

Dashboard

                            Home

Dashboard

                            @component('components.who')
                            @endcomponent

@endsection

Floor Blade (floor.blade.php)

@extends('layouts.user')

@section('content')

{{ ucwords($get_floor_name) }}

                            Home

                            Dashboard

{{ ucwords($get_floor_name) }}

                            @foreach ($get_rooms as $get_room)
                                {{ ucwords($get_room->rooms_name) }}
                            @endforeach

@endsection

HomeController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Floor;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where('floors.co_id', Auth::user()->co_id)
                ->get();

        return view('home')->with('floors', $floors);
    }
}

FloorController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Floor;
use App\Room;

class FloorController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($fid)
    {

       $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where('floors.co_id', Auth::user()->co_id)
                ->get();

        $get_floor_details = Floor::where(['floors.co_id' => Auth::user()->co_id, 'id' => $fid])->get();

        foreach($get_floor_details as $get_floor)
        {
            $get_floor_name = $get_floor->name;
        }

        $get_rooms = Room::select(
            'rooms.id AS room_id',
            'rooms.name AS rooms_name',
            'floors.name AS get_floor_name'
            )
            ->join('floors', 'floors.id', '=', 'rooms.floor_id')
            ->where(['rooms.co_id' => Auth::user()->co_id, 'rooms.floor_id' => $fid])
            ->get();

        $data = [
                'floors' => $floors,
                'get_floor_name' => $get_floor_name,
                'get_rooms' => $get_rooms
        ];

        return view('floor')->with($data);
    }
}

@Andy Song solution

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use View;
use Auth;
use App\Floor;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer('layouts.user', function ($view)
        {
            $floors = Floor::select(
                'floors.id AS floor_id',
                'floors.name AS floor_name'
                )
                ->where(['co_id' => Auth::user()->co_id])
                ->get();
            $view->with('floors', $floors);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Body:
Instead of returning variables from everywhere use View::share() at one location (perhaps in index()):

use View;

//...

View::share('floors', $floors);