问:
Excel VBA - Add Function to Macro to Delete Rows Containing Specific Text
I'm new to this site, and to Excel. I've been working on creating a spreadsheet, and fumbling my way through automating it as much as I can in order to streamline it for myself and the other members of my team. It performs most of the tasks I would like it to, but there are still a few remaining. Here is my code as it stands currently:

```<code>Sub Setup()
'
' Setup Macro
'
' Keyboard Shortcut: Ctrl+e
'
Rows("1:3").Select
Application.CutCopyMode = False
Selection.delete Shift:=xlUp
Cells.Select
ActiveWorkbook.Worksheets("Panel1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Panel1").Sort.SortFields.Add Key:=Range("C1:C18") _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Panel1").Sort
    .SetRange Range("A1:Q18")
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
Columns("B:B").Select
Cells.Replace What:="RTA", Replacement:="DELETE", LookAt:=xlWhole, _
    SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
    ReplaceFormat:=False
Columns("C:C").Select
Selection.Copy
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 3
ActiveWindow.ScrollColumn = 4
ActiveWindow.ScrollColumn = 5
Columns("O:O").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.TextToColumns Destination:=Range("O1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
    Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
    :=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Columns("O:P").Select
With Selection
    .VerticalAlignment = xlCenter
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .MergeCells = False
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
Columns("N:N").Select
ActiveWindow.LargeScroll ToRight:=-1
Columns("A:N").Select
Range("N1").Activate
Selection.EntireColumn.Hidden = True
End Sub
</code>```

The thing I'm currently struggling with the most is adding a function to this Macro which will find a specific text string, and delete the entire row which contains it. I've seen a lot of people suggest using Autofilter, but I need the row to be deleted entirely, not just hidden. I've also found a lot of really great standalone solutions, but I can't seem to figure out how to integrate them into this Macro, only how to make them a new Module. And I've also attempted to incorporate a Delete Sheet Rows action into the Macro thinking that if I did a Find and Replace first, that it would only delete that particular row, but it ended up deleting my entire worksheet.

As I stated, what it does now is a Find (RTA) and Replace (DELETE), as I was attempting to go the Delete Sheet Rows route, but ultimately all I need it to do is search Column B for the text RTA and delete the row(s) which contain it.

Additionally, is there a way to have this run on two worksheets (Panel1, Panel2) simultaneously, or will it need to be executed on both independently?

Thanks so much for any and all help, I am incredibly grateful. I would continue trying to work the solution out myself, but apparently I've been spending too much time on this task...

答:
You may try this. The sub will look for a specific string in a given range and remove all lines (and whole lines) that contain the string.

```<code>Sub CleanRange(R As Range, T As String)
Dim I As Long, F As Object
Dim M As Long, N As Long, P As Long, Q As Long
M = R.Row
N = R.Column
P = M + R.Rows.Count - 1
Q = N + R.Columns.Count - 1
I = M
While I <= P
    Set F = Range(Cells(I, N), Cells(I, Q)).Find(T, LookIn:=xlValues)
    If F Is Nothing Then
        I = I + 1
    Else
        Rows(I).Delete
        P = P - 1
    End If
Wend
End Sub
</code>```

Call for instance

```<code>Call CleanRange(Range("A1:C8"), "2")
</code>```

If you are looking for T in a single column, you may simplify and use Cells(I, K).Value directly.

It's possible to adapt this to operate on several sheets, or to look for several strings.

If you are always looking in column B, you can write

```<code>Sub CleanRange(R As Range, T As String)
Dim I As Long
Dim M As Long, N As Long, P As Long, Q As Long
M = R.Row
N = R.Column
P = M + R.Rows.Count - 1
Q = N + R.Columns.Count - 1
I = M
While I <= P
    If Cells(I, 2).Value = T Then
        Rows(I).Delete
        P = P - 1
    Else
        I = I + 1
    End If
Wend
End Sub
</code>```

Or even

```<code>Sub CleanRange(R1 As Long, R2 As Long, T As String)
Dim I As Long
Dim M As Long, N As Long, P As Long, Q As Long
M = R1
P = R2
I = M
While I <= P
    If Cells(I, 2).Value = T Then
        Rows(I).Delete
        P = P - 1
    Else
        I = I + 1
    End If
Wend
End Sub
</code>```

Notice the While is important, instead of the more obvious For loop, because as you delete rows, the last row to visit moves up, so the limit of the loop is reduced (that's why there is P = P - 1).

Then, if you want to call this sub in another sub, you will have

```<code>Sub Something(...)
!Declarations
!Do whatever you want here (initialisation...)

!Then do the call, with the appropriate range and string, here is an example
Call CleanRange(Range("A1:C100"), "2")

!Do whatever you want
End Sub
</code>```

Body:
I'm new to this site, and to Excel. I've been working on creating a spreadsheet, and fumbling my way through automating it as much as I can in order to streamline it for myself and the other members of my team. It performs most of the tasks I would like it to, but there are still a few remaining. Here is my code as it stands currently:

Sub Setup()
'
' Setup Macro
'
' Keyboard Shortcut: Ctrl+e
'
Rows("1:3").Select
Application.CutCopyMode = False
Selection.delete Shift:=xlUp
Cells.Select
ActiveWorkbook.Worksheets("Panel1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Panel1").Sort.SortFields.Add Key:=Range("C1:C18") _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Panel1").Sort
    .SetRange Range("A1:Q18")
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
Columns("B:B").Select
Cells.Replace What:="RTA", Replacement:="DELETE", LookAt:=xlWhole, _
    SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
    ReplaceFormat:=False
Columns("C:C").Select
Selection.Copy
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 3
ActiveWindow.ScrollColumn = 4
ActiveWindow.ScrollColumn = 5
Columns("O:O").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.TextToColumns Destination:=Range("O1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
    Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
    :=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Columns("O:P").Select
With Selection
    .VerticalAlignment = xlCenter
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .MergeCells = False
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
Columns("N:N").Select
ActiveWindow.LargeScroll ToRight:=-1
Columns("A:N").Select
Range("N1").Activate
Selection.EntireColumn.Hidden = True
End Sub

The thing I'm currently struggling with the most is adding a function to this Macro which will find a specific text string, and delete the entire row which contains it. I've seen a lot of people suggest using Autofilter, but I need the row to be deleted entirely, not just hidden. I've also found a lot of really great standalone solutions, but I can't seem to figure out how to integrate them into this Macro, only how to make them a new Module. And I've also attempted to incorporate a Delete Sheet Rows action into the Macro thinking that if I did a Find and Replace first, that it would only delete that particular row, but it ended up deleting my entire worksheet.

As I stated, what it does now is a Find (RTA) and Replace (DELETE), as I was attempting to go the Delete Sheet Rows route, but ultimately all I need it to do is search Column B for the text RTA and delete the row(s) which contain it.

Additionally, is there a way to have this run on two worksheets (Panel1, Panel2) simultaneously, or will it need to be executed on both independently?

Thanks so much for any and all help, I am incredibly grateful. I would continue trying to work the solution out myself, but apparently I've been spending too much time on this task...

Body:
You may try this. The sub will look for a specific string in a given range and remove all lines (and whole lines) that contain the string.

Sub CleanRange(R As Range, T As String)
Dim I As Long, F As Object
Dim M As Long, N As Long, P As Long, Q As Long
M = R.Row
N = R.Column
P = M + R.Rows.Count - 1
Q = N + R.Columns.Count - 1
I = M
While I <= P
    Set F = Range(Cells(I, N), Cells(I, Q)).Find(T, LookIn:=xlValues)
    If F Is Nothing Then
        I = I + 1
    Else
        Rows(I).Delete
        P = P - 1
    End If
Wend
End Sub

Call for instance

Call CleanRange(Range("A1:C8"), "2")

If you are looking for T in a single column, you may simplify and use Cells(I, K).Value directly.

It's possible to adapt this to operate on several sheets, or to look for several strings.

If you are always looking in column B, you can write

Sub CleanRange(R As Range, T As String)
Dim I As Long
Dim M As Long, N As Long, P As Long, Q As Long
M = R.Row
N = R.Column
P = M + R.Rows.Count - 1
Q = N + R.Columns.Count - 1
I = M
While I <= P
    If Cells(I, 2).Value = T Then
        Rows(I).Delete
        P = P - 1
    Else
        I = I + 1
    End If
Wend
End Sub

Or even

Sub CleanRange(R1 As Long, R2 As Long, T As String)
Dim I As Long
Dim M As Long, N As Long, P As Long, Q As Long
M = R1
P = R2
I = M
While I <= P
    If Cells(I, 2).Value = T Then
        Rows(I).Delete
        P = P - 1
    Else
        I = I + 1
    End If
Wend
End Sub

Notice the While is important, instead of the more obvious For loop, because as you delete rows, the last row to visit moves up, so the limit of the loop is reduced (that's why there is P = P - 1).

Then, if you want to call this sub in another sub, you will have

Sub Something(...)
!Declarations
!Do whatever you want here (initialisation...)

!Then do the call, with the appropriate range and string, here is an example
Call CleanRange(Range("A1:C100"), "2")

!Do whatever you want
End Sub


来源: stackexchange

问:
Unable to create UML C# class diagrams in VS 2010
I am unable to create the UML class diagram for my C# code in VS 2010 ultimate for unknown reason, I searched the internet and found that I need to download the Visualization and Modeling Feature Pack but the site is not working for me.

So is there another tool/application to create UML diagrams for my code rather than VS 2010 ?

Thanks in advance

答:
Try UMLet , a Free UML Tool for Fast UML Diagrams.
You can find more about it from the link below.

http://www.umlet.com/

Or you can try NClass also.

http://nclass.sourceforge.net/downloads.html

ContentLicense: CC BY-SA 3.0


问:
How to make a server side youtube player so the time played would be same for all users?
Take a look at plug.dj website, if you refresh a currently playing song, the timing won't be affected on the server and will not affect it.

I prefer node.js but any other language is also fine.

答:
From my understanding, what you are after is a shared youtube experience. I would do the following...

When a client joins, the server sends to the client a "start time", which indicates where the client should start watching the Youtube video and in such way "join" the rest of the viewers. Server needs to keep track of this time from the moment viewers start watching. The client should periodically make sure that the video is in sync with the time of others by having a timer outside of the youtube video, in browser. Youtube video can become out-of-sync due to buffering, a simple timer/clock in browser cannot.


问:
AWS Add Account Error
First of all I am new to spinnaker so I am still learning the ropes.  Said that, I'm adding an account to the aws provider like this:

hal config provider aws account add ServiceAccountSpinnaker \
   --account-id XXXXXXXXXXX \
   --assume-role role/spinnakerManaged

where the XXXXXXXXXXX is my actual account ID, i've created a user account named
ServiceAccountSpinnaker with a configured role of spinnakerManaged,

All as specified in Spinnaker Documentation:

https://www.spinnaker.io/setup/providers/aws/

After executing the Hal command here's what I am getting back:

Get current deployment   Success

Add the ServiceAccountSpinnaker account   Failure Problems in default.provider.aws.ServiceAccountSpinnaker: ! ERROR Account name
  must match pattern   ^[a-z0-9]+([-a-z0-9_]*[a-z0-9])?$ ? It must start
  and end with a lower-case character or number, and   only container
  lower-case character, numbers, dashes, or underscores

WARNING No validation for the AWS provider has been   implemented.

Failed to add account ServiceAccountSpinnaker for provider   aws.

So basically I have a problem with the account name, some enlightening is actually needed, since I've spent as an idiot, 45 minutes trying so many combinations to a simple thing.

I appreciate the help.

EN

答:
Note the requirement "It must start and end with a lower-case character or number, and only container lower-case character, numbers, dashes, or underscores". Your account name "ServiceAccountSpinnaker" is capitalized.

Keep in mind that this account name is only relevant within Spinnaker, and does not need to match any naming within AWS.

Title: AWS Add Account Error


问:
3 Digit currency code to currency symbol
In C# is it possible to get a currency symbol, like '£', from the 3 character currency code, in this case 'GBP'?

Is this possible either in SQL Server or in C#?

答:
```<code>public static string GetCurrencySymbol(string code)
{
 System.Globalization.RegionInfo regionInfo = (from culture in System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.InstalledWin32Cultures)
              where culture.Name.Length > 0 && !culture.IsNeutralCulture
              let region = new System.Globalization.RegionInfo(culture.LCID)
              where String.Equals(region.ISOCurrencySymbol, code, StringComparison.InvariantCultureIgnoreCase)
              select region).First();

 return regionInfo.CurrencySymbol;
}
</code>```


问:
Post JSON request in Swift 3
I need to post JSON data that looks like this :

```<code> { “orders”:[ {“id”: 208, “quantity”: 1 },{“id”: 212, “quantity”: 2},{“id”: 202, “quantity”: 5}, ...etc  ],“HHStatus”: “1 }
</code>```

I have the following variable :

```<code>var orders : [ShoppingCart] = []
</code>```

that contains data as :

[Crash.ShoppingCart(drinkId: 743, drinkName: "aqua", drinkPrice: "2.26", drinkQuantity: 2), Crash.ShoppingCart(drinkId: 715, drinkName: "yellow", drinkPrice: "6.92", drinkQuantity: 1), Crash.ShoppingCart(drinkId: 738, drinkName: "blue", drinkPrice: "4.69", drinkQuantity: 2)]

...etc

I am able to post the request using :

```<code>for order in orders {
        let orderId = order.drinkId
        let orderQuantity = order.drinkQuantity

    let parameters = ["orders": [["id": orderId, "quantity": orderQuantity]], "HHStatus": orderHHStatus!] as [String : Any]

    let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
</code>```

but then I want the whole order not just one id and one quantity,

and I have tried using :

```<code>    let orderId = orders.map { $0.drinkId }
    let orderQuantity = orders.map { $0.drinkQuantity }

    let parameters = ["orders": [["id": orderId, "quantity": orderQuantity]], "HHStatus": orderHHStatus!] as [String : Any]

    let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
</code>```

but then I end up with something like this :

```<code>["HHStatus": "0", "orders": [["id": [743, 715, 738], "quantity": [2, 1, 2]]]]
</code>```

How can I send all the ids and quantities in one request?

I can't figure out how to get something like :

```<code>["orders": [["id": orderId, "quantity": orderQuantity],["id": orderId, "quantity": orderQuantity], ["id": orderId, "quantity": orderQuantity]], "HHStatus": orderHHStatus!]
</code>```

so many thanks for any help provided!

答:
Map the ShoppingCart array to an array of dictionaries with the map function:

```<code>let mappedOrders = orders.map { ["id" : $0.drinkId, "quantity" : $0.drinkQuantity] }
</code>```

Create the parameters dictionary

```<code>let parameters : [String:Any] =  ["orders" : mappedOrders, "HHStatus" : orderHHStatus!]
</code>```

Don't pass the .prettyPrinted option, the server doesn't care about aesthetics.

Omit the options parameter.

Title: Post JSON request in Swift 3

Body:
I need to post JSON data that looks like this :

 { “orders”:[ {“id”: 208, “quantity”: 1 },{“id”: 212, “quantity”: 2},{“id”: 202, “quantity”: 5}, ...etc  ],“HHStatus”: “1 }

I have the following variable :

var orders : [ShoppingCart] = []

that contains data as :

[Crash.ShoppingCart(drinkId: 743, drinkName: "aqua", drinkPrice: "2.26", drinkQuantity: 2), Crash.ShoppingCart(drinkId: 715, drinkName: "yellow", drinkPrice: "6.92", drinkQuantity: 1), Crash.ShoppingCart(drinkId: 738, drinkName: "blue", drinkPrice: "4.69", drinkQuantity: 2)]

...etc

I am able to post the request using :

for order in orders {
        let orderId = order.drinkId
        let orderQuantity = order.drinkQuantity

    let parameters = ["orders": [["id": orderId, "quantity": orderQuantity]], "HHStatus": orderHHStatus!] as [String : Any]

    let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

but then I want the whole order not just one id and one quantity,

and I have tried using :

    let orderId = orders.map { $0.drinkId }
    let orderQuantity = orders.map { $0.drinkQuantity }

    let parameters = ["orders": [["id": orderId, "quantity": orderQuantity]], "HHStatus": orderHHStatus!] as [String : Any]

    let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

but then I end up with something like this :

["HHStatus": "0", "orders": [["id": [743, 715, 738], "quantity": [2, 1, 2]]]]

How can I send all the ids and quantities in one request?

I can't figure out how to get something like :

["orders": [["id": orderId, "quantity": orderQuantity],["id": orderId, "quantity": orderQuantity], ["id": orderId, "quantity": orderQuantity]], "HHStatus": orderHHStatus!]

so many thanks for any help provided!

Body:
Map the ShoppingCart array to an array of dictionaries with the map function:

let mappedOrders = orders.map { ["id" : $0.drinkId, "quantity" : $0.drinkQuantity] }

Create the parameters dictionary

let parameters : [String:Any] =  ["orders" : mappedOrders, "HHStatus" : orderHHStatus!]

Don't pass the .prettyPrinted option, the server doesn't care about aesthetics.

Omit the options parameter.


问:
Is it bad to have your test and production environments on the same machine?
Would it be bad to have things set up so that MySite.com is production and test.MySite.com is test?  Both running off the same machine.  The site doesn't get a lot of traffic.

UPDATE

I am talking about an ASP.NET web application running on a Windows server.

答:
As your question is not platform specific, I'll try to answer in a general form. I'll lso refer only to the "same machine" part of your question, since the "domain name" should be very easy to  change ... if all common precautions have been taken.

What you really need is to isolate environments. Depending on the technology used, that may mean "separate machines" or not.

As an example, a lot small to medium banks in the world run their critical systems on one mainframe. It's not unusual for one of those beasts to cost (peripherals and all) six figures.  Some of them opted to have separate, smaller machines for development and testing, while others run hundreds of environments (sometimes as VMs) on the same machine. The tricky detail is that the mainframe hardware and OS do provide real and consistent isolation between those environments, assigning disks, CPUs, comm channels, credentials, libraries, OS modules, DBs, etc, etc based on a strict policy that can be as granular as you want.

The problem with many other platforms is that finding the way to isolate the environments is up to you, while in a dinosaur platform is provided by the grace of HAL.

HTH!

ContentLicense: CC BY-SA 2.5


问:
Element style not allowed as child of element div in this context
I have been going through W3C errors and have cleared all but this one.

Element style not allowed as child of element div in this context.

Here is the code it refers to:

```<code><style><!--ul.lists { width: 29%; float: left;}--></style>
</code>```

Any help ridding me of this last error would be appreciated.

答:
If you're trying to do an inline style you can use

```<code><ul style="width:29%;float:left"></ul>
</code>```

Or put the code in a .css file

```<code>ul.lists {
  width: 29%;
  float: left;
}
</code>```

And declare the class in the HTML

```<code><ul class="lists"></ul>
</code>```

To comment in CSS you must use /* this is a comment */

Body:
I have been going through W3C errors and have cleared all but this one.

Element style not allowed as child of element div in this context.

Here is the code it refers to:

Any help ridding me of this last error would be appreciated.

Body:
If you're trying to do an inline style you can use

<ul style="width:29%;float:left"></ul>

Or put the code in a .css file

ul.lists {
  width: 29%;
  float: left;
}

And declare the class in the HTML

<ul class="lists"></ul>

To comment in CSS you must use /* this is a comment */


问:
Why is MongoDB's skip() so slow and bad to use, while MySQL's LIMIT is so fast?
Mongo's skip() is fine for small collections, but once you have a few thousand records it starts to become slow.

I would honestly like to know why a decent LIMIT-like function in a NoSQL database is so hard to do.

The only "solution" I keep reading about is using range-based queries. But for a lot of cases that is not a viable solution.

答:
I was facing the same issue with skip(). Everything worked fine when my database was having fewer documents but performance started affecting when my document count was more than 10L.

I had to get rid of skip but then fetching specific count of data was a challenge to me. below blog helped me out.

https://scalegrid.io/blog/fast-paging-with-mongodb/


问:
NHibernate: Updating collections during EventListener "PreUpdateEvent"
I'm trying to write an audit tracking for Nhibernate that hooks into the PreUpdate event. I have an AuditLogEntry class (when, who, etc), that contains a list of AuditLogEntryDetails (i.e. individual properties that changed).  If I isolate the AuditLogEntry class from the entity being audited then my code runs with no errors.   However, if I add a list of AuditLogEntry's to the entity being audited then my code throws a

collection [DomainObjects.AuditTracking.AuditLogEntry.Details] was not processed by
flush()

assertion failure when I attempt to save the modified list inside the event listener.  This only happens when the audited item already has one (or more) AuditLogEntry instance in the list.  If there are no entries then a new list is created and added to the entity being audited and this is fine.

I think by isolating the issue to the above it would appear to be around (lazy) loading the existing list to add the new instance of AuditLogEntry too.  However I've been unable to progress any further. Adding 'Lazy="False"' to the list mapping doesn't appear to help.  I'm really in the early days of using NHibernate, having borrowed concepts from both the HN 3.0 Cookbook and this blog post.  My code is very similar to this, but attempts to add the audit history to the item being audited in a list (and as such I think that I need to also do that in the pre, rather than post update event).

A snap shot of the entity interfaces/classes in question are:

```<code>public class AuditLogEntry : Entity
{
    public virtual AuditEntryTypeEnum AuditEntryType { get; set; }
    public virtual string EntityFullName { get; set; }
    public virtual string EntityShortName { get; set; }
    public virtual string Username { get; set; }
    public virtual DateTime When { get; set; }
    public virtual IList<AuditLogEntryDetail> Details { get; set; }
}

public interface IAuditTrackedEntity
{
    Guid Id { get; }
    IList<AuditLogEntry> ChangeHistory { get; set; }
}

public class AuditTrackedEntity : StampedEntity, IAuditTrackedEntity
{
    public virtual IList<AuditLogEntry> ChangeHistory { get; set; }
}

public class LookupValue : AuditTrackedEntity
{
    public virtual string Description { get; set; }
}
</code>```

For the mappings I have:

AuditTrackedEntry.hbm.xml:

```<code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DomainObjects" namespace="DomainObjects.AuditTracking">
  <class name="AuditLogEntry">
    <id name="Id">
      <generator class="guid.comb" />
    </id>
    <version name="Version" />
    <property name="AuditEntryType"/>
    <property name="EntityFullName"/>
    <property name="EntityShortName"/>
    <property name="Username"/>
    <property name="When" column="`When`"/>
    <list name ="Details" cascade="all">
      <key column="AuditLogEntryId"/>
      <list-index column="DetailsIndex" base="1"/>
      <one-to-many class="AuditLogEntryDetail"/>
    </list>
  </class>
</hibernate-mapping>
</code>```

lookupvalue.hbm.xml:

```<code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DomainObjects" namespace="DomainObjects">
  <class name="LookupValue">
    <id name="Id">
      <generator class="guid.comb" />
    </id>
    <discriminator type="string">
      <column name="LookupValueType" unique-key="UQ_TypeName" not-null="true" />
    </discriminator>
    <version name="Version" />
    <property name="Description" unique-key="UQ_TypeName" not-null="true" />
    <property name="CreatedBy" />
    <property name="WhenCreated" />
    <property name="ChangedBy" />
    <property name="WhenChanged" />
    <list name ="ChangeHistory">
      <key column="EntityId"/>
      <list-index column="ChangeIndex" base="1"/>
      <one-to-many class="DomainObjects.AuditTracking.AuditLogEntry"/>
    </list>
  </class>
</hibernate-mapping>
</code>```

The EventListener PreUpdate event handler calls the follow code:
The lines that cause the problem are commented near the end of the code block

```<code>    public void TrackPreUpdate(IAuditTrackedEntity entity, object[] oldState, object[] state, IEntityPersister persister, IEventSource eventSource)
    {
        if (entity == null || entity is AuditLogEntry)
            return;

        var entityFullName = entity.GetType().FullName;
        if (oldState == null)
        {
            throw new ArgumentNullException("No old state available for entity type '" + entityFullName +
                                            "'. Make sure you're loading it into Session before modifying and saving it.");
        }

        var dirtyFieldIndexes = persister.FindDirty(state, oldState, entity, eventSource);
        var session = eventSource.GetSession(EntityMode.Poco);

        AuditLogEntry auditLogEntry = null;
        foreach (var dirtyFieldIndex in dirtyFieldIndexes)
        {
            if (IsIngoredProperty(persister, dirtyFieldIndex))
                continue;

            var oldValue = GetStringValueFromStateArray(oldState, dirtyFieldIndex);
            var newValue = GetStringValueFromStateArray(state, dirtyFieldIndex);

            if (oldValue == newValue)
            {
                continue;
            }
            if (auditLogEntry == null)
            {
                auditLogEntry = new AuditLogEntry
                                    {
                                        AuditEntryType = AuditEntryTypeEnum.Update,
                                        EntityShortName = entity.GetType().Name,
                                        EntityFullName = entityFullName,
                                        Username = Environment.UserName,
                                        //EntityId = entity.Id,
                                        When = DateTime.Now,
                                        Details =  new List<AuditLogEntryDetail>()
                                    };

                //**********************
                // The next three lines cause a problem when included,
                // collection [] was not processed by flush()
                //**********************
                if (entity.ChangeHistory == null)
                    entity.ChangeHistory = new List<AuditLogEntry>();
                entity.ChangeHistory.Add(auditLogEntry);

                session.Save(auditLogEntry);
            }

            var detail = new AuditLogEntryDetail
                             {
                                 //AuditLogEntryId = auditLogEntry.Id,
                                 PropertyName = persister.PropertyNames[dirtyFieldIndex],
                                 OldValue = oldValue,
                                 NewValue = newValue
                             };
            session.Save(detail);
            auditLogEntry.Details.Add(detail);

        }

        session.Flush();
    }
</code>```

As previously stated, in this configuration I get an assertion failure "collection [] was not processed by flush()".  If I remove the three lines above and the list mapping in the lookupcode.hmb.xml then everything works as expected, other than the entity being audited no longer contains a reference to it's own audited items.

答:
Ok, I have found your problem, this line is actually causing the problem.

```<code>Details =  new List<AuditLogEntryDetail>()
</code>```

You can't initialize an empty collection before you save because the EntityPersister will not persist the collection, but it will error that the collection has not been processed.

Also, once nHibernate calls event listeners, cascades do not work (not sure if this is by design or not). So even though you are adding the detail item to the collection later, you are only calling save on the detail, not the parent, so the change is not propagated. I would recommend re-factoring so that items are completed in this order...

Detail, then save,

AuditLogEntry, then save,

Entity, then update.

Body:
I'm trying to write an audit tracking for Nhibernate that hooks into the PreUpdate event. I have an AuditLogEntry class (when, who, etc), that contains a list of AuditLogEntryDetails (i.e. individual properties that changed).  If I isolate the AuditLogEntry class from the entity being audited then my code runs with no errors.   However, if I add a list of AuditLogEntry's to the entity being audited then my code throws a

collection [DomainObjects.AuditTracking.AuditLogEntry.Details] was not processed by
flush()

assertion failure when I attempt to save the modified list inside the event listener.  This only happens when the audited item already has one (or more) AuditLogEntry instance in the list.  If there are no entries then a new list is created and added to the entity being audited and this is fine.

I think by isolating the issue to the above it would appear to be around (lazy) loading the existing list to add the new instance of AuditLogEntry too.  However I've been unable to progress any further. Adding 'Lazy="False"' to the list mapping doesn't appear to help.  I'm really in the early days of using NHibernate, having borrowed concepts from both the HN 3.0 Cookbook and this blog post.  My code is very similar to this, but attempts to add the audit history to the item being audited in a list (and as such I think that I need to also do that in the pre, rather than post update event).

A snap shot of the entity interfaces/classes in question are:

public class AuditLogEntry : Entity
{
    public virtual AuditEntryTypeEnum AuditEntryType { get; set; }
    public virtual string EntityFullName { get; set; }
    public virtual string EntityShortName { get; set; }
    public virtual string Username { get; set; }
    public virtual DateTime When { get; set; }
    public virtual IList<AuditLogEntryDetail> Details { get; set; }
}

public interface IAuditTrackedEntity
{
    Guid Id { get; }
    IList<AuditLogEntry> ChangeHistory { get; set; }
}

public class AuditTrackedEntity : StampedEntity, IAuditTrackedEntity
{
    public virtual IList<AuditLogEntry> ChangeHistory { get; set; }
}

public class LookupValue : AuditTrackedEntity
{
    public virtual string Description { get; set; }
}

For the mappings I have:

AuditTrackedEntry.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DomainObjects" namespace="DomainObjects.AuditTracking">
  <class name="AuditLogEntry">
    <id name="Id">
      <generator class="guid.comb" />
    </id>
    <version name="Version" />
    <property name="AuditEntryType"/>
    <property name="EntityFullName"/>
    <property name="EntityShortName"/>
    <property name="Username"/>
    <property name="When" column="`When`"/>
    <list name ="Details" cascade="all">
      <key column="AuditLogEntryId"/>
      <list-index column="DetailsIndex" base="1"/>
      <one-to-many class="AuditLogEntryDetail"/>
    </list>
  </class>
</hibernate-mapping>

lookupvalue.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DomainObjects" namespace="DomainObjects">
  <class name="LookupValue">
    <id name="Id">
      <generator class="guid.comb" />
    </id>
    <discriminator type="string">
      <column name="LookupValueType" unique-key="UQ_TypeName" not-null="true" />
    </discriminator>
    <version name="Version" />
    <property name="Description" unique-key="UQ_TypeName" not-null="true" />
    <property name="CreatedBy" />
    <property name="WhenCreated" />
    <property name="ChangedBy" />
    <property name="WhenChanged" />
    <list name ="ChangeHistory">
      <key column="EntityId"/>
      <list-index column="ChangeIndex" base="1"/>
      <one-to-many class="DomainObjects.AuditTracking.AuditLogEntry"/>
    </list>
  </class>
</hibernate-mapping>

The EventListener PreUpdate event handler calls the follow code:
The lines that cause the problem are commented near the end of the code block

    public void TrackPreUpdate(IAuditTrackedEntity entity, object[] oldState, object[] state, IEntityPersister persister, IEventSource eventSource)
    {
        if (entity == null || entity is AuditLogEntry)
            return;

        var entityFullName = entity.GetType().FullName;
        if (oldState == null)
        {
            throw new ArgumentNullException("No old state available for entity type '" + entityFullName +
                                            "'. Make sure you're loading it into Session before modifying and saving it.");
        }

        var dirtyFieldIndexes = persister.FindDirty(state, oldState, entity, eventSource);
        var session = eventSource.GetSession(EntityMode.Poco);

        AuditLogEntry auditLogEntry = null;
        foreach (var dirtyFieldIndex in dirtyFieldIndexes)
        {
            if (IsIngoredProperty(persister, dirtyFieldIndex))
                continue;

            var oldValue = GetStringValueFromStateArray(oldState, dirtyFieldIndex);
            var newValue = GetStringValueFromStateArray(state, dirtyFieldIndex);

            if (oldValue == newValue)
            {
                continue;
            }
            if (auditLogEntry == null)
            {
                auditLogEntry = new AuditLogEntry
                                    {
                                        AuditEntryType = AuditEntryTypeEnum.Update,
                                        EntityShortName = entity.GetType().Name,
                                        EntityFullName = entityFullName,
                                        Username = Environment.UserName,
                                        //EntityId = entity.Id,
                                        When = DateTime.Now,
                                        Details =  new List<AuditLogEntryDetail>()
                                    };

                //**********************
                // The next three lines cause a problem when included,
                // collection [] was not processed by flush()
                //**********************
                if (entity.ChangeHistory == null)
                    entity.ChangeHistory = new List<AuditLogEntry>();
                entity.ChangeHistory.Add(auditLogEntry);

                session.Save(auditLogEntry);
            }

            var detail = new AuditLogEntryDetail
                             {
                                 //AuditLogEntryId = auditLogEntry.Id,
                                 PropertyName = persister.PropertyNames[dirtyFieldIndex],
                                 OldValue = oldValue,
                                 NewValue = newValue
                             };
            session.Save(detail);
            auditLogEntry.Details.Add(detail);

        }

        session.Flush();
    }

As previously stated, in this configuration I get an assertion failure "collection [] was not processed by flush()".  If I remove the three lines above and the list mapping in the lookupcode.hmb.xml then everything works as expected, other than the entity being audited no longer contains a reference to it's own audited items.

Body:
Ok, I have found your problem, this line is actually causing the problem.

Details =  new List<AuditLogEntryDetail>()

You can't initialize an empty collection before you save because the EntityPersister will not persist the collection, but it will error that the collection has not been processed.

Also, once nHibernate calls event listeners, cascades do not work (not sure if this is by design or not). So even though you are adding the detail item to the collection later, you are only calling save on the detail, not the parent, so the change is not propagated. I would recommend re-factoring so that items are completed in this order...

Detail, then save,

AuditLogEntry, then save,

Entity, then update.


答:
The W3C error message describes your problem and a possible solution very well:

The element named above was found in a context where it is not allowed. This could mean that you have incorrectly nested elements -- such as a "style" element in the "body" section instead of inside "head" -- or two elements that overlap (which is not allowed).

You have to move your

```

You try to comment some code?

You are using the comment syntax for HTML instead of CSS. You try to comment the CSS code inside

Title: Element style not allowed as child of element div in this context

Body:
The W3C error message describes your problem and a possible solution very well:

The element named above was found in a context where it is not allowed. This could mean that you have incorrectly nested elements -- such as a "style" element in the "body" section instead of inside "head" -- or two elements that overlap (which is not allowed).

You have to move your <style> to the <head> area of the site.

<html>
  <head>
    <style>
      ul.lists {
        width: 29%;
        float: left;
      }
      /* this is a CSS comment. */
    </style>
  </head>
  <body>
    <div></div>
    <!-- this is a HTML comment. -->
  </body>
</html>

You try to comment some code?

You are using the comment syntax for HTML instead of CSS. You try to comment the CSS code inside <style> with <!-- ... -->. You have to use the CSS syntax /* ... */ instead.


问:
Docker process killed with cryptic `Killed` message
Running a python script in a docker container and everything seems to be running smoothly, seeing some STDOUT messages, about 5 minutes in I get a Killed message with no further explanation and the process stops. Querying a db so could be a disk space issue, could be OOM issue. I'm not sure but I have no idea where to find logs about this kill message so I can get to the root of this problem. Any ideas where these logs are?

Running docker-machine on Mac OSX.

That's really all the message says!

```<code>root@c7b800e0f276:/opt/mymodule# python
Python 2.7.13 (default, May  1 2017, 22:44:36)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from mymodule import model
>>> model.run('2017-04-01')
INFO:Deleting from input table.
INFO:Inserting into input table.
INFO:Querying input table for chunk.
Killed
root@c7b800e0f276:/opt/mymodule# exit
</code>```

Thanks!

答:
With Docker for Mac, you can get into the host VM namespace with:

```<code>docker run --net=host --ipc=host --uts=host --pid=host -it --security-opt=seccomp=unconfined --privileged --rm -v /:/host alpine /bin/sh
</code>```

Then run chroot /host to change root to the host mount. Now, you can use utilities like dmesg to check for any OOM message (like the comments to your question suggest).

Body:
Running a python script in a docker container and everything seems to be running smoothly, seeing some STDOUT messages, about 5 minutes in I get a Killed message with no further explanation and the process stops. Querying a db so could be a disk space issue, could be OOM issue. I'm not sure but I have no idea where to find logs about this kill message so I can get to the root of this problem. Any ideas where these logs are?

Running docker-machine on Mac OSX.

That's really all the message says!

root@c7b800e0f276:/opt/mymodule# python
Python 2.7.13 (default, May  1 2017, 22:44:36)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from mymodule import model
>>> model.run('2017-04-01')
INFO:Deleting from input table.
INFO:Inserting into input table.
INFO:Querying input table for chunk.
Killed
root@c7b800e0f276:/opt/mymodule# exit

Thanks!

Body:
With Docker for Mac, you can get into the host VM namespace with:

docker run --net=host --ipc=host --uts=host --pid=host -it --security-opt=seccomp=unconfined --privileged --rm -v /:/host alpine /bin/sh

Then run chroot /host to change root to the host mount. Now, you can use utilities like dmesg to check for any OOM message (like the comments to your question suggest).


问:
How do I use input if the user entered a char into an int?
I have a code in which I read ints into a vector.

```<code>vector <int> v;

for (int i; cin >> i;){
    v.push_back(i);
}
</code>```

and to end the loop, the user must enter '/'. How would I do that?
in other words, if the user enters a char into an int, how do I use the input?

答:
use std::string to read array of characters, compare the string if it equals to your desired string for termination of the sequence and if not, convert it to int

```<code>std::vector <int> v;
std::string buffer;

while(true){
   std::cin >> buffer;

   if(buffer == "/") break;

   v.push_back(std::stoi(buffer));
}
</code>```

NOTE: if u try to enter characters that can't be converted there will be an error

for more reference check out:
http://en.cppreference.com/w/cpp/string/basic_string/stol

Body:
I have a code in which I read ints into a vector.

vector <int> v;

for (int i; cin >> i;){
    v.push_back(i);
}

and to end the loop, the user must enter '/'. How would I do that?
in other words, if the user enters a char into an int, how do I use the input?

Body:
use std::string to read array of characters, compare the string if it equals to your desired string for termination of the sequence and if not, convert it to int

std::vector <int> v;
std::string buffer;

while(true){
   std::cin >> buffer;

   if(buffer == "/") break;

   v.push_back(std::stoi(buffer));
}

NOTE: if u try to enter characters that can't be converted there will be an error

for more reference check out:
http://en.cppreference.com/w/cpp/string/basic_string/stol


问:
What's mean of template<typename T, T*> in c++ templates?
What's mean of template<typename T, T*> in c++ templates?
And in what situation，i should use it？

```<code>#include <iostream>
using namespace std;

template<typename T, T*>
void test(T a)
{
    cout << "test template\n";
}

int main(int argc, char **argv)
{
    test(10);
    return 0;
}
</code>```

I got a compile error from above code.

```<code>./test.cpp: In function ‘int main(int, char**)’:
./test.cpp:12: error: no matching function for call to ‘test(int)’
</code>```

change test(10); to test<int, int*>(10);, still don't work.

答:
Usage would be:

```<code>extern int global;

int main()
{
    test<int, &global>(10);
}
</code>```

Demo

Body:
What's mean of template<typename T, T*> in c++ templates?
And in what situation，i should use it？

#include <iostream>
using namespace std;

template<typename T, T*>
void test(T a)
{
    cout << "test template\n";
}

int main(int argc, char **argv)
{
    test(10);
    return 0;
}

I got a compile error from above code.

./test.cpp: In function ‘int main(int, char**)’:
./test.cpp:12: error: no matching function for call to ‘test(int)’

change test(10); to test<int, int*>(10);, still don't work.

Body:
Usage would be:

extern int global;

int main()
{
    test<int, &global>(10);
}

Demo


问:
javascript regex help
i am trying to validate if a certain company was already picked for an application. the companyList format is:

60,261,420  ( a list of companyID)

I used

```<code>cID = $('#coName').val().split('::')[1];
</code>```

to get the id only.

I am calling this function by passing say 60:

```<code>    findCompany = function(value) {
    var v = /^.+60,261,420$/.test(value);
    alert(v);
}
</code>```

when I pass the exact same string, i get false. any help?

答:
Well if your company list is a list of numeric IDs like that, you need to make the resulting regular expression actually be the correct expression — if that's even the way you want to do it.

Another option is to just make an array, and then test for the value being in the array.

As a regex, though, what you could do is this:

```<code>var companyList = [<cfoutput> whatever </cfoutput>]; // get company ID list as an array of numbers
var companyRegex = new RegExp("^(?:" + companyList.join('|') + ")$");
</code>```

Then you can say:

```<code>function findCompany(id) {
  if (companyRegex.test(id)) alert(id + " is already in the list!");
}
</code>```

Title: javascript regex help

Body:
i am trying to validate if a certain company was already picked for an application. the companyList format is:

60,261,420  ( a list of companyID)

I used

cID = $('#coName').val().split('::')[1];

to get the id only.

I am calling this function by passing say 60:

    findCompany = function(value) {
    var v = /^.+60,261,420$/.test(value);
    alert(v);
}

when I pass the exact same string, i get false. any help?

Body:
Well if your company list is a list of numeric IDs like that, you need to make the resulting regular expression actually be the correct expression — if that's even the way you want to do it.

Another option is to just make an array, and then test for the value being in the array.

As a regex, though, what you could do is this:

var companyList = [<cfoutput> whatever </cfoutput>]; // get company ID list as an array of numbers
var companyRegex = new RegExp("^(?:" + companyList.join('|') + ")$");

Then you can say:

function findCompany(id) {
  if (companyRegex.test(id)) alert(id + " is already in the list!");
}


问:
How to hash session IDs for the database?
Specifically, I am doing this in PHP, but this question is not about the built-in PHP session mechanism; I am creating my own authentication system for experimental/educational purposes.

"Don't make your own system" isn't a helpful answer here because I want to understand the conceptual issue at hand regardless of that.

Here is the problem:

Session IDs are sensitive in much the same way as passwords and should be stored with similar security (hashes)

Regular cryptographic hash functions are now widely decried as worthless for this use because of their speed.

Modern password-hashing algorithms have features that make them inconvenient for hashing the session ID.

Let me explain #3.

The session ID is of course a long random string stored in a cookie -- the system compares the hash of this to the hashed session IDs in the database to verify a valid session, look up which session to use, and from there know which user they're logged in as and so on.
Unlike passwords, the session IDs are long, random, and guaranteed unique so having a separate salt for each one is not very valuable. Therefore you can use a system wide salt, allowing you to hash the input once and look up the session in the database based on that hash.

However, password-hashing functions (at least, their forms available in PHP) always auto generate a salt for you (providing a salt is either disallowed or deprecated) and append it to the hash output, and comparing an input against the hash involves using a special verify function that uses the salt stored with the hash to hash the input and compare.
This means that, when using password hashing for session IDs, there is no way to quickly look up the session based on the session ID, instead it requires re-hashing the input to separately compare against every session in the system, unfeasible especially considering this happens on every HTTP request.

Possible solutions I have considered:

Give each session an autoincrement integer ID which also appears in the cookie. This way, the "session ID"  will function as more of a session-specific password, instead of doing double duty as a password and ID. The integer will be used for lookup. This still doesn't let someone hijack a session by crafting a cookie with info they get from a database leak (or just guessing); they need the pre-hashed SID which is a long random string only appearing in the user's cookie. The disadvantage I can see is that, in the event of a cookie stealing attack, the attacker will know which session the SID corresponds to without calculating any hashes or actually attempting to hijack the session. Combined with a database leak they'll also know which user the session is for and so on. This doesn't seem like that big of a deal though. Additionally, I feel like I might be missing something bigger because there must be some reason why session management traditionally has only used a session ID (also treated as a password) in the cookie rather than a separate session ID and session-specific password.

Use Keccak for hashing session IDs and accept that session IDs don't need the same level of database leak mitigation as passwords, considering that the application requires re-authentication for sensitive actions like changing the user's password/email/etc and sessions have both an idle and absolute timeout

答:
The PHP function hash_pbkdf2 does not generate it's own salt nor does it append a salt to the output.

string hash_pbkdf2 ( string $algo , string $password , string $salt , int $iterations [, int $length = 0 [, bool $raw_output = false ]] )

The caller controls the output length, salt, iteration count and there are 45 hash algorythms to choose from.


问:
Swift - Parse - Friend list - Possibility to create groups of friends
Could someone give me a link (github/gitlab) of a swift projet which show the possibility of managing Users on Parse.

For example , I would like for a user (who have 15 friends):

to create a group with 5 friends for example (the user could add a name for this group)

to delete if necessary the group

to send a message(textfield) to a group

to send a message (textfield) to a user

For the UI, I would like if it exists, to manager user like the Springboard (having the picture of user in round), and when you longpress on it, you have a cross to delete /and 'block sign' to block user.
And the user could drag/drop other user on his friend list to create a group (like on the Springboard when you create a group of app)

Thanks for helping me !

Have a nice day!

答:
What you're asking for is pretty general and extensive. You could use Roles and Relations to manage friend groups. You could have Group objects, give them an owner, and a relation for all the members of the group.

For chat, I'd recommend not trying to just build that directly into Parse. Twilio recently released their Programmable Chat feature, which is awesome. Sounds like it'd be beneficial for you to use that.


问:
writing to/updating a TextBox in "real time" on a networked form C#
I have a windows form in visual studio 10 that connects to a python server program and receives a string of data repeatedly from the server. it then writes this string to a textbox. currently for testing purposes the server sends this string 10 times and then turns off. what i want the client to do is after it receives each string it writes it to the text box immediately but currently it waits until the server has finished and then writes the last string. the client code for this is as follows:

```<code>while (TestConnection(client))
                {
                   char tt = ' ';
                   try{
                       tt = Convert.ToChar(clientStreamReader.Read());
                       if (count < 17)
                       {
                           message = tt.ToString();
                           m += message;
                           count += 1;
                       }
                       else if (count >= 17)
                       {
                           textBox2.Text = m + "\r\n";
                           m = "";
                           count = 0;
                       }
                   }catch(OverflowException){
                            m += "";
                   }
                }
</code>```

how can I change this to write each string as they are received?

(TestConnection is a custom bool that indicates weather the connection is good)
EDIT:
(loop is inside button click event)

答:
You could write an background Worker process, which always checks in a loop if there is a new string wich can be written to your textbox.
Check out this link: example on CodeProject</p>

Body:
I have a windows form in visual studio 10 that connects to a python server program and receives a string of data repeatedly from the server. it then writes this string to a textbox. currently for testing purposes the server sends this string 10 times and then turns off. what i want the client to do is after it receives each string it writes it to the text box immediately but currently it waits until the server has finished and then writes the last string. the client code for this is as follows:

while (TestConnection(client))
                {
                   char tt = ' ';
                   try{
                       tt = Convert.ToChar(clientStreamReader.Read());
                       if (count < 17)
                       {
                           message = tt.ToString();
                           m += message;
                           count += 1;
                       }
                       else if (count >= 17)
                       {
                           textBox2.Text = m + "\r\n";
                           m = "";
                           count = 0;
                       }
                   }catch(OverflowException){
                            m += "";
                   }
                }

how can I change this to write each string as they are received?

(TestConnection is a custom bool that indicates weather the connection is good)
EDIT:
(loop is inside button click event)


问:
Cannot assign to 'Boolean' because it is a constant or a read-only property
I am creating a typescript object to represent read/write permissions in my app, but I came across this quirk in assigning the variables that makes no sense to me.  Hopefully, someone can look at this and tell me what I am doing wrong.

```<code>export class Permission {
       watcher:Object =  { read:Boolean = true};
}
</code>```

The previous code results in a error which says:

[ts] Cannot assign to 'Boolean' because it is a constant or a read-only property.
const Boolean: BooleanConstructor

I'm probably just doing something stupid, so apologies in advance if this is super newbish.

答:
If you intended to type your watcher property to be an object with property read, then it should be typed something like this:

```<code>export class Permission {
  // The part after the ":" is the type definition of the property.
  // The part after "=" is its value
  watcher: {
    read: boolean
  } = { read: true };
}
</code>```

What you currently have is probably a syntactic error. You probably do not want to override the built-in constructor Boolean with Boolean = true

Body:
I am creating a typescript object to represent read/write permissions in my app, but I came across this quirk in assigning the variables that makes no sense to me.  Hopefully, someone can look at this and tell me what I am doing wrong.

export class Permission {
       watcher:Object =  { read:Boolean = true};
}

The previous code results in a error which says:

[ts] Cannot assign to 'Boolean' because it is a constant or a read-only property.
const Boolean: BooleanConstructor

I'm probably just doing something stupid, so apologies in advance if this is super newbish.

Body:
If you intended to type your watcher property to be an object with property read, then it should be typed something like this:

export class Permission {
  // The part after the ":" is the type definition of the property.
  // The part after "=" is its value
  watcher: {
    read: boolean
  } = { read: true };
}

What you currently have is probably a syntactic error. You probably do not want to override the built-in constructor Boolean with Boolean = true


问:
Java, rJava install on AWS EC2 for R (xlsx and other packages)
I have reactivated my dormant Amazon EC2 microinstance with Ubuntu 16.04.LTS and RStudio (see sessionInfo() output below) running (thanks to AMI by Louis Aslett). After ssh-ing to the AWS instance first I've run sudo apt-get update.

When I tried installing some packages (e.g xlsx and others) in R Studio (I've got an error because of missing Java, which seems to be a common problem). I followed advices to 1) install dependencies (for e.g. xlsx like rJava, and xlsxjars) separately; 2)  apt-get install r-cran-rjava as suggested here. Then checking the installed java -version showed

openjdk version "1.8.0_131"

  OpenJDK Runtime Environment (build 1.8.0_131-8u131-b11-0ubuntu1.16.04.2-b11)

  OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

Similar problems were proposed "rJava load error in RStudio/R after “upgrading” to OSX Yosemite" and here "error: unable to load installed packages...", where the solution seemed to be linking the path of java to R export LD_LIBRARY_PATH=$JAVA_LD_LIBRARY_PATH or setting R's env. variables Sys.setenv(JAVA_HOME='/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/amd64/server').

However, running R CMD javareconf -e revealed (I suppose) some deeper issues (see Image) &/or snippet:

R CMD javareconf -e
Java interpreter : /usr/lib/jvm/default-java/jre/bin/java
Java version     : 1.8.0_131
Java home path   : /usr/lib/jvm/default-java
Java compiler    : not present
Java headers gen.:
Java archive tool:

trying to compile and link a JNI program
detected JNI cpp flags    :
detected JNI linker flags : -L$(JAVA_HOME)/jre/lib/amd64/server -ljvm
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c conftest.c -o conftest.o
conftest.c:1:17: fatal error: jni.h: No such file or directory
compilation terminated.
/usr/lib/R/etc/Makeconf:132: recipe for target 'conftest.o' failed
make: *** [conftest.o] Error 1
Unable to compile a JNI program

The following Java variables have been exported:
JAVA_HOME JAVA JAVAC JAVAH JAR JAVA_LIBS JAVA_CPPFLAGS JAVA_LD_LIBRARY_PATH
Running: /bin/bash```
</div>
</div>
</p>

<p>with Java compiler: not present and </p>

<blockquote>
  <p>conftest.c:1:17: <strong>fatal error</strong>: jni.h: No such file or directory
  compilation terminated.  /usr/lib/R/etc/Makeconf:132: recipe for target 'conftest.o' failed</p>
</blockquote>

<p>Then I've found a question "how to make jni.h be found?": here the best solution suggested <code>gcc -I/usr/lib/jvm/jdk1.7.0_07/include</code>
Checking the same directory <code>cd /usr/lib/jvm/</code> and listing its content <code>ls --all</code> showed: </p>

<blockquote>
  <p>.default-java<br>
    .java-1.8.0-openjdk-amd64.jinfo<br>
    ..java-1.8.0-openjdk-amd64
    java-8-openjdk-amd64</p>
</blockquote>

<p>Running, <code>gcc -I/usr/lib/jvm/java-1.8.0-openjdk-amd64/include</code> resulted in: <code>gcc: fatal error: no input files</code>
Additionally, I have tried <code>sudo apt-get install openjdk-X-jdk</code> (it was among the suggested answers "how to make jni.h be found?") but probably the package does not exist anymore "Unable to locate package openjdk-X-jdk". </p>

<p>Unfortunately, I am stuck and not skilled enough to implement other (seemingly more complicated solutions). I would really appreciate some help/input.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>R version 3.3.1 (2016-06-21)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.1 LTS

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] parallel  compiler  stats     graphics  grDevices utils     datasets
[8] methods   base

other attached packages:
 [1] openxlsx_4.0.17        qdapTools_1.3.1        qdapRegex_0.7.2
 [4] qdapDictionaries_1.0.6 stringr_1.1.0          stringi_1.1.2
 [7] dplyr_0.5.0            tm_0.7-1               NLP_0.1-10
[10] scales_0.4.0           RColorBrewer_1.1-2     ParallelForest_1.1.0
[13] doMC_1.3.4             iterators_1.0.8        foreach_1.4.3
[16] boot_1.3-18            reshape2_1.4.1         glmm_1.1.1
[19] Matrix_1.2-6           mvtnorm_1.0-5          trust_0.1-7
[22] ggplot2_2.1.0          shiny_0.13.2

loaded via a namespace (and not attached):
 [1] gtools_3.5.0      slam_0.1-40       lattice_0.20-33
 [4] colorspace_1.2-7  htmltools_0.3.5   chron_2.3-50
 [7] XML_3.98-1.7      DBI_0.5-1         plyr_1.8.4
[10] munsell_0.4.3     gtable_0.2.0      codetools_0.2-14
[13] httpuv_1.3.3      gender_0.5.1      Rcpp_0.12.7
[16] xtable_1.8-2      gdata_2.17.0      mime_0.5
[19] gridExtra_2.2.1   digest_0.6.10     grid_3.3.1
[22] tools_3.3.1       bitops_1.0-6      magrittr_1.5
[25] RCurl_1.95-4.8    tibble_1.2        data.table_1.10.4
[28] assertthat_0.1    R6_2.2.0          igraph_1.0.1     </code>```

答:
You need to install JDK. Take a look here as well.

http://www.owsiak.org/?p=3671

where I describe how to play with R, Java and rJava package. Even though description is macOS based, it should work with Linux as well. It's quite general approach.

Your issue is related to the fact you are using JRE instead of JDK. JNI headers are missing there.

Body:
I have reactivated my dormant Amazon EC2 microinstance with Ubuntu 16.04.LTS and RStudio (see sessionInfo() output below) running (thanks to AMI by Louis Aslett). After ssh-ing to the AWS instance first I've run sudo apt-get update.

When I tried installing some packages (e.g xlsx and others) in R Studio (I've got an error because of missing Java, which seems to be a common problem). I followed advices to 1) install dependencies (for e.g. xlsx like rJava, and xlsxjars) separately; 2)  apt-get install r-cran-rjava as suggested here. Then checking the installed java -version showed

openjdk version "1.8.0_131"

  OpenJDK Runtime Environment (build 1.8.0_131-8u131-b11-0ubuntu1.16.04.2-b11)

  OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

Similar problems were proposed "rJava load error in RStudio/R after “upgrading” to OSX Yosemite" and here "error: unable to load installed packages...", where the solution seemed to be linking the path of java to R export LD_LIBRARY_PATH=$JAVA_LD_LIBRARY_PATH or setting R's env. variables Sys.setenv(JAVA_HOME='/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/amd64/server').

However, running R CMD javareconf -e revealed (I suppose) some deeper issues (see Image) &/or snippet:

R CMD javareconf -e
Java interpreter : /usr/lib/jvm/default-java/jre/bin/java
Java version     : 1.8.0_131
Java home path   : /usr/lib/jvm/default-java
Java compiler    : not present
Java headers gen.:
Java archive tool:

trying to compile and link a JNI program
detected JNI cpp flags    :
detected JNI linker flags : -L$(JAVA_HOME)/jre/lib/amd64/server -ljvm
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c conftest.c -o conftest.o
conftest.c:1:17: fatal error: jni.h: No such file or directory
compilation terminated.
/usr/lib/R/etc/Makeconf:132: recipe for target 'conftest.o' failed
make: *** [conftest.o] Error 1
Unable to compile a JNI program

The following Java variables have been exported:
JAVA_HOME JAVA JAVAC JAVAH JAR JAVA_LIBS JAVA_CPPFLAGS JAVA_LD_LIBRARY_PATH
Running: /bin/bash

with Java compiler: not present and

conftest.c:1:17: fatal error: jni.h: No such file or directory
  compilation terminated.  /usr/lib/R/etc/Makeconf:132: recipe for target 'conftest.o' failed

Then I've found a question "how to make jni.h be found?": here the best solution suggested gcc -I/usr/lib/jvm/jdk1.7.0_07/include
Checking the same directory cd /usr/lib/jvm/ and listing its content ls --all showed:

.default-java

    .java-1.8.0-openjdk-amd64.jinfo

    ..java-1.8.0-openjdk-amd64
    java-8-openjdk-amd64

Running, gcc -I/usr/lib/jvm/java-1.8.0-openjdk-amd64/include resulted in: gcc: fatal error: no input files
Additionally, I have tried sudo apt-get install openjdk-X-jdk (it was among the suggested answers "how to make jni.h be found?") but probably the package does not exist anymore "Unable to locate package openjdk-X-jdk".

Unfortunately, I am stuck and not skilled enough to implement other (seemingly more complicated solutions). I would really appreciate some help/input.

R version 3.3.1 (2016-06-21)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.1 LTS

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] parallel  compiler  stats     graphics  grDevices utils     datasets
[8] methods   base

other attached packages:
 [1] openxlsx_4.0.17        qdapTools_1.3.1        qdapRegex_0.7.2
 [4] qdapDictionaries_1.0.6 stringr_1.1.0          stringi_1.1.2
 [7] dplyr_0.5.0            tm_0.7-1               NLP_0.1-10
[10] scales_0.4.0           RColorBrewer_1.1-2     ParallelForest_1.1.0
[13] doMC_1.3.4             iterators_1.0.8        foreach_1.4.3
[16] boot_1.3-18            reshape2_1.4.1         glmm_1.1.1
[19] Matrix_1.2-6           mvtnorm_1.0-5          trust_0.1-7
[22] ggplot2_2.1.0          shiny_0.13.2

loaded via a namespace (and not attached):
 [1] gtools_3.5.0      slam_0.1-40       lattice_0.20-33
 [4] colorspace_1.2-7  htmltools_0.3.5   chron_2.3-50
 [7] XML_3.98-1.7      DBI_0.5-1         plyr_1.8.4
[10] munsell_0.4.3     gtable_0.2.0      codetools_0.2-14
[13] httpuv_1.3.3      gender_0.5.1      Rcpp_0.12.7
[16] xtable_1.8-2      gdata_2.17.0      mime_0.5
[19] gridExtra_2.2.1   digest_0.6.10     grid_3.3.1
[22] tools_3.3.1       bitops_1.0-6      magrittr_1.5
[25] RCurl_1.95-4.8    tibble_1.2        data.table_1.10.4
[28] assertthat_0.1    R6_2.2.0          igraph_1.0.1


问:
parsing Json data with jq
Need help in parsing Json data using jq , I used to parse the data using json path as [?(@.type=='router')].externalIP. I am not sure how to do the same using jq.

The result from the query should provide the .externalIp from the type=router.
198.22.66.99

Json data snippet as below

[
  {
    "externalHostName": "localhost",
    "externalIP": "198.22.66.99",
    "internalHostName": "localhost",
    "isUp": true,
    "pod": "gateway",
    "reachable": true,
    "region": "dc-1",
     "type": [
      "router"
    ],
    "uUID": "b5f986fe-982e-47ae-8260-8a3662f25fc2"
  },
  ]```

##

答:
The description:

i would like to extract externalIP for only the array "type": [ "router" ]

The corresponding jq query is:

```<code>.[] | select(.type==["router"]) | .externalIP
</code>```

To base the query on whether "router" is amongst the specified types:

```<code>.[] | select(.type|index("router")) | .externalIP
</code>```

Title: parsing Json data with jq

Body:
Need help in parsing Json data using jq , I used to parse the data using json path as [?(@.type=='router')].externalIP. I am not sure how to do the same using jq.

The result from the query should provide the .externalIp from the type=router.
198.22.66.99

Json data snippet as below

[
  {
    "externalHostName": "localhost",
    "externalIP": "198.22.66.99",
    "internalHostName": "localhost",
    "isUp": true,
    "pod": "gateway",
    "reachable": true,
    "region": "dc-1",
     "type": [
      "router"
    ],
    "uUID": "b5f986fe-982e-47ae-8260-8a3662f25fc2"
  },
  ]

##

Body:
The description:

i would like to extract externalIP for only the array "type": [ "router" ]

The corresponding jq query is:

.[] | select(.type==["router"]) | .externalIP

To base the query on whether "router" is amongst the specified types:

.[] | select(.type|index("router")) | .externalIP


问:
printing on screen and a text file
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

```
1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >
```

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

```<code>printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
</code>```

Is there an easiest way to implement this to cut down the number of lines of code?

答:
Edit: I didn't notice you needed a C solution. I'll leave this answer for reference, but it obviously requires C++.

You could create a new stream class that sends the output to two streams. I found an implementation of this at http://www.cs.technion.ac.il/~imaman/programs/teestream.html. I haven't tried it, but it should work.

Here's the code from the link:

```<code>#include <iostream>
#include <fstream>

template<typename Elem, typename Traits = std::char_traits<Elem> >
struct basic_TeeStream : std::basic_ostream<Elem,Traits>
{
   typedef std::basic_ostream<Elem,Traits> SuperType;

   basic_TeeStream(std::ostream& o1, std::ostream& o2)
      :  SuperType(o1.rdbuf()), o1_(o1), o2_(o2) { }

   basic_TeeStream& operator<<(SuperType& (__cdecl *manip)(SuperType& ))
   {
      o1_ << manip;
      o2_ << manip;
      return *this;
   }

   template<typename T>
   basic_TeeStream& operator<<(const T& t)
   {
      o1_ << t;
      o2_ << t;
      return *this;
   }

private:
   std::ostream& o1_;
   std::ostream& o2_;
};

typedef basic_TeeStream<char> TeeStream;
</code>```

You would use it like this:

```<code>ofstream f("stackoverflow.txt");
TeeStream ts(std::cout, f);
ts << "Jon Skeet" << std::endl; // "Jon Skeet" is sent to TWO streams
</code>```

OwnerDisplayName: Thi

Title: printing on screen and a text file

Body:
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);

Is there an easiest way to implement this to cut down the number of lines of code?

LastEditorDisplayName: Jonathan Leffler

Body:
Edit: I didn't notice you needed a C solution. I'll leave this answer for reference, but it obviously requires C++.

You could create a new stream class that sends the output to two streams. I found an implementation of this at http://www.cs.technion.ac.il/~imaman/programs/teestream.html. I haven't tried it, but it should work.

Here's the code from the link:

#include <iostream>
#include <fstream>

template<typename Elem, typename Traits = std::char_traits<Elem> >
struct basic_TeeStream : std::basic_ostream<Elem,Traits>
{
   typedef std::basic_ostream<Elem,Traits> SuperType;

   basic_TeeStream(std::ostream& o1, std::ostream& o2)
      :  SuperType(o1.rdbuf()), o1_(o1), o2_(o2) { }

   basic_TeeStream& operator<<(SuperType& (__cdecl *manip)(SuperType& ))
   {
      o1_ << manip;
      o2_ << manip;
      return *this;
   }

   template<typename T>
   basic_TeeStream& operator<<(const T& t)
   {
      o1_ << t;
      o2_ << t;
      return *this;
   }

private:
   std::ostream& o1_;
   std::ostream& o2_;
};

typedef basic_TeeStream<char> TeeStream;

You would use it like this:

ofstream f("stackoverflow.txt");
TeeStream ts(std::cout, f);
ts << "Jon Skeet" << std::endl; // "Jon Skeet" is sent to TWO streams

OwnerDisplayName: Matthew Crumley

LastEditorDisplayName: Matthew Crumley


问:
Xamarin XAML vs AXML vs Storyboard
First of all, I am not even sure if this is a good question, but I am a bit confused with these concepts so I gotta go ahead and ask. Please understand that II have very limited experience with Xamarin.

I've created a project (shared class lib) and I've seen that we create forms with XAML in the shared project. However, I also discovered that there are AXML files in the Android project and Storyboard files in the iOS project, which from what I understand are used to create UI and navigation relations. If I am wrong until here, please correct me.

So the question is, which one should I be using? From what I've experimented with XAML, it is quite easy to create UI's for all platforms but why are those andoroid and ios storyboard things are there then? Or are they completely unrelated from each other?

I am doing this on VS2017 but I've also experimented on Xamarin on Visual Studio for Mac. But primarily my dev environment will be Windows.

Cheers.

答:
Storyboards only apply to iOS.  AXML only applies to Android.  XAML is used by Xamarin Forms, which can be used for both Android and iOS (and others).

If you're building a XF project, you will generally want to use XAML, unless there is some platform specific UI you need to create, in which case you (might) use the native Storyboard/AXML approach.

Title: Xamarin XAML vs AXML vs Storyboard


问:
Spring Resttemplate: Parsing using @JsonIgnore causes values to be null
So, I am using Spring Boot 1.5.3 and am trying to a part  of the following Json - - namely AccountId and Username- (actually, it is an oData v2 interface getting from a SAP Netweaver instance) into a class using restTemplate.exchange:

```<code>{
   "d":{
      "__metadata":{
         "id":"...",
         "uri":"...",
         "type":"...."
      },
      "AccountID":"0100000001",
      "Username":"test@test.com",
      "Partners":{
         "__deferred":{
            "uri":"Navigationproperty"
         }
      }
   }
}
</code>```

My class is set up like this, because for a start I only want to get the account id and name:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class PortalAccount implements Serializable{

    public PortalAccount() {
    }

    @JsonProperty("AccountID")
    public String accountID;

    @JsonProperty("Username")
    public String username;

    public String getPortalAccountID() {
        return accountID;
    }

    public void setPortalAccountID(String portalAccountID) {
        this.accountID = portalAccountID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "Account{" +
                "accountID='" + accountID + '\'' +
                ", username='" + username +'\'' +
                '}';
    }
}
</code>```

and here's the way I try to call it:

```<code>        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = this.createHeaders();
        ResponseEntity<String> response;
        response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
        ObjectMapper mapper = new ObjectMapper();

        PortalAccount acc = mapper.readValue(response.getBody(), PortalAccount.class);
</code>```

I first tried to parse it directly like in the docs using ResponseEntity<PortalAccount>, but this just lead to an empty class (accountid = null, username = null), So i tried the way above using ResponseEntity<String> to see what I get when just parsing the response into the string representation. That way, I could make sure the json above is correctly returned, which it is.So, the values are definitely there, it has to be a matter of parsing, but I sadly don't get my way around this problem.

I hope you could help me out here!

edit: As one answer mentions, getForObject might work, but this leads for me to other problems, as I have to use basic authentication, so its not really viable.I also tried casing-issues, naming the Variables accountID or AccountID, which did not work out.

答:
The problem is, that according to your JSON the ObjectMapper would require a class that contains a property of type "d" which contains two properties named "AccountId" and "Username".

So, you essentially need to only parse the content of object "d".

Parsing a subset of JSON in Java using Jackson describes how it's done.

Body:
So, I am using Spring Boot 1.5.3 and am trying to a part  of the following Json - - namely AccountId and Username- (actually, it is an oData v2 interface getting from a SAP Netweaver instance) into a class using restTemplate.exchange:

{
   "d":{
      "__metadata":{
         "id":"...",
         "uri":"...",
         "type":"...."
      },
      "AccountID":"0100000001",
      "Username":"test@test.com",
      "Partners":{
         "__deferred":{
            "uri":"Navigationproperty"
         }
      }
   }
}

My class is set up like this, because for a start I only want to get the account id and name:

@JsonIgnoreProperties(ignoreUnknown = true)
public class PortalAccount implements Serializable{

    public PortalAccount() {
    }

    @JsonProperty("AccountID")
    public String accountID;

    @JsonProperty("Username")
    public String username;

    public String getPortalAccountID() {
        return accountID;
    }

    public void setPortalAccountID(String portalAccountID) {
        this.accountID = portalAccountID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "Account{" +
                "accountID='" + accountID + '\'' +
                ", username='" + username +'\'' +
                '}';
    }
}

and here's the way I try to call it:

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = this.createHeaders();
        ResponseEntity<String> response;
        response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
        ObjectMapper mapper = new ObjectMapper();

        PortalAccount acc = mapper.readValue(response.getBody(), PortalAccount.class);

I first tried to parse it directly like in the docs using ResponseEntity<PortalAccount>, but this just lead to an empty class (accountid = null, username = null), So i tried the way above using ResponseEntity<String> to see what I get when just parsing the response into the string representation. That way, I could make sure the json above is correctly returned, which it is.So, the values are definitely there, it has to be a matter of parsing, but I sadly don't get my way around this problem.

I hope you could help me out here!

edit: As one answer mentions, getForObject might work, but this leads for me to other problems, as I have to use basic authentication, so its not really viable.I also tried casing-issues, naming the Variables accountID or AccountID, which did not work out.


问:
Power shell | Extract user name out of computer name in Domain Controller
How can I extract the user name in my active directory when I only have the computer name. </p>

<p>Obviously, no relation whats or ever between the computer name and the user name in terms of naming. </p>

答:
ArcSet's answer is great (it's what I'd do) but for basic PowerShellers, I'd have pushed them towards the AD-cmdlets like (Mitchell did):

```<code>Get-ADUser -Property samaccountname
</code>```

or even:

```<code>Get-ADObject -ldapfilter '(objectcategory=user)' -Property samaccountname
</code>```

Body:
How can I extract the user name in my active directory when I only have the computer name.

Obviously, no relation whats or ever between the computer name and the user name in terms of naming.

Body:
ArcSet's answer is great (it's what I'd do) but for basic PowerShellers, I'd have pushed them towards the AD-cmdlets like (Mitchell did):

Get-ADUser -Property samaccountname

or even:

Get-ADObject -ldapfilter '(objectcategory=user)' -Property samaccountname


问:
Python tkinter how to get text from button I clicked on
I have code like this (just part of a code). I need when someone click on the button that is in list named buttonList then it gets buttons text.
This is code how I make render of those buttons. Its normally in class I put only the main part of code here.
So how can I get buttons text on click on him ?</p>

```<code>def obsahOkna(self):

    #vykresleni
    radek = 0
    bunka = 0
    for i in range(100):
        btn = Button(self.okno, text=seznamTextu[i], width="5", height="2", bg="black", command=self.getText)
        btn.grid(row=radek, column=bunka)

        bunka += 1
        if bunka == 10 :
            bunka = 0
            radek +=1

def getText(self, udalost):
    pass
</code>```

答:
Ok so here is an example using a class to perform what I think it is you are asking.

You want to use lambda in your command and assign the value of text to a variable. Then you pass that variable to the getTest(self, text) method to be able to print your button.

From your comment

Whole code is not need i just need way to get buttons text nothing else

I have created a bit of code to illustrate what you are wanting.

EDIT: I have added code that will allow you to change the configs of the button as well.

```<code>import tkinter as tk

# created this variable in order to test your code.
seznamTextu = ["1st Button", "2nd Button", "3rd Button", "4th Button", "5th Button"]

class MyButton(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.obsahOkna()
    def obsahOkna(self):

        radek = 0
        bunka = 0
        for i in range(5):
            btn = tk.Button(self.parent, text=seznamTextu[i])
            btn.config(command= lambda t=seznamTextu[i], btn = btn: self.getText(t, btn))
            # in order for this to work you need to add the command in the config after the button is created.
            # in the lambda you need to create the variables to be passed then pass them to the function you want.
            btn.grid(row=radek, column=bunka)

            bunka += 1
            if bunka == 2 : # changed this variable to make it easier to test code.
                bunka = 0
                radek +=1

    def getText(self, text, btn):
        btn.configure(background = 'black', foreground = "white")
        print("successfully called getText")
        print(text)

if __name__ == "__main__":
    root = tk.Tk()
    myApp = MyButton(root)

    root.mainloop()
</code>```

Here is the result of running the program and pressing a couple buttons.

Body:
I have code like this (just part of a code). I need when someone click on the button that is in list named buttonList then it gets buttons text.
This is code how I make render of those buttons. Its normally in class I put only the main part of code here.
So how can I get buttons text on click on him ?

def obsahOkna(self):

    #vykresleni
    radek = 0
    bunka = 0
    for i in range(100):
        btn = Button(self.okno, text=seznamTextu[i], width="5", height="2", bg="black", command=self.getText)
        btn.grid(row=radek, column=bunka)

        bunka += 1
        if bunka == 10 :
            bunka = 0
            radek +=1

def getText(self, udalost):
    pass

Body:
Ok so here is an example using a class to perform what I think it is you are asking.

You want to use lambda in your command and assign the value of text to a variable. Then you pass that variable to the getTest(self, text) method to be able to print your button.

From your comment

Whole code is not need i just need way to get buttons text nothing else

I have created a bit of code to illustrate what you are wanting.

EDIT: I have added code that will allow you to change the configs of the button as well.

import tkinter as tk

# created this variable in order to test your code.
seznamTextu = ["1st Button", "2nd Button", "3rd Button", "4th Button", "5th Button"]

class MyButton(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.obsahOkna()
    def obsahOkna(self):

        radek = 0
        bunka = 0
        for i in range(5):
            btn = tk.Button(self.parent, text=seznamTextu[i])
            btn.config(command= lambda t=seznamTextu[i], btn = btn: self.getText(t, btn))
            # in order for this to work you need to add the command in the config after the button is created.
            # in the lambda you need to create the variables to be passed then pass them to the function you want.
            btn.grid(row=radek, column=bunka)

            bunka += 1
            if bunka == 2 : # changed this variable to make it easier to test code.
                bunka = 0
                radek +=1

    def getText(self, text, btn):
        btn.configure(background = 'black', foreground = "white")
        print("successfully called getText")
        print(text)

if __name__ == "__main__":
    root = tk.Tk()
    myApp = MyButton(root)

    root.mainloop()

Here is the result of running the program and pressing a couple buttons.


问:
Facebook block graph api access to closed groups?
I'm developing a program that read posts from groups by using
graph.facebook.com/v2.3/[group_id]/feed

I've heard that facebook is about to block the access for developers to closed groups.
but I can't find any formal mention of this.

Anyone know if it's true?

Thanks

答:
Facebook seems to remove all possibilities for users to read their own content automatically:

No more access to user groups (without being admin of that group)

No more access to messages (except for conversations with pages)

This will become a severe problem with deprecation of API v2.3 on July 8, 2017.


问:
I've seen this email protection on a website and would like to know how they have achieved this
I would like to know how I can replicate this sort of email protection and what parts of it actually does what please.</p>

```<code> <a href="cdn-cgi/l/email-protection.html#d7a7a5bea1b6b4ae97b0b6a3bfb2a5b4b8b9a3b2b9a3f9b4b8ba"><span class="__cf_email__" data-cfemail="0474766d7265677d446365706c6176676b6a70616a702a676b69">[email protected]</span><script data-cfhash='f9e31' type="text/javascript">/* <![CDATA[ */!function(t,e,r,n,c,a,p){try{t=document.currentScript||function(){for(t=document.getElementsByTagName('script'),e=t.length;e--;)if(t[e].getAttribute('data-cfhash'))return t[e]}();if(t&&(c=t.previousSibling)){p=t.parentNode;if(a=c.getAttribute('data-cfemail')){for(e='',r='0x'+a.substr(0,2)|0,n=2;a.length-n;n+=2)e+='%'+('0'+('0x'+a.substr(n,2)^r).toString(16)).slice(-2);p.replaceChild(document.createTextNode(decodeURIComponent(e)),c)}p.removeChild(t)}}catch(u){}}()/* ]]> */</script></a>
</code>```

答:
This is CloudFlare's dynamic email obfuscation. CloudFlare automatically apply the obfuscation to websites that they protect.

If your website is protected by CloudFlare, you can turn the feature on by signing in to the dashboard then Cloudflare.com > ScrapeShield > Email Obfuscation.

Body:
I would like to know how I can replicate this sort of email protection and what parts of it actually does what please.

 [email protected]