问:
Native messaging host in Edge browser
The new Microsoft Edge program is now open to accept chromium-based extensions for the new Microsoft Edge (ver. 77 or above). I have tested my chrome extension on Edge browser and it gets installed in Edge browser. I am trying to reuse the native host in Edge browser which is developed for Chrome browser. But somehow it is not working.

Does anyone has any idea about how to support the chrome native host in Edge browser? or do I need to implement the native host by using UWP?

I have tried communicationg with native host from my edge extension but getting the "Unchecked runtime.lastError: Specified native messaging host not found." Error.
code from .js file

```<code>var hostname = "com.microsoft.edge.myExtension";
port = chrome.runtime.connectNative(hostname);
</code>```

Manifest(com.microsoft.edge.myExtension.json) file for my native host

```<code>    "name": "com.microsoft.edge.myExtension",
    "description": "My Native Host",
    "path": "C:\\EdgeNativeHost.exe",
    "type": "stdio",
    "allowed_origins": [
        "extension://pbdancjikoidhjcgkfpipggnhlackjpe/"
    ]
}
</code>```

Added registry key by running shell command

```<code>REG ADD "HKCU\Software\Microsoft\Edge\NativeMessagingHosts\com.microsoft.edge.myExtension" /ve /t REG_SZ /d "C:\com.microsoft.edge.myExtension.json" /f
</code>```

Please let me know what's the wrong with me?

答:
Extensions written for Chromium, in most cases, run on Microsoft (Chromium) Edge with minimal changes. You could refer to this guide about how to port a Chrome Extension to Microsoft (Chromium) Edge.

You should check if you have used the following extension APIs which are not supported by Microsoft Edge:

The extension APIs and manifest keys supported by Chrome are code-compatible with Microsoft (Chromium) Edge. However, Microsoft Edge does not support the following Extension APIs:

chrome.gcm

chrome.identity.getAccounts

chrome.identity.getAuthToken

chrome.identity.getProfileUserInfo

chrome.instanceID

You should also re-brand the Extension for Microsoft Edge if you are using Chrome in the name or description of your Extension.

For native messaging host, you should especially note:

If your Extension exchanges messages with a native application using chrome.runtime.connectNative API, ensure that you set allowedorigins to "extension://[Microsoft-Catalog-extensionID]" in your native messaging host manifest file. This enables the app to identify the Extension.

For more information, you could refer to this article. The native messaging host location is also a little different from Chrome Extension. Google\Chrome in the registry key should be Microsoft\Edge.

Title: Native messaging host in Edge browser

Body:
The new Microsoft Edge program is now open to accept chromium-based extensions for the new Microsoft Edge (ver. 77 or above). I have tested my chrome extension on Edge browser and it gets installed in Edge browser. I am trying to reuse the native host in Edge browser which is developed for Chrome browser. But somehow it is not working.

Does anyone has any idea about how to support the chrome native host in Edge browser? or do I need to implement the native host by using UWP?

I have tried communicationg with native host from my edge extension but getting the "Unchecked runtime.lastError: Specified native messaging host not found." Error.
code from .js file

var hostname = "com.microsoft.edge.myExtension";
port = chrome.runtime.connectNative(hostname);

Manifest(com.microsoft.edge.myExtension.json) file for my native host

    "name": "com.microsoft.edge.myExtension",
    "description": "My Native Host",
    "path": "C:\\EdgeNativeHost.exe",
    "type": "stdio",
    "allowed_origins": [
        "extension://pbdancjikoidhjcgkfpipggnhlackjpe/"
    ]
}

Added registry key by running shell command

REG ADD "HKCU\Software\Microsoft\Edge\NativeMessagingHosts\com.microsoft.edge.myExtension" /ve /t REG_SZ /d "C:\com.microsoft.edge.myExtension.json" /f

Please let me know what's the wrong with me?


来源: stackexchange

问:
Get data from RowCommand
I have a grid which shows product versions and have a few link buttons like edit, delete, preview etc.
On click of the edit button I want to get the Product ID and Version ID and redirect to some xyz.aspx page where the product details can be edited.

Here is how my Grid looks:

<asp:GridView ID="grdBindVersion" runat="server" AutoGenerateColumns="false"
            onrowcommand="grdBindVersion_RowCommand" >

        <RowStyle BorderStyle="Solid" BorderWidth="1px" />
        <Columns>
            <asp:BoundField datafield="HistoryId"  HeaderText="Version ID.">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

            <asp:BoundField datafield="Title" HeaderText="Title">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

             <asp:TemplateField HeaderText = "Edit">
                   <ItemTemplate>

                       <asp:LinkButton ID="Edit" runat="server" CommandArgument='<%# Container.DataItem %>'  CommandName ="Add">Edit</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Delete">
                   <ItemTemplate>
                           <asp:LinkButton ID="Delete" runat="server">Delete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Sub Page">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddSubPage" runat="server">Add Sub Page</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Rank">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddRank" runat="server">Add Rank</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Approve/DisApprove">
                   <ItemTemplate>
                           <asp:LinkButton ID="ApproveStatus" runat="server">Approve/DisApprove</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Complete">
                   <ItemTemplate>
                            <asp:LinkButton ID="Complete" runat="server">Complete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Preview">
                   <ItemTemplate>
                            <asp:LinkButton ID="Preview" runat="server">Preview</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Comment">
                   <ItemTemplate>
                            <asp:LinkButton ID="Comment" runat="server">Comment</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

        </Columns>
        </asp:GridView>
```

I am tracking the clicking on the link button  in the RowCommand event of the GridView.
Here i want to get the VersionID and ProductID and then redirect to another page.
Please help me.
I am really new to coding.
I did a bit of Google but none of the solutions are helping me.

答:
```<code>protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Edit")
    {
        GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
        // row contains current Clicked Gridview Row
        String VersionId = row.Cells[CellIndex].Text;
        .............
        .............
        //e.CommandArgument  -- this return Data Key Value
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get data from RowCommand

Body:
I have a grid which shows product versions and have a few link buttons like edit, delete, preview etc.
On click of the edit button I want to get the Product ID and Version ID and redirect to some xyz.aspx page where the product details can be edited.

Here is how my Grid looks:

<asp:GridView ID="grdBindVersion" runat="server" AutoGenerateColumns="false"
            onrowcommand="grdBindVersion_RowCommand" >

        <RowStyle BorderStyle="Solid" BorderWidth="1px" />
        <Columns>
            <asp:BoundField datafield="HistoryId"  HeaderText="Version ID.">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

            <asp:BoundField datafield="Title" HeaderText="Title">
                        <HeaderStyle CssClass="grid"></HeaderStyle>
            </asp:BoundField>

             <asp:TemplateField HeaderText = "Edit">
                   <ItemTemplate>

                       <asp:LinkButton ID="Edit" runat="server" CommandArgument='<%# Container.DataItem %>'  CommandName ="Add">Edit</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Delete">
                   <ItemTemplate>
                           <asp:LinkButton ID="Delete" runat="server">Delete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Sub Page">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddSubPage" runat="server">Add Sub Page</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Add Rank">
                   <ItemTemplate>
                            <asp:LinkButton ID="AddRank" runat="server">Add Rank</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Approve/DisApprove">
                   <ItemTemplate>
                           <asp:LinkButton ID="ApproveStatus" runat="server">Approve/DisApprove</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Complete">
                   <ItemTemplate>
                            <asp:LinkButton ID="Complete" runat="server">Complete</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Preview">
                   <ItemTemplate>
                            <asp:LinkButton ID="Preview" runat="server">Preview</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

              <asp:TemplateField HeaderText = "Comment">
                   <ItemTemplate>
                            <asp:LinkButton ID="Comment" runat="server">Comment</asp:LinkButton>
                   </ItemTemplate>
              </asp:TemplateField>

        </Columns>
        </asp:GridView>

I am tracking the clicking on the link button  in the RowCommand event of the GridView.
Here i want to get the VersionID and ProductID and then redirect to another page.
Please help me.
I am really new to coding.
I did a bit of Google but none of the solutions are helping me.


问:
Is it possible to select an anchor tag which contains a h1 which contains the text "Visit Site"?
I am using Cypress.io to test my startup's website and would like to select a specific anchor tag.

However, that anchor tag does not have any unique attribute I can use to identify it, therefore I would like to use a child h1 tag containing the text "Visit Site" to help with identifying the anchor tag.

```<code><a href="/blablabla" target="_blank" rel="noopener noreferrer canonical">
  <h1>Visit Site</h1>
</a>
</code>```

I would not be able to use the href attribute to help identify the anchor tag, as the written test would be used across other pages of the same structure but of different content.

My issue is that I do not know if its possible to select an element based on whether it contains an element of a certain text.

答:
For the example... I prevented the default behavior of a link (preventDefault()).

So using the :contains() selector, you can target the link containing a particular text.

It will target ALL of the elements matching... But in practice, if you dont iterate the collection, you will have the first one as a result.

Inn the example here... It throws the parent element of a clicked element. So there is no issue. All depends on what you want to do. ;)

Then... Get the parent() of that target to get the href attribute of the anchor.

$("a h1:contains('Visit Site')").click(function(e){
 e.preventDefault();
 console.log("YEAH! " + $(this).parent().attr("href"))
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <h1>Visit Site</h1>

  <h1>Wrong link</h1>

  <h1>Other link</h1>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Cypress.io to test my startup's website and would like to select a specific anchor tag.

However, that anchor tag does not have any unique attribute I can use to identify it, therefore I would like to use a child h1 tag containing the text "Visit Site" to help with identifying the anchor tag.

Visit Site

I would not be able to use the href attribute to help identify the anchor tag, as the written test would be used across other pages of the same structure but of different content.

My issue is that I do not know if its possible to select an element based on whether it contains an element of a certain text.

Body:
For the example... I prevented the default behavior of a link (preventDefault()).

So using the :contains() selector, you can target the link containing a particular text.

It will target ALL of the elements matching... But in practice, if you dont iterate the collection, you will have the first one as a result.

Inn the example here... It throws the parent element of a clicked element. So there is no issue. All depends on what you want to do. ;)

Then... Get the parent() of that target to get the href attribute of the anchor.

$("a h1:contains('Visit Site')").click(function(e){
 e.preventDefault();
 console.log("YEAH! " + $(this).parent().attr("href"))
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="/blablabla" target="_blank" rel="noopener noreferrer canonical">
  <h1>Visit Site</h1>
</a>
<a href="/hummphh" target="_blank" rel="noopener noreferrer canonical">
  <h1>Wrong link</h1>
</a>
<a href="/hooo" target="_blank" rel="noopener noreferrer canonical">
  <h1>Other link</h1>
</a>


问:
Use of using statement for Entity Framework DbContext in foreach-loop
There is a parser that parses a text file which contains object definition. The object definitions in the text file have a placeholder handle key. The place holder handle needs to be replaced with actual value by looking up the handle value in DB. In my application I am making use of the Entity framework Core for working with the DB.

The parser returns one object at a time, and I am looking up the handle and other properties in the DB one at a time. This is how the code looks so far:

```<code>    IEnumerable<ObjectInfo> GetNextContent();

    IEnumerable<ObjectInfo> GetNextObjectInfo()
    {

        foreach (var item in parser.GetNextContent())
        {
            using (var dbContext = new ContentDbContext())
            {
                string key = item.Key;

                string id = dbContext.Contents.Find(key).ObjectId;
                item.Id = id;
                // Assign other fields...

                yield return item;
            }
        }
    }
</code>```

The question that I have is that in the code above, the 'using' block is within the foreach loop.
Is this a right thing to do?
The other thought is that I can take the 'using' block outside of the foreach-loop but then I am not sure how would that play out with the iterator in the code.

答:
You should move ContentDbContext into outside for better performance.

This is simply because You just need one context per request.

One DbContext per web request... why?

```<code>using (var dbContext = new ContentDbContext())
 {
    foreach (var item in parser.GetNextContent())
     {
            string key = item.Key;

            string id = dbContext.Contents.Find(key).ObjectId;
            item.Id = id;
            // Assign other fields...

            yield return item;
        }
    }
</code>```

Updated

You might also join then make sure that fetch all data at a time

```<code>// You need to fetch all `item.Key` from `parser.GetNextContent()` to get all data in `dbContext.Contents`
var keys = parser.GetNextContent().Select(p => p.Key).ToArray();

var result = (from content in dbContext.Contents
              join key in keys on content.Id equals key
              select new
{
  Id = content.ObjectId,
  //....
}
</code>```

If you are use C# 8, using statement may be as below:

```<code> using var dbContext = new ContentDbContext();

 foreach (var item in parser.GetNextContent())
 {
        string key = item.Key;

        string id = dbContext.Contents.Find(key).ObjectId;
        item.Id = id;
        // Assign other fields...

        yield return item;
  }
</code>```

Body:
There is a parser that parses a text file which contains object definition. The object definitions in the text file have a placeholder handle key. The place holder handle needs to be replaced with actual value by looking up the handle value in DB. In my application I am making use of the Entity framework Core for working with the DB.

The parser returns one object at a time, and I am looking up the handle and other properties in the DB one at a time. This is how the code looks so far:

    IEnumerable<ObjectInfo> GetNextContent();

    IEnumerable<ObjectInfo> GetNextObjectInfo()
    {

        foreach (var item in parser.GetNextContent())
        {
            using (var dbContext = new ContentDbContext())
            {
                string key = item.Key;

                string id = dbContext.Contents.Find(key).ObjectId;
                item.Id = id;
                // Assign other fields...

                yield return item;
            }
        }
    }

The question that I have is that in the code above, the 'using' block is within the foreach loop.
Is this a right thing to do?
The other thought is that I can take the 'using' block outside of the foreach-loop but then I am not sure how would that play out with the iterator in the code.

Body:
You should move ContentDbContext into outside for better performance.

This is simply because You just need one context per request.

One DbContext per web request... why?

using (var dbContext = new ContentDbContext())
 {
    foreach (var item in parser.GetNextContent())
     {
            string key = item.Key;

            string id = dbContext.Contents.Find(key).ObjectId;
            item.Id = id;
            // Assign other fields...

            yield return item;
        }
    }

Updated

You might also join then make sure that fetch all data at a time

// You need to fetch all `item.Key` from `parser.GetNextContent()` to get all data in `dbContext.Contents`
var keys = parser.GetNextContent().Select(p => p.Key).ToArray();

var result = (from content in dbContext.Contents
              join key in keys on content.Id equals key
              select new
{
  Id = content.ObjectId,
  //....
}

If you are use C# 8, using statement may be as below:

 using var dbContext = new ContentDbContext();

 foreach (var item in parser.GetNextContent())
 {
        string key = item.Key;

        string id = dbContext.Contents.Find(key).ObjectId;
        item.Id = id;
        // Assign other fields...

        yield return item;
  }


问:
VBA: Cut a range of columns and paste it to bottom of data in first three columns
I have data in an excel file in which there is data for separated into three columns:
Date (column A), number (column B), number (column C).

This sequence gets repeated to column UI. I would like to cut the data in every three columns and paste it the last row + 1 in column a,b,c so I only have three columns of data. I am having trouble accounting for three columns of data in my code.

```<code>`Sub movedata()
Application.ScreenUpdating = False

Dim i As Integer

Set ws = ThisWorkbook.Sheets("Cashflow Chart")
    With ws
        lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column 'get last column using Row 1
        For i = 4 To lastcolumn  'loop though each column starting from 4
            Set Rng = .Range(.Cells(1, i), .Cells(.Cells(.Rows.Count, i).End(xlUp).Row, i)) 'set range to copy
            .Range("A" & .Cells(.Rows.Count, "A").End(xlUp).Row + 1).Resize(Rng.Rows.Count).Value = Rng.Value

    End With
    Application.ScreenUpdating = True
End Sub`
</code>```

答:
Fundimentally, change the For loop to step by 3's

Also, moving the data via a Variant Array will be faster, plus a few other things

```<code>Sub MoveData()
    Application.ScreenUpdating = False

    Dim i As Long
    Dim Data As Variant
    Dim LastColumn As Long
    Dim InsertRow As Long

    With ThisWorkbook.Sheets("Cashflow Chart")
        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column 'get last column using Row 1
        InsertRow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row 'get insert point using column A
        For i = 4 To LastColumn Step 3  'loop though each column starting from 4, step by 3
            Data = .Range(.Cells(1, i + 2), .Cells(.Rows.Count, i).End(xlUp)).Value 'copy range to variant array
            .Cells(InsertRow, 1).Resize(UBound(Data, 1), 3).Value = Data 'place data at end of column A data
            InsertRow = InsertRow + UBound(Data, 1) 'increment insert point
        Next
        .Cells(1, 4).Resize(InsertRow, LastColumn - 3).ClearContents 'clear old data
    End With

    Application.ScreenUpdating = True
End Sub
</code>```

Body:
I have data in an excel file in which there is data for separated into three columns:
Date (column A), number (column B), number (column C).

This sequence gets repeated to column UI. I would like to cut the data in every three columns and paste it the last row + 1 in column a,b,c so I only have three columns of data. I am having trouble accounting for three columns of data in my code.

`Sub movedata()
Application.ScreenUpdating = False

Dim i As Integer

Set ws = ThisWorkbook.Sheets("Cashflow Chart")
    With ws
        lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column 'get last column using Row 1
        For i = 4 To lastcolumn  'loop though each column starting from 4
            Set Rng = .Range(.Cells(1, i), .Cells(.Cells(.Rows.Count, i).End(xlUp).Row, i)) 'set range to copy
            .Range("A" & .Cells(.Rows.Count, "A").End(xlUp).Row + 1).Resize(Rng.Rows.Count).Value = Rng.Value

    End With
    Application.ScreenUpdating = True
End Sub`

Body:
Fundimentally, change the For loop to step by 3's

Also, moving the data via a Variant Array will be faster, plus a few other things

Sub MoveData()
    Application.ScreenUpdating = False

    Dim i As Long
    Dim Data As Variant
    Dim LastColumn As Long
    Dim InsertRow As Long

    With ThisWorkbook.Sheets("Cashflow Chart")
        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column 'get last column using Row 1
        InsertRow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row 'get insert point using column A
        For i = 4 To LastColumn Step 3  'loop though each column starting from 4, step by 3
            Data = .Range(.Cells(1, i + 2), .Cells(.Rows.Count, i).End(xlUp)).Value 'copy range to variant array
            .Cells(InsertRow, 1).Resize(UBound(Data, 1), 3).Value = Data 'place data at end of column A data
            InsertRow = InsertRow + UBound(Data, 1) 'increment insert point
        Next
        .Cells(1, 4).Resize(InsertRow, LastColumn - 3).ClearContents 'clear old data
    End With

    Application.ScreenUpdating = True
End Sub


问:
localhost chrome on catalina
I can not get localhost to work on chrome after upgrading to macOS Catalina.  I spent a lot of time trying to figure out why I was getting this message </p>

```<code>localhost normally uses encryption to protect your information. When Google Chrome tried to connect to localhost this time, the website sent back unusual and incorrect credentials. This may happen when an attacker is trying to pretend to be localhost, or a Wi-Fi sign-in screen has interrupted the connection. Your information is still secure because Google Chrome stopped the connection before any data was exchanged.

You cannot visit localhost right now because the website sent scrambled credentials that Google Chrome cannot process. Network errors and attacks are usually temporary, so this page will probably work later.
</code>```

<p>(I wish I had taken a screen shot) </p>

答:
OS X Catalina increased the requirements for an SSL/TLS certificate to be acceptable around November 2019. Notably, certificates now need a "Subject Alternative Name" section, which was not previously required. Note that this is an OS-level requirement and not specific to a single browser (although it doesn't affect FireFox because Firefox doesn't use the OS security stack).

The solution to your issue is how you generate the SSL certificate, not anything you can do as a Chrome user. This particular issue can not be bypassed by clicking through a Chrome warning message.

Also note that fixing this issue for OS X may make the certificate unusable on Chrome + Linux (I have linked to WebPack Dev Server's GitHub Issue discussion of this issue).

Title: localhost chrome on catalina

Body:
I can not get localhost to work on chrome after upgrading to macOS Catalina.  I spent a lot of time trying to figure out why I was getting this message

localhost normally uses encryption to protect your information. When Google Chrome tried to connect to localhost this time, the website sent back unusual and incorrect credentials. This may happen when an attacker is trying to pretend to be localhost, or a Wi-Fi sign-in screen has interrupted the connection. Your information is still secure because Google Chrome stopped the connection before any data was exchanged.

You cannot visit localhost right now because the website sent scrambled credentials that Google Chrome cannot process. Network errors and attacks are usually temporary, so this page will probably work later.

(I wish I had taken a screen shot)


问:
When I open my project, I get this message: "This solution is offline. [Team Foundation //https://xxxxxxxxxxxx/tfs/applications"
This solution is offline.  [Team Foundation Server: http://xxxxxxxxxx/tfs/applications]
The solution was offline during its previous session and will remain offline.

What kinds of problems would cause the above error?
And when this happens, there is no check-in option and trying to save individual files results in a message that says the file you're trying to save is write protected. Do you wish to override? I can still save files by responding "yes." But all this is very confusing and dangerous. What causes this condition?

答:
What kinds of problems would cause the above error?

I assume you're using a non-git TFS workspace (i.e. using TFS' old-school centralized source-control service that essentially is Microsoft's not-invented-here take on SVN.

TFS workspaces come in two flavours: "Local" and "Server". A "Local" workspace is kinda like a git repo in that it allows you to make check-ins while working offline but it has limitations. A "Server" workspace requires you to have an active and reliable connection to the TFS server and you cannot make check-ins while disconnected (you can still make changes, of course, but you can't save them to TFS).

I assume you have a "Server" workspace instead of a "Local" workspace, hence the error message.

And when this happens, there is no check-in option and trying to save individual files results in a message that says the file you're trying to save is write protected.

Correct. But you can always remove the Read-only flag on your files in the filesystem and edit the files and do a manual sync to make a TFS check-in after you've reconnected. The files are marked as Read-only because TFS is designed around locking files and checking-out files from source-control, so it wants to discourage you from editing files that haven't been checked-out. If you do edit a file that hasn't been checked-out you can still include it in a check-in but you need to retroactively check it out when you reconnect to the TFS server.

I can still save files by responding "yes." But all this is very confusing and dangerous.

It's not really dangerous - the whole point of a version-control system is to get the freedom to make arbitrary changes and be able to rollback (or branch) whenever you want (except doing so using TFS rather than git (especially when offline), is just a rather huge PITA).

To resolve this situation:

Open Visual Studio (you don't need to open a project/solution first).

Assuming you're using VS2015 or later, open Team Explorer.

Ensure Team Explorer is in TFS mode instead of git mode:

When in git mode you'll see buttons like "Changes", "Branches", "Sync" which have a red highlight.

When in TFS mode you'll see buttons like "My Work", "Pending Changes", and "Source Control Explorer".

If it's in git mode, switch to TFS mode by clicking the Connect button in the tool windows' toolbar at the top and select your TFS server.

You may also need to go Tools > Options > Source Control > Current plugin: "Visual Studio Team Foundation Server".

After reconnecting to TFS, reopen your project/solution.

VS should detect that you made changes while offline and offer to create a pending check-in for you (and automatically check-out any edited files). If not, open "Source Control Explorer" and manually run the "Compare Folders" tool and check-out any files it detects as changed before making your new check-in.

You may also need to go File > Source Control > "Go online"

Here's a screenshot from Visual Studio 2008 (it's the only screenshot I could find, sorry - but the menu layout is identical):

After you've done this and made your check-in, it's very important that you visit your local fishmonger and buy a large trout, then visit your project manager and give them a jolly good slapping with it for requiring their team to use TFS in 2020. Even Microsoft uses git internally.


问:
Javascript function executed before defined
I am learning Javascript and have some Python experience. The below confuses me massively. How is it that you can call a function before it has been defined?

My assumption is that check_user_age() would not work because it is not defined until further down the script.

How does this work?

```<code>'''
<!doctype html>
<html>

<body onload="check_user_age()" style="position:absolute">
    <h1>Spiritueux Wines and Liquors</h1>
    <script>
        function check_user_age() {
            if (age_of_user() < 18)
                alert("You are too young to buy alcohol.");
        }

        function age_of_user() {
            var age = prompt("What is your age?");
            return age;
        }
    </script>
</body>

</html>
'''
</code>```

答:
@CertainPerformane have already answered the question , but there is one more catch here.  output from the prompt is a string.Though comparison operator like < & > will coercive the the value to primitives but better use parseInt to convert to number and then compare

function check_user_age() {
  if (age_of_user() < 18)
    alert("You are too young to buy alcohol.");
}

function age_of_user() {
  var age = prompt("What is your age?");
  return parseInt(age, 10);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="check_user_age()" style="position:absolute">
  <h1>Spiritueux Wines and Liquors</h1>
</body></code>```

Body:
I am learning Javascript and have some Python experience. The below confuses me massively. How is it that you can call a function before it has been defined?

My assumption is that check_user_age() would not work because it is not defined until further down the script.

How does this work?

'''
<!doctype html>

Spiritueux Wines and Liquors

'''

Body:
@CertainPerformane have already answered the question , but there is one more catch here.  output from the prompt is a string.Though comparison operator like < & > will coercive the the value to primitives but better use parseInt to convert to number and then compare

function check_user_age() {
  if (age_of_user() < 18)
    alert("You are too young to buy alcohol.");
}

function age_of_user() {
  var age = prompt("What is your age?");
  return parseInt(age, 10);
}

<body onload="check_user_age()" style="position:absolute">
  <h1>Spiritueux Wines and Liquors</h1>
</body>


问:
Fabricjs - selection only via border
I'm using Fabric.js to draw some rectangles on a canvas. The default behavior is that clicking inside a rectangle selects it. How can I change the behavior such that it is only selected when clicking on the border of the rectangle?

Clicking inside the rectangle but not on the border should do nothing.

You can see this behavior by drawing a rectangle on a TradingView.com chart

It there an option for this in fabric, and if not how could I go around implementing it?

答:
This approach overrides the _checkTarget method within FabricJS to reject clicks that are more than a specified distance from the border (defined by the clickableMargin variable).

//sets the width of clickable area
var clickableMargin = 15;

var canvas = new fabric.Canvas("canvas");

canvas.add(new fabric.Rect({
  width: 150,
  height: 150,
  left: 25,
  top: 25,
  fill: 'green',
  strokeWidth: 0
}));

//overrides the _checkTarget method to add check if point is close to the border
fabric.Canvas.prototype._checkTarget = function(pointer, obj, globalPointer) {
  if (obj &&
      obj.visible &&
      obj.evented &&
      this.containsPoint(null, obj, pointer)){
    if ((this.perPixelTargetFind || obj.perPixelTargetFind) && !obj.isEditing) {
      var isTransparent = this.isTargetTransparent(obj, globalPointer.x, globalPointer.y);
      if (!isTransparent) {
        return true;
      }
    }
    else {
     var isInsideBorder = this.isInsideBorder(obj);
     if(!isInsideBorder) {
       return true;
      }
    }
  }
}

fabric.Canvas.prototype.isInsideBorder = function(target) {
   var pointerCoords = target.getLocalPointer();
   if(pointerCoords.x > clickableMargin &&
     pointerCoords.x < target.getScaledWidth() - clickableMargin &&
     pointerCoords.y > clickableMargin &&
     pointerCoords.y < target.getScaledHeight() - clickableMargin) {
     return true;
   }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
<canvas id="canvas" height="300" width="400"></canvas></code>```

Title: Fabricjs - selection only via border

Body:
This approach overrides the _checkTarget method within FabricJS to reject clicks that are more than a specified distance from the border (defined by the clickableMargin variable).

//sets the width of clickable area
var clickableMargin = 15;

var canvas = new fabric.Canvas("canvas");

canvas.add(new fabric.Rect({
  width: 150,
  height: 150,
  left: 25,
  top: 25,
  fill: 'green',
  strokeWidth: 0
}));

//overrides the _checkTarget method to add check if point is close to the border
fabric.Canvas.prototype._checkTarget = function(pointer, obj, globalPointer) {
  if (obj &&
      obj.visible &&
      obj.evented &&
      this.containsPoint(null, obj, pointer)){
    if ((this.perPixelTargetFind || obj.perPixelTargetFind) && !obj.isEditing) {
      var isTransparent = this.isTargetTransparent(obj, globalPointer.x, globalPointer.y);
      if (!isTransparent) {
        return true;
      }
    }
    else {
     var isInsideBorder = this.isInsideBorder(obj);
     if(!isInsideBorder) {
       return true;
      }
    }
  }
}

fabric.Canvas.prototype.isInsideBorder = function(target) {
   var pointerCoords = target.getLocalPointer();
   if(pointerCoords.x > clickableMargin &&
     pointerCoords.x < target.getScaledWidth() - clickableMargin &&
     pointerCoords.y > clickableMargin &&
     pointerCoords.y < target.getScaledHeight() - clickableMargin) {
     return true;
   }
 }

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
<canvas id="canvas" height="300" width="400"></canvas>


问:
Delete Unique permissions for One-Drive Item through Microsoft Graph
Is there a way perform Delete Unique Permissions from Microsoft Graph API. As we can do this from the UI.

答:
You can delete only not inerited permissions.</p>

```<code>var permissions = await _client
                .Drives[{ driveId }]
                .Items[{ itemId  }]
                .Permissions
                .Request()
                .GetAsync();

            foreach (var p in permissions)
            {
                if (p.InheritedFrom == null)
                {
                    await _client
                        .Drives[{ driveId }]
                        .Items[{ itemId  }]
                        .Permissions[p.Id]
                        .Request()
                        .DeleteAsync();
                }
            }
</code>```

Body:
You can delete only not inerited permissions.

var permissions = await _client
                .Drives[{ driveId }]
                .Items[{ itemId  }]
                .Permissions
                .Request()
                .GetAsync();

            foreach (var p in permissions)
            {
                if (p.InheritedFrom == null)
                {
                    await _client
                        .Drives[{ driveId }]
                        .Items[{ itemId  }]
                        .Permissions[p.Id]
                        .Request()
                        .DeleteAsync();
                }
            }


问:
Add header to every request in Postman in pre-request script
I want to automatically add a header to every request in my whole collection using this pre-request script:

```<code>pm.request.headers.add({
    'key': "myvar",
    'value': pm.environment.get("myvar")
});
</code>```

myvar is an environment variable.

Unfortunately, it doesn't work. Did I miss something?

答:
This certainly works. Loose the inverted commas on key and value </p>

```<code>pm.request.headers.add({
    key: "myvar",
    value: pm.environment.get("myvar")
});
</code>```

Body:
I want to automatically add a header to every request in my whole collection using this pre-request script:

pm.request.headers.add({
    'key': "myvar",
    'value': pm.environment.get("myvar")
});

myvar is an environment variable.

Unfortunately, it doesn't work. Did I miss something?

Body:
This certainly works. Loose the inverted commas on key and value

pm.request.headers.add({
    key: "myvar",
    value: pm.environment.get("myvar")
});


问:
Will I be Charged for a VM instance which was running in a project I shut down?
I have recently shut down a project and I had a VM instance running in that. Will that charge my free trial credit even after shut down??
If yes, will it charge even after deletion(after 30 days of shut down)</p>

答:
Billing will be terminated once the resources are deleted.

This should be roughly coincident with your request to delete the project that contains the resources but there could be slight latency..

Deleting a project deletes the project's resources. It's a blunt but effective way to terminate all a project's resources in a single transaction.


问:
How to parameterise method name in TestNG xml file?
Below is the testng.xml code. here I have test name Test1 and I want to include all the scenarios starting with regression tag (tag is present in cucumber feature file).

I want to parameterise "regression.*" value and want to pass as an argument at run time (Runas testng).

```<code><test name="Test1">
  <groups>
    <run>
      <include name="regression.*"/>
    </run>
  </groups>
</code>```

Can somebody help me with this scenario.

Thanks in advance.....

答:
You should be able to build the dynamic ability to pick and choose a group at runtime using a beanshell as a method selector.

Here's a sample beanshell powered suite xml. In the below sample, we are making use of a JVM argument -DgroupToRun to pass in the name of the groups which we want to be executed.

For more details on how to work with beanshells in TestNG take a look at

The official documentation here

my blog post here

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="false">
    <test name="Test">
        <method-selectors>
            <method-selector>

            </method-selector>
        </method-selectors>
        <classes>
            <class name="organized.chaos.GroupsPlayGround" />
        </classes>
    </test>
</suite>
```

Body:
Below is the testng.xml code. here I have test name Test1 and I want to include all the scenarios starting with regression tag (tag is present in cucumber feature file).

I want to parameterise "regression.*" value and want to pass as an argument at run time (Runas testng).

<test name="Test1">
  <groups>
    <run>
      <include name="regression.*"/>
    </run>
  </groups>

Can somebody help me with this scenario.

Thanks in advance.....

Body:
You should be able to build the dynamic ability to pick and choose a group at runtime using a beanshell as a method selector.

Here's a sample beanshell powered suite xml. In the below sample, we are making use of a JVM argument -DgroupToRun to pass in the name of the groups which we want to be executed.

For more details on how to work with beanshells in TestNG take a look at

The official documentation here

my blog post here

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="false">
    <test name="Test">
        <method-selectors>
            <method-selector>
                <script language="beanshell">
                <![CDATA[
                    whatGroup = System.getProperty("groupToRun");
                    groups.containsKey(whatGroup);
                ]]>
                </script>
            </method-selector>
        </method-selectors>
        <classes>
            <class name="organized.chaos.GroupsPlayGround" />
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->


问:
Giving access to s3 having a specific "tag" using AWS IAM roles and policy
I want to create an AWS IAM Policy, such that the attached role should have access to all S3 buckets having the Tag , "Team = devops". I tried the following JSON file, but it wont work.</p>

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "arn:aws:s3:::*",
            "Condition": {
                "StringEquals": {"s3:ResourceTag/Team": "devops"}
            }
        }
    ]
}
</code>```

答:
As per Available Condition Keys, s3:ResourceTag is not available for S3 conditions.

The predefined keys available for specifying conditions in an Amazon S3 access policy can be classified as follows:

As in Object Tagging and Access Control Policies, access control per object is possible with s3:ExistingObjectTag condition key.

The following permissions policy grants a user permission to read objects, but the condition limits the read permission to only objects that have the following specific tag key and value.

  security : public

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect":     "Allow",
      "Action":     "s3:GetObject",
      "Resource":    "arn:aws:s3:::examplebucket/*",
      "Principal":   "*",
      "Condition": {  "StringEquals": {"s3:ExistingObjectTag/security": "public" } }
    }
  ]
}
</code>```

Body:
I want to create an AWS IAM Policy, such that the attached role should have access to all S3 buckets having the Tag , "Team = devops". I tried the following JSON file, but it wont work.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "arn:aws:s3:::*",
            "Condition": {
                "StringEquals": {"s3:ResourceTag/Team": "devops"}
            }
        }
    ]
}

Body:
As per Available Condition Keys, s3:ResourceTag is not available for S3 conditions.

The predefined keys available for specifying conditions in an Amazon S3 access policy can be classified as follows:

As in Object Tagging and Access Control Policies, access control per object is possible with s3:ExistingObjectTag condition key.

The following permissions policy grants a user permission to read objects, but the condition limits the read permission to only objects that have the following specific tag key and value.

  security : public

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect":     "Allow",
      "Action":     "s3:GetObject",
      "Resource":    "arn:aws:s3:::examplebucket/*",
      "Principal":   "*",
      "Condition": {  "StringEquals": {"s3:ExistingObjectTag/security": "public" } }
    }
  ]
}


问:
React Native - Promise returns undefined
I have a js file that returns whether I have internet connection or not, and then in another js I have an if else statement that gets that value. The thing is im getting connection = undefined.</p>

```<code>import React from 'react';
import NetInfo from "@react-native-community/netinfo";

const isConnected = function() {
  NetInfo.fetch().then(state => {
    console.log("state.isConnected: ", state.isConnected)
    return state.isConnected
  });
}

export default isConnected;
</code>```

```<code>import isConnected from '../../src/utils/internetConnection';

async checking(){
   var connection = await isConnected()
   console.log("connection : ", connection)
   if (connection){
      return true
   }

   Alert.alert("There is no Internet connection")
   return
}
</code>```

答:
Because you didn't return anything in isConnected function. let's try this
code:

const isConnected = async function() {
  const { isConnected } = await NetInfo.fetch()

  return isConnected;
}
```

<pre class="lang-js prettyprint-override"><code>async checking(){
  var connection = await isConnected()

  return Boolean(connection)
}
</code>```

Body:
I have a js file that returns whether I have internet connection or not, and then in another js I have an if else statement that gets that value. The thing is im getting connection = undefined.

import React from 'react';
import NetInfo from "@react-native-community/netinfo";

const isConnected = function() {
  NetInfo.fetch().then(state => {
    console.log("state.isConnected: ", state.isConnected)
    return state.isConnected
  });
}

export default isConnected;

import isConnected from '../../src/utils/internetConnection';

async checking(){
   var connection = await isConnected()
   console.log("connection : ", connection)
   if (connection){
      return true
   }

   Alert.alert("There is no Internet connection")
   return
}

Body:
Because you didn't return anything in isConnected function. let's try this
code:

const isConnected = async function() {
  const { isConnected } = await NetInfo.fetch()

  return isConnected;
}

async checking(){
  var connection = await isConnected()

  return Boolean(connection)
}


问:
DataBricks - save changes back to DataLake (ADLS Gen2)
I have legacy data stored as CSV in an Azure DataLake Gen2 storage account. I'm able to connect to this and interrogate it using DataBricks. I have a requirement to remove certain records once their retention period expires, or if a GDPR "right to be forgotten" needs applying to the data.

Using Delta I can load a CSV into a Delta table and use SQL to locate and delete the required rows, but what is the best way to save these changes? Ideally back to the original file, so that the data is removed from the original. I've used the LOCATION option when creating the Delta table to persist the generated Parquet format files to the DataLake but it would be nice to keep it in the original CSV format.

Any advice appreciated.

答:
If you are running the delete operations periodically then it is costly to save file in csv, As every time you are reading the file and transforming the dataframe to Delta and then query on it and finally after filtering the records you are again saving it to csv and deleting the Delta table.

So my suggestion here would be, transform the csv to Delta once, perform delete periodically and generate csv only when it's needed.

The advantage here is - Delta internally stores data in parquet format which stores data in binary format and allow better compression and encoding/decoding of data.


问:
I need to capitalize the next string css
I need to capitalize the next string css

1- item

```<code>.table-generic p::first-letter {
text-transform: uppercase;}
</code>```

How can I do this with that number at the beginning?

答:
For that specific case, you could just use text-transform: capitalize on the element itself (instead of the first-letter pseudo-element).

p {
  text-transform: capitalize;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>1- item</p></code>```

Maybe you have other requirements or restrictions, but they are not apparent from your question.

Body:
I need to capitalize the next string css

1- item

.table-generic p::first-letter {
text-transform: uppercase;}

How can I do this with that number at the beginning?

Body:
For that specific case, you could just use text-transform: capitalize on the element itself (instead of the first-letter pseudo-element).

p {
  text-transform: capitalize;
}

<p>1- item</p>

Maybe you have other requirements or restrictions, but they are not apparent from your question.


问:
Impossible to display BottomNavigationBar in flutter
I have an issue about to display Bottom Navigation Bar. I don't understand why I have no issues in the console.

```<code>
class MyApp extends StatefulWidget {
  @override

  State<StatefulWidget> createState(){
    return _MyAppState();
  }

}

class _MyAppState extends State<MyApp>  {

  int _selectedPage =0;
  final _pageOptions = [
    HomeScreen(),
    ProfileScreen(),
  ];

  @override
  Widget build(BuildContext context) {
    var localizationDelegate = LocalizedApp.of(context).delegate;
    return  LocalizationProvider(
      state: LocalizationProvider.of(context).state,
      child: MaterialApp(
          localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          localizationDelegate
        ],
        initialRoute: '',
        onGenerateRoute: MyRoutes().getRoute,
        supportedLocales: localizationDelegate.supportedLocales,
//        locale: localizationDelegate.currentLocale,
        theme: ThemeData( primarySwatch: Colors.red),
        home:  Scaffold(
          body: _pageOptions[_selectedPage],
          bottomNavigationBar: BottomNavigationBar(
              type: BottomNavigationBarType.fixed,
              currentIndex: _selectedPage,
              onTap: (int index){
                setState(() {
                  _selectedPage = index;
                });
              },
              items: [
                BottomNavigationBarItem(
                  icon: Icon(Icons.home),
                  title: Text('Home'),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.account_circle),
                  title: Text('Me'),
                ),
              ]
          ),
        ),
      ),
    );

  }
}

</code>```

I use flutter_translate. I know it's a very simple case but I'm stuck on it. I search in google but I find nothing which can fit my case.

Thank you.

Solved

Delete App from my device (mobile)

Flutter clean in the console

Launch Debug in Android Studio

答:
You can try this,

Bottom navigationbar is the property of scaffold.

```<code>bottomNavigationBar: BottomAppBar(
        shape: CircularNotchedRectangle(),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 48.0, vertical: 3),
          child: new Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.home),
                color: Colors.white,
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.contact_phone),
                color: Colors.white,
                onPressed: () {},
              ),
            ],
          ),
        ),
        color: Colors.blueGrey,
      );
</code>```

Body:
I have an issue about to display Bottom Navigation Bar. I don't understand why I have no issues in the console.

class MyApp extends StatefulWidget {
  @override

  State<StatefulWidget> createState(){
    return _MyAppState();
  }

}

class _MyAppState extends State<MyApp>  {

  int _selectedPage =0;
  final _pageOptions = [
    HomeScreen(),
    ProfileScreen(),
  ];

  @override
  Widget build(BuildContext context) {
    var localizationDelegate = LocalizedApp.of(context).delegate;
    return  LocalizationProvider(
      state: LocalizationProvider.of(context).state,
      child: MaterialApp(
          localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          localizationDelegate
        ],
        initialRoute: '',
        onGenerateRoute: MyRoutes().getRoute,
        supportedLocales: localizationDelegate.supportedLocales,
//        locale: localizationDelegate.currentLocale,
        theme: ThemeData( primarySwatch: Colors.red),
        home:  Scaffold(
          body: _pageOptions[_selectedPage],
          bottomNavigationBar: BottomNavigationBar(
              type: BottomNavigationBarType.fixed,
              currentIndex: _selectedPage,
              onTap: (int index){
                setState(() {
                  _selectedPage = index;
                });
              },
              items: [
                BottomNavigationBarItem(
                  icon: Icon(Icons.home),
                  title: Text('Home'),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.account_circle),
                  title: Text('Me'),
                ),
              ]
          ),
        ),
      ),
    );

  }
}

I use flutter_translate. I know it's a very simple case but I'm stuck on it. I search in google but I find nothing which can fit my case.

Thank you.

Solved

Delete App from my device (mobile)

Flutter clean in the console

Launch Debug in Android Studio

Body:
You can try this,

Bottom navigationbar is the property of scaffold.

bottomNavigationBar: BottomAppBar(
        shape: CircularNotchedRectangle(),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 48.0, vertical: 3),
          child: new Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.home),
                color: Colors.white,
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.contact_phone),
                color: Colors.white,
                onPressed: () {},
              ),
            ],
          ),
        ),
        color: Colors.blueGrey,
      );


问:
Use two RecyclerView with different adapter inside NestedScrollView load very slowly
I need to use two RecyclerView with different Adapter in the same view.

My First RecyclerView will load just once in onCreate.

My Second RecyclerView will load more and more data when user scroll to bottom and call the api to get new data.

When I let my Second RecyclerView call the api to load more and more data, it will load very slowly and scroll heavy.

How can I fix that, thank you!

Here is my fragment:

```<code>public class NewFragment extends Fragment {

    private void setRecyclerAndAdapter(){
        if(swipeRefreshLayout != null && postRecycler != null){

            layoutManager = new LinearLayoutManager(context);
            postRecycler.setLayoutManager(layoutManager);

            LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_up_to_down);
            postRecycler.setLayoutAnimation(animationController);

            if(postAdAdapter == null){
                postAdAdapter = new PostCardAdapter(context, postDataList);
                postRecycler.setAdapter(postAdAdapter);

                setListener();
            }else{
                postAdAdapter.notifyDataSetChanged();
            }
        }else
            return;
    }
.
    private void setListener(){
        if(swipeRefreshLayout != null && postRecycler != null){

            ......

            nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
                @Override
                public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if(v.getChildAt(v.getChildCount() - 1) != null) {
                        if ((scrollY >= (v.getChildAt(v.getChildCount() - 1).getMeasuredHeight() - v.getMeasuredHeight())) &&
                                scrollY > oldScrollY) {

                            visibleItemCount = layoutManager.getChildCount();
                            totalItemCount = layoutManager.getItemCount();
                            pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();

                            if(controlCanGetMorePostData == true){
                                controlCanGetMorePostData = false;

                                if(postAdAdapter != null){
                                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                                        postAdAdapter.setLoadState(postAdAdapter.LOADING);
                                        callApiManagerGetMoreData();
                                    }
                                }else
                                    return;
                            }
                            else{
                                hasMorePostData = false;
                                setMoreDataState();
                            }
                        }
                    }
                }
            });
        }else
            return;
    }

}
</code>```

Here is my Layout:

```<code><androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/fragment_new_swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/fragment_new_nestedScroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            android:scrollbars="none">

                <GridLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:columnCount="1"
                    android:rowCount="2">

                        <RelativeLayout
                            android:id="@+id/fragment_new_banner_content"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_row="0">

                                <androidx.recyclerview.widget.RecyclerView
                                    android:id="@+id/fragment_new_first_recycler"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:scrollbars="vertical" />

                                <com.gmpsykr.each.Game.BannerIndicator
                                    android:id="@+id/fragment_new_banner_indicator"
                                    android:layout_width="match_parent"
                                    android:layout_height="32dp"
                                    android:layout_alignBottom="@+id/fragment_new_banner_recycler"
                                    app:selectColor="@color/colorAccent"
                                    app:unselectedColor="#ffffff"
                                    app:radius="3dp"
                                    app:space="10dp" />

                        </RelativeLayout>

                        <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/fragment_new_second_recycler"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layoutAnimation="@anim/layout_animation_up_to_down"
                            android:layout_row="1" />

                </GridLayout>

        </androidx.core.widget.NestedScrollView>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</code>```

答:
I want you to read this article and the same problem at https://stackoverflow.com/a/37337641/11560055.

I think this will be an answer for your problem.

Body:
I need to use two RecyclerView with different Adapter in the same view.

My First RecyclerView will load just once in onCreate.

My Second RecyclerView will load more and more data when user scroll to bottom and call the api to get new data.

When I let my Second RecyclerView call the api to load more and more data, it will load very slowly and scroll heavy.

How can I fix that, thank you!

Here is my fragment:

public class NewFragment extends Fragment {

    private void setRecyclerAndAdapter(){
        if(swipeRefreshLayout != null && postRecycler != null){

            layoutManager = new LinearLayoutManager(context);
            postRecycler.setLayoutManager(layoutManager);

            LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_up_to_down);
            postRecycler.setLayoutAnimation(animationController);

            if(postAdAdapter == null){
                postAdAdapter = new PostCardAdapter(context, postDataList);
                postRecycler.setAdapter(postAdAdapter);

                setListener();
            }else{
                postAdAdapter.notifyDataSetChanged();
            }
        }else
            return;
    }
.
    private void setListener(){
        if(swipeRefreshLayout != null && postRecycler != null){

            ......

            nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
                @Override
                public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if(v.getChildAt(v.getChildCount() - 1) != null) {
                        if ((scrollY >= (v.getChildAt(v.getChildCount() - 1).getMeasuredHeight() - v.getMeasuredHeight())) &&
                                scrollY > oldScrollY) {

                            visibleItemCount = layoutManager.getChildCount();
                            totalItemCount = layoutManager.getItemCount();
                            pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();

                            if(controlCanGetMorePostData == true){
                                controlCanGetMorePostData = false;

                                if(postAdAdapter != null){
                                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                                        postAdAdapter.setLoadState(postAdAdapter.LOADING);
                                        callApiManagerGetMoreData();
                                    }
                                }else
                                    return;
                            }
                            else{
                                hasMorePostData = false;
                                setMoreDataState();
                            }
                        }
                    }
                }
            });
        }else
            return;
    }

}

Here is my Layout:

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/fragment_new_swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/fragment_new_nestedScroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            android:scrollbars="none">

                <GridLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:columnCount="1"
                    android:rowCount="2">

                        <RelativeLayout
                            android:id="@+id/fragment_new_banner_content"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_row="0">

                                <androidx.recyclerview.widget.RecyclerView
                                    android:id="@+id/fragment_new_first_recycler"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:scrollbars="vertical" />

                                <com.gmpsykr.each.Game.BannerIndicator
                                    android:id="@+id/fragment_new_banner_indicator"
                                    android:layout_width="match_parent"
                                    android:layout_height="32dp"
                                    android:layout_alignBottom="@+id/fragment_new_banner_recycler"
                                    app:selectColor="@color/colorAccent"
                                    app:unselectedColor="#ffffff"
                                    app:radius="3dp"
                                    app:space="10dp" />

                        </RelativeLayout>

                        <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/fragment_new_second_recycler"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layoutAnimation="@anim/layout_animation_up_to_down"
                            android:layout_row="1" />

                </GridLayout>

        </androidx.core.widget.NestedScrollView>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>


问:
Display UITababrController on leftside in tvOS
I am working on tvOS app and the requirement is to display tab bar controls on left side like in Disney+ tvos app. So can display tabbar controls on the left side or do I have to create a custom view to achieve this?

Attached is the Disney+ tvos tabbar images

答:
As far as I know, there is no way to rotate a UITabBarController on its side. However, you could take a UITabView (https://developer.apple.com/documentation/uikit/uitabbar) and rotate it on its side using Core Animation. To add functionality, set something as the UITabBar's delegate to learn about changes.

As far as an actual code snippet, I typically write in Swift, but I found another Stack Overflow answer with what you're looking for.

How to programmatically rotate image by 90 Degrees in iPhone?

Hope that helps, have a nice day!


问:
Is there a way i can get a route parameter in vue
I am new to vuejs, i have my api in laravel having a route such as

Route::get('/get-song-details/{id}','SongsController@getSongDetails');. How do get this id in vue so that i can display only information about the selected song.

in the sample below, when i pass 1, i get information about song 1, and so on. how do i make it dynamic?

```<code>export default {
    data(){
        return {
            songs : []
        }
    },
    created(){
        axios.get('/api/get-song-details/1')
        .then(response => this.songs = response.data);
    }
};
</script>

</code>```

答: All route params can be accessed by using this.$route.params.paramName in JS code or by using $route.params.paramName in template. paramName is the parameter name as defined in your router.

Body:
I am new to vuejs, i have my api in laravel having a route such as

Route::get('/get-song-details/{id}','SongsController@getSongDetails');. How do get this id in vue so that i can display only information about the selected song.

in the sample below, when i pass 1, i get information about song 1, and so on. how do i make it dynamic?

export default {
    data(){
        return {
            songs : []
        }
    },
    created(){
        axios.get('/api/get-song-details/1')
        .then(response => this.songs = response.data);
    }
};
</script>


问:
resolveLocalFileSystemURL TypeError: Cannot read property 'then' of undefined TypeError
I am working on ionic 4 ( capacitor ). I am trying to resolve a local file system URL so I used this function resolveLocalFilesystemUrl but unfortunately,  I am getting this error

TypeError: Cannot read property 'then' of undefined TypeError: Cannot read property 'then' of undefined

This is my code:

    constructor(private _file: NativeFile) {}
...
..
          this._file.resolveLocalFilesystemUrl(nativeFilePath).then((entry: Entry) => {
   console.log(entry);
});

Note that this function returns a promise

答:
Be sure that you are using the right plugin. This is the one you need: https://ionicframework.com/docs/native/file

```<code>import { File } from '@ionic-native/file/ngx';

...

constructor(private _file: File) { }

this._file.resolveLocalFilesystemUrl(nativeFilePath).then((entry: Entry) => {
   console.log(entry);
});
</code>```

Edit

Are you sure the method returns a promise? According to some documentation, the method accepts a callbakc function. So your code will be something like:

```<code>this._file.resolveLocalFilesystemUrl(
  nativeFilePath,
  (entry: Entry) => console.log(entry),
  err => console.log(err)
);
</code>```

EDIT 2

I am working on a cordova based project (Ionic 4) an I am using the officially suggested plugin: https://ionicframework.com/docs/native/file . It is also supported in capacitor projects.
Form the official documentation:

You also need a FileEntry object to read an existing file. Use the
  file property of FileEntry to get the file reference, and then create
  a new FileReader object. You can use methods like readAsText to start
  the read operation. When the read operation is complete, this.result
  stores the result of the read operation.

```<code>function readFile(fileEntry) {
  fileEntry.file(function (file) {
    var reader = new FileReader();

    reader.onloadend = function() {
      console.log("Successful file read: " + this.result);
      displayFileData(fileEntry.fullPath + ": " + this.result);
    };

    reader.readAsText(file);

  }, onErrorReadFile);
}
</code>```

Official Ionic Documentation
Official plugin documentation

Body:
Be sure that you are using the right plugin. This is the one you need: https://ionicframework.com/docs/native/file

import { File } from '@ionic-native/file/ngx';

...

constructor(private _file: File) { }

this._file.resolveLocalFilesystemUrl(nativeFilePath).then((entry: Entry) => {
   console.log(entry);
});

Edit

Are you sure the method returns a promise? According to some documentation, the method accepts a callbakc function. So your code will be something like:

this._file.resolveLocalFilesystemUrl(
  nativeFilePath,
  (entry: Entry) => console.log(entry),
  err => console.log(err)
);

EDIT 2

I am working on a cordova based project (Ionic 4) an I am using the officially suggested plugin: https://ionicframework.com/docs/native/file . It is also supported in capacitor projects.
Form the official documentation:

You also need a FileEntry object to read an existing file. Use the
  file property of FileEntry to get the file reference, and then create
  a new FileReader object. You can use methods like readAsText to start
  the read operation. When the read operation is complete, this.result
  stores the result of the read operation.

function readFile(fileEntry) {
  fileEntry.file(function (file) {
    var reader = new FileReader();

    reader.onloadend = function() {
      console.log("Successful file read: " + this.result);
      displayFileData(fileEntry.fullPath + ": " + this.result);
    };

    reader.readAsText(file);

  }, onErrorReadFile);
}

Official Ionic Documentation
Official plugin documentation


问:
React native failed to launch emulator
While trying to test the android app am creating with React native, I run into this error

info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
```

I have the emulator(the AMD version) installed in the android studio.

How can I solve this problem

答:
In your scenario before running react native application you need to create emulator using Android Studio. You can view official documentation about running application on device by here

Before running your project make sure you have installed adb drivers - More

First of all create AVD using Android Studio.

Open your project android folder using Android Studio.

1. Click AVD Manager from Android Studio

 2. Click Create Virtual Device

 3. Select your device from device list and click Next

 4. Select the android os version from the available version list and click Next

 5. On last keep default settings on device and click Finish

After that you can see your available android emulator device list from AVD Manager window.

* Before run your react native application make sure you have turn on and run the android emulator from android studio

After that run your project using react-native run-android

Title: React native failed to launch emulator

Body:
While trying to test the android app am creating with React native, I run into this error

info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.

I have the emulator(the AMD version) installed in the android studio.

How can I solve this problem


问:
How to select value from Oracle table having field name as default keyword
We have Oracle table having default keyword(i.e in as field name) field name.Now i am querying table but unable to extract specific field data.

```<code>select a.filename,a.in from table a
</code>```

Following error appears "invalid field name.

答:
Try using double quotes.</p>

```<code>select a."IN" from table a
</code>```

Body:
We have Oracle table having default keyword(i.e in as field name) field name.Now i am querying table but unable to extract specific field data.

select a.filename,a.in from table a

Following error appears "invalid field name.

Body:
Try using double quotes.

select a."IN" from table a


问:
Regular Expression validator for date format DD/MMM/YYYY
```<code><asp:TextBox ID="txtDob" runat="server" MaxLength="100" CssClass="textbox2" size="10"  />
<ajax:TextBoxWatermarkExtender ID="txtWEDOB" WatermarkText="DD/MON/YYYY" TargetControlID="txtDob" runat="server" />
<asp:RegularExpressionValidator ID="rfv" runat="server" ControlToValidate="txtDob" SetFocusOnError="true"
ValidationExpression="^(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}$"
Display="None" ValidationGroup="search" ErrorMessage="Please enter correct date">
</asp:RegularExpressionValidator>
</code>```

I am using this regular expression validator for date. It is not giving error for like 12-FEB-2010 or 12 Feb 2010. I strictly want 12/FEB/2010 format. This Regular expressii\on is not working for date like 29/FEB/2010. what changes need to be made.

答:
It will be very complicated regular expression if you want to validate all the possible cases (like for example 30/FEB).

You will need sub-expression for months with 30 day, you will need a sub-expression for months with 31 day, and the most interesting is Feb and leap years. I don't think that using a regular expression is a good idea here.

[EDIT]

To the question in the comment:

```<code>^((31(?! (FEB|APR|JUN|SEP|NOV)))|((30|29)(?! FEB))|(29(?= FEB (((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8])/(JAN|FEB|MAR|MAY|APR|JUL|JUN|AUG|OCT|SEP|NOV|DEC)/((1[6-9]|[2-9]\d)\d{2})$
</code>```

Body:
<asp:TextBox ID="txtDob" runat="server" MaxLength="100" CssClass="textbox2" size="10"  />
<ajax:TextBoxWatermarkExtender ID="txtWEDOB" WatermarkText="DD/MON/YYYY" TargetControlID="txtDob" runat="server" />
<asp:RegularExpressionValidator ID="rfv" runat="server" ControlToValidate="txtDob" SetFocusOnError="true"
ValidationExpression="^(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}$"
Display="None" ValidationGroup="search" ErrorMessage="Please enter correct date">
</asp:RegularExpressionValidator>

I am using this regular expression validator for date. It is not giving error for like 12-FEB-2010 or 12 Feb 2010. I strictly want 12/FEB/2010 format. This Regular expressii\on is not working for date like 29/FEB/2010. what changes need to be made.

Body:
It will be very complicated regular expression if you want to validate all the possible cases (like for example 30/FEB).

You will need sub-expression for months with 30 day, you will need a sub-expression for months with 31 day, and the most interesting is Feb and leap years. I don't think that using a regular expression is a good idea here.

[EDIT]

To the question in the comment:

^((31(?! (FEB|APR|JUN|SEP|NOV)))|((30|29)(?! FEB))|(29(?= FEB (((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8])/(JAN|FEB|MAR|MAY|APR|JUL|JUN|AUG|OCT|SEP|NOV|DEC)/((1[6-9]|[2-9]\d)\d{2})$


问:
Is there a way to dynamically create a counter if such "month" exists?
I would like to enquire or get some reference as to how can I dynamically create a counter for each month if the exists ? Currently, I am retrieving the dates from a CSV file and store it in an ArrayList, from there I am comparing the dates to check whether if such month exists. If the month exists then "counter++". Afterwards, store the counter in a hashmap. I understand my code currently is an inefficient way of coding. How could I make it better ?

CODE

```<code>public HashMap<String, Integer> getDataPoint() {
    //My function code
    HashMap<String, Integer> numberOfPost = new HashMap<String, Integer>();
    int janCounter = 0;
    int febCounter = 0;
    int marCounter = 0;
    int aprCounter = 0;
    int mayCounter = 0;
    int juneCounter = 0;
    int julyCounter = 0;
    int augCounter = 0;
    int septCounter = 0;
    int octCounter = 0;
    int novCounter = 0;
    int decCounter = 0;
    String pattern = "MMM";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    OpenCsvReader reader = new OpenCsvReader();
    ArrayList <STPost> STArray = reader.loadST("file_path");

    Iterator STitr = STArray.iterator();
    while (STitr.hasNext()) {
        STPost St = (STPost) STitr.next();
        Date retrievedate = St.getTime();
        String strDate = sdf.format(retrievedate);
        if(strDate.equals("Jan")) {
            janCounter++;
        }
        else if (strDate.equals("Feb")) {
            febCounter++;
        }
        else if (strDate.equals("Mar")) {
            marCounter++;
        }
        else if (strDate.equals("Apr")) {
            aprCounter++;
        }
        else if (strDate.equals("May")) {
            mayCounter++;
        }
        else if (strDate.equals("June")) {
            juneCounter++;
        }
        else if (strDate.equals("July")) {
            julyCounter++;
        }
        else if (strDate.equals("Aug")) {
            augCounter++;
        }
        else if (strDate.equals("Sept")) {
            septCounter++;
        }
        else if (strDate.equals("Oct")) {
            octCounter++;
        }
        else if (strDate.equals("Nov")) {
            novCounter++;
        }
        else if (strDate.equals("Dec")) {
            decCounter++;
        }
        numberOfPost.put("January", janCounter);
        numberOfPost.put("Feburary", febCounter);
        numberOfPost.put("March", marCounter);
        numberOfPost.put("April", aprCounter);
        numberOfPost.put("May", mayCounter);
        numberOfPost.put("June", juneCounter);
        numberOfPost.put("July", julyCounter);
        numberOfPost.put("August", augCounter);
        numberOfPost.put("September", septCounter);
        numberOfPost.put("October", octCounter);
        numberOfPost.put("November", novCounter);
        numberOfPost.put("December", decCounter);
    }
  return numberOfPost
}
</code>```

答:
You can create an array of months and check if value exists there using indexOf method.

```<code>String months = "JanFebMarAprMayJunJulAugSepOctNovDec";
Integer idx = months.indexOf(strDate);
</code>```

Thereafter you can use SimpleDateFormat("MMMM") pattern to put and get it into your map.

```<code>if(idx > -1) {
    String longDate = new SimpleDateFormat("MMMM").format(retrievedate);
    Integer current = numberOfPost.get(longDate);
    if (current == null) {
        current = 1;
    } else {
        current += 1;
    }
    numberOfPost.put(longDate, current);
}
</code>```

Thereafter, you can use map iterator to display content of map.

Body:
I would like to enquire or get some reference as to how can I dynamically create a counter for each month if the exists ? Currently, I am retrieving the dates from a CSV file and store it in an ArrayList, from there I am comparing the dates to check whether if such month exists. If the month exists then "counter++". Afterwards, store the counter in a hashmap. I understand my code currently is an inefficient way of coding. How could I make it better ?

CODE

public HashMap<String, Integer> getDataPoint() {
    //My function code
    HashMap<String, Integer> numberOfPost = new HashMap<String, Integer>();
    int janCounter = 0;
    int febCounter = 0;
    int marCounter = 0;
    int aprCounter = 0;
    int mayCounter = 0;
    int juneCounter = 0;
    int julyCounter = 0;
    int augCounter = 0;
    int septCounter = 0;
    int octCounter = 0;
    int novCounter = 0;
    int decCounter = 0;
    String pattern = "MMM";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    OpenCsvReader reader = new OpenCsvReader();
    ArrayList <STPost> STArray = reader.loadST("file_path");

    Iterator STitr = STArray.iterator();
    while (STitr.hasNext()) {
        STPost St = (STPost) STitr.next();
        Date retrievedate = St.getTime();
        String strDate = sdf.format(retrievedate);
        if(strDate.equals("Jan")) {
            janCounter++;
        }
        else if (strDate.equals("Feb")) {
            febCounter++;
        }
        else if (strDate.equals("Mar")) {
            marCounter++;
        }
        else if (strDate.equals("Apr")) {
            aprCounter++;
        }
        else if (strDate.equals("May")) {
            mayCounter++;
        }
        else if (strDate.equals("June")) {
            juneCounter++;
        }
        else if (strDate.equals("July")) {
            julyCounter++;
        }
        else if (strDate.equals("Aug")) {
            augCounter++;
        }
        else if (strDate.equals("Sept")) {
            septCounter++;
        }
        else if (strDate.equals("Oct")) {
            octCounter++;
        }
        else if (strDate.equals("Nov")) {
            novCounter++;
        }
        else if (strDate.equals("Dec")) {
            decCounter++;
        }
        numberOfPost.put("January", janCounter);
        numberOfPost.put("Feburary", febCounter);
        numberOfPost.put("March", marCounter);
        numberOfPost.put("April", aprCounter);
        numberOfPost.put("May", mayCounter);
        numberOfPost.put("June", juneCounter);
        numberOfPost.put("July", julyCounter);
        numberOfPost.put("August", augCounter);
        numberOfPost.put("September", septCounter);
        numberOfPost.put("October", octCounter);
        numberOfPost.put("November", novCounter);
        numberOfPost.put("December", decCounter);
    }
  return numberOfPost
}

Body:
You can create an array of months and check if value exists there using indexOf method.

String months = "JanFebMarAprMayJunJulAugSepOctNovDec";
Integer idx = months.indexOf(strDate);

Thereafter you can use SimpleDateFormat("MMMM") pattern to put and get it into your map.

if(idx > -1) {
    String longDate = new SimpleDateFormat("MMMM").format(retrievedate);
    Integer current = numberOfPost.get(longDate);
    if (current == null) {
        current = 1;
    } else {
        current += 1;
    }
    numberOfPost.put(longDate, current);
}

Thereafter, you can use map iterator to display content of map.


问:
Are Managed Identity token acquisition environment variables available on VM?
When using Azure Managed Identity in the App Service/Functions, the endpoint and header are available as environment variables.

When using Azure Managed Identity in Virtual Machine, the endpoint is published as the Azure Instance Metadata service (IMDS) (http://169.254.169.254/metadata/identity/oauth2/token), accessible only from within the VM.

On a VM, is the endpoint set as an environment variable (MSI_ENDPOINT)?

On a VM, is there an indication whether managed identity is enabled?

Ideally, my code can simply check for that variable. Otherwise, I need to check the variable and make a call to the IMDS.

答:
The Azure Managed Identity is different between App Service/Functions and VM. As you know, the App Service/Functions use the Managed Identity through the environment variables MSI_ENDPOINT and MSI_SECRET as it shows here.

But for VM, it does not set the environment variables, you will get the access token from a server inside the Azure and it cannot access outside. Here are ways to get the access token for the VMS.

The indication for the Managed Identity of the VM, I think you can get the VM identity property and it will show you if it enables the Managed Identity and which type is used. For example, I use the Azure CLI and it shows like this:


问:
Nesting  list items within list items of an Ordered List ?
I am attempting to figure out how to create an incremented ordered list currently aimed towards IE6 and IE7.

E.G. It should render something like below:

```<code>1.0
    1.1
    1.2
    1.3
2.0
    2.1
    2.2
</code>```

From what I understand, this is possible to create in CSS with something like this:

```<code>UL, OL { counter-reset: item; }
LI { display: block }
LI:before { content: counters(item, "."); counter-increment: item }
</code>```

However, of course, IE6 and IE7 don't support this.

What options are available to create a proper incremented list in IE6/7? Am I stuck having to hard code this.? Unfortunately, using JavaScript is not an option.

Are there any updated methodologies for newer browsers?

答:
If JavaScript is not an option, you will have to hard code it/implement it on the server side.

The positive side is: It will work for other less capable user agents/devices (think BlackBerry Browser etc) right away.

OwnerDisplayName: Martin M

Body:
I am attempting to figure out how to create an incremented ordered list currently aimed towards IE6 and IE7.

E.G. It should render something like below:

1.0
    1.1
    1.2
    1.3
2.0
    2.1
    2.2

From what I understand, this is possible to create in CSS with something like this:

UL, OL { counter-reset: item; }
LI { display: block }
LI:before { content: counters(item, "."); counter-increment: item }

However, of course, IE6 and IE7 don't support this.

What options are available to create a proper incremented list in IE6/7? Am I stuck having to hard code this.? Unfortunately, using JavaScript is not an option.

Are there any updated methodologies for newer browsers?

LastEditorDisplayName: Andrew Hare

OwnerDisplayName: Tomalak

ContentLicense: CC BY-SA 2.5


问:
Mate How to inject UI component
In the Mate framework for flex.  I'm trying to inject a UIComponent into a non UIComponent.

The reason is the UI component is a library component and it has methods that need to be invoked on it. I'm not able to remove the requirement to invoke the methods.

I've got something like this currently

```<code><ObjectBuilder cache="global" generator="{DashboardController}" registerTarget="true"/>
<EventHandlers type="{DashboardEvent.DASHBOARD_CREATION_COMPLETE}">
    <PropertySetter generator="{DashboardController}"
        targetKey="dashboard"
        source="{lastReturn}"
        sourceKey="target" />
</EventHandlers>
</code>```

And I'm receiving an error like this.

```
<blockquote>
---------------------------------------------------------
MATE Error: Property type mismatch, turn on the debugger for more information
EventType:test.example.events.creationComplete. Error was found in a EventHandlers list in file DashboardEventMap
---------------------------------------------------------
</blockquote>
```

I've also tried using an object builder to set the property.

答: I suppose the problem is your lastReturn type isn't compatible with DashboardController.dashboard field. Please recheck it.

Title: Mate How to inject UI component

Body:
In the Mate framework for flex.  I'm trying to inject a UIComponent into a non UIComponent.

The reason is the UI component is a library component and it has methods that need to be invoked on it. I'm not able to remove the requirement to invoke the methods.

I've got something like this currently

<ObjectBuilder cache="global" generator="{DashboardController}" registerTarget="true"/>
<EventHandlers type="{DashboardEvent.DASHBOARD_CREATION_COMPLETE}">
    <PropertySetter generator="{DashboardController}"
        targetKey="dashboard"
        source="{lastReturn}"
        sourceKey="target" />
</EventHandlers>

And I'm receiving an error like this.

---------------------------------------------------------
MATE Error: Property type mismatch, turn on the debugger for more information
EventType:test.example.events.creationComplete. Error was found in a EventHandlers list in file DashboardEventMap
---------------------------------------------------------

I've also tried using an object builder to set the property.