问:
How to amend my code to split the supplied text?
This text need to be break like the image below. I tried to use regex but did not get a very good result:

ص6:9؛ 17:1؛ 24:40؛ 2مل20:3؛ مز128:1؛ مي6:8؛ ملا2:> 6

The result needed to be like this:

ص6:9 * ص - 6 - 9

17:1 * ص - 17 - 1

24:40 * ص - 24 - 40

2مل20:3 * 2مل - 20 - 3

مز128:1 * مز - 128 - 1

مي6:8 * مي - 6 - 8

ملا2:6 * ملا - 2 - 6

The result came out from this string

ص6:9 * ص - 6 - 9

 17:1 *  - 17 - 1

 24:40 *  - 24 - 40

 2مل20:3 * مل - 220 - 3

 مز128:1 * مز - 128 - 1

 مي6:8 * مي - 6 - 8

 ملا2:6 * ملا - 2 - 6

This the code I used and edit it several times

```<code> Public Function SplitVerseCrossRefrence(Numbers As String, InputString As String) As String
    'RR = 0
    Dim Result As String = ""
    Dim OldBookId As String = ""
    Dim MyStr As New StringBuilder
    Dim WordList As New List(Of String)
    '
    Dim forbdin() As Char = {":", "-", ";", "،", "؛"}
    '
    Try
        If InputString.IndexOf("؛") > -1 Then
            WordList.AddRange(InputString.Split("؛").ToList())
        Else
            WordList.Add(InputString)
        End If
        '
        Result = ""
        '
        For Each Word In WordList
            '
            Dim strArray As Char() = Word.ToCharArray
            '
            For xxx As Integer = 0 To strArray.Count - 1
                '
                Dim CleanText = strArray(xxx)
                '
                If IsNumeric(CleanText) = False Then
                    MyStr.Append(CleanText)
                Else
                    If MyStr.Length = 0 Then
                        MyStr.Append(CleanText)
                    End If
                End If
                '
            Next

            Dim MyItem As String = MyStr.ToString.Trim
            '
            For ss As Integer = 0 To forbdin.Count - 1
                MyItem = MyItem.Replace(forbdin(ss).ToString.Trim, String.Empty).Trim
            Next
            '
            If IsNumeric(MyItem.Trim) = False Or MyItem.Trim <> "" Then
                OldBookId = MyItem
            Else
                MyItem = OldBookId
            End If

            If MyItem.Length >= 2 Then
                OldBookId = MyItem
            Else
                MyItem = OldBookId
            End If
            '
            Dim MyChapter As New StringBuilder
            Dim ChapterArry() = Word.Split(":")(0).Trim.ToArray

            For xx As Integer = 0 To ChapterArry.Count - 1
                If xx >= 0 Then
                    If IsNumeric(ChapterArry(xx)) = True Then
                        MyChapter.Append(ChapterArry(xx))
                    End If
                End If
            Next
            '
            Dim VersesCheck = Word.Split(":")(1).Trim
            Dim VersesFrom, VersesTo
            '
            If VersesCheck.Contains("-") = True Then
                VersesFrom = VersesCheck.Split("-")(0)
                VersesTo = VersesCheck.Split("-")(1)
            ElseIf VersesCheck.Contains("،") = True Then
                VersesFrom = VersesCheck.Split("،")(0)
                VersesTo = VersesCheck.Split("،")(1)
            Else
                VersesFrom = VersesCheck
                VersesTo = 0
            End If
            '
            If MyItem = "ص" Then
                MyItem = Numbers.Split(".")(0)
            End If
            '
            Result = Result & Word & " * " & MyItem & " - " & MyChapter.ToString & " - " & VersesFrom & "<br />" & vbCrLf
            MyStr.Clear()
        Next
    Catch ex As Exception
        Result = InputString
    End Try
    Return Result
End Function
</code>```

But the result not as I need.

答:
This Function help me to get the right result i post it. so if any one need it </p>

```<code> Public Function SplitText(InputString As String) As String
    Dim Result As String = ""
    Dim OldBookId As String = ""
    Dim MyStr As New StringBuilder
    Dim MyChapter As New StringBuilder
    Dim WordList As New List(Of String)
    '
    Try
        '
        If InputString.IndexOf("؛") > -1 Then
            WordList.AddRange(InputString.Split("؛").ToList())
        Else
            WordList.Add(InputString)
        End If
        '
        Result = "" '"( "

        For Each Word In WordList

            Dim IsCheck As Boolean = False
            Dim A() As String = Word.Split(":")
            Dim AName As String = A(0).Trim
            Dim RevAName As String = StrReverse(AName)
            Dim strArray() As Char = RevAName.ToArray
            '
            For xxx As Integer = 0 To UBound(strArray)
                '
                'txtLog.AppendText(AscW(strArray(xxx)) & vbCrLf)
                '
                If AscW(strArray(xxx)) <> 8207 Then
                    If IsNumeric(strArray(xxx)) = True And IsCheck = False Then
                        'strArray.RemoveAt(xxx)
                        MyChapter.Append(strArray(xxx))
                    Else
                        IsCheck = True
                        MyStr.Append(strArray(xxx))
                    End If
                End If
                '
            Next
            '
            Dim MyItem As String = StrReverse(MyStr.ToString.Trim)
            '
            If MyItem <> "" Then
                OldBookId = MyItem
            Else
                MyItem = OldBookId
            End If
            '
            Dim VersesCheck = A(1)
            Dim VersesFrom, VersesTo
            '
            If VersesCheck.Contains("-") = True Then
                VersesFrom = VersesCheck.Split("-")(0)
                VersesTo = VersesCheck.Split("-")(1)
            ElseIf VersesCheck.Contains("،") = True Then
                VersesFrom = VersesCheck.Split("،")(0)
                VersesTo = VersesCheck.Split("،")(1)
            Else
                VersesFrom = VersesCheck
                VersesTo = 0
            End If
            '
            Result = Result & Word & " * " & MyItem & " - " & StrReverse(MyChapter.ToString) & " - " & VersesFrom & " - " & VersesTo & vbCrLf

            MyChapter.Clear()
            MyStr.Clear()
            IsCheck = False
            '
        Next

    Catch ex As Exception
        Result = InputString
    End Try
    '
    Return Result
    '
End Function
</code>```

Body:
This text need to be break like the image below. I tried to use regex but did not get a very good result:

ص6:9؛ 17:1؛ 24:40؛ 2مل20:3؛ مز128:1؛ مي6:8؛ ملا2:> 6

The result needed to be like this:

ص6:9 * ص - 6 - 9

17:1 * ص - 17 - 1

24:40 * ص - 24 - 40

2مل20:3 * 2مل - 20 - 3

مز128:1 * مز - 128 - 1

مي6:8 * مي - 6 - 8

ملا2:6 * ملا - 2 - 6

The result came out from this string

ص6:9 * ص - 6 - 9

 17:1 *  - 17 - 1

 24:40 *  - 24 - 40

 2مل20:3 * مل - 220 - 3

 مز128:1 * مز - 128 - 1

 مي6:8 * مي - 6 - 8

 ملا2:6 * ملا - 2 - 6

This the code I used and edit it several times

 Public Function SplitVerseCrossRefrence(Numbers As String, InputString As String) As String
    'RR = 0
    Dim Result As String = ""
    Dim OldBookId As String = ""
    Dim MyStr As New StringBuilder
    Dim WordList As New List(Of String)
    '
    Dim forbdin() As Char = {":", "-", ";", "،", "؛"}
    '
    Try
        If InputString.IndexOf("؛") > -1 Then
            WordList.AddRange(InputString.Split("؛").ToList())
        Else
            WordList.Add(InputString)
        End If
        '
        Result = ""
        '
        For Each Word In WordList
            '
            Dim strArray As Char() = Word.ToCharArray
            '
            For xxx As Integer = 0 To strArray.Count - 1
                '
                Dim CleanText = strArray(xxx)
                '
                If IsNumeric(CleanText) = False Then
                    MyStr.Append(CleanText)
                Else
                    If MyStr.Length = 0 Then
                        MyStr.Append(CleanText)
                    End If
                End If
                '
            Next

            Dim MyItem As String = MyStr.ToString.Trim
            '
            For ss As Integer = 0 To forbdin.Count - 1
                MyItem = MyItem.Replace(forbdin(ss).ToString.Trim, String.Empty).Trim
            Next
            '
            If IsNumeric(MyItem.Trim) = False Or MyItem.Trim <> "" Then
                OldBookId = MyItem
            Else
                MyItem = OldBookId
            End If

            If MyItem.Length >= 2 Then
                OldBookId = MyItem
            Else
                MyItem = OldBookId
            End If
            '
            Dim MyChapter As New StringBuilder
            Dim ChapterArry() = Word.Split(":")(0).Trim.ToArray

            For xx As Integer = 0 To ChapterArry.Count - 1
                If xx >= 0 Then
                    If IsNumeric(ChapterArry(xx)) = True Then
                        MyChapter.Append(ChapterArry(xx))
                    End If
                End If
            Next
            '
            Dim VersesCheck = Word.Split(":")(1).Trim
            Dim VersesFrom, VersesTo
            '
            If VersesCheck.Contains("-") = True Then
                VersesFrom = VersesCheck.Split("-")(0)
                VersesTo = VersesCheck.Split("-")(1)
            ElseIf VersesCheck.Contains("،") = True Then
                VersesFrom = VersesCheck.Split("،")(0)
                VersesTo = VersesCheck.Split("،")(1)
            Else
                VersesFrom = VersesCheck
                VersesTo = 0
            End If
            '
            If MyItem = "ص" Then
                MyItem = Numbers.Split(".")(0)
            End If
            '
            Result = Result & Word & " * " & MyItem & " - " & MyChapter.ToString & " - " & VersesFrom & "
" & vbCrLf
            MyStr.Clear()
        Next
    Catch ex As Exception
        Result = InputString
    End Try
    Return Result
End Function

But the result not as I need.

Body:
This Function help me to get the right result i post it. so if any one need it

 Public Function SplitText(InputString As String) As String
    Dim Result As String = ""
    Dim OldBookId As String = ""
    Dim MyStr As New StringBuilder
    Dim MyChapter As New StringBuilder
    Dim WordList As New List(Of String)
    '
    Try
        '
        If InputString.IndexOf("؛") > -1 Then
            WordList.AddRange(InputString.Split("؛").ToList())
        Else
            WordList.Add(InputString)
        End If
        '
        Result = "" '"( "

        For Each Word In WordList

            Dim IsCheck As Boolean = False
            Dim A() As String = Word.Split(":")
            Dim AName As String = A(0).Trim
            Dim RevAName As String = StrReverse(AName)
            Dim strArray() As Char = RevAName.ToArray
            '
            For xxx As Integer = 0 To UBound(strArray)
                '
                'txtLog.AppendText(AscW(strArray(xxx)) & vbCrLf)
                '
                If AscW(strArray(xxx)) <> 8207 Then
                    If IsNumeric(strArray(xxx)) = True And IsCheck = False Then
                        'strArray.RemoveAt(xxx)
                        MyChapter.Append(strArray(xxx))
                    Else
                        IsCheck = True
                        MyStr.Append(strArray(xxx))
                    End If
                End If
                '
            Next
            '
            Dim MyItem As String = StrReverse(MyStr.ToString.Trim)
            '
            If MyItem <> "" Then
                OldBookId = MyItem
            Else
                MyItem = OldBookId
            End If
            '
            Dim VersesCheck = A(1)
            Dim VersesFrom, VersesTo
            '
            If VersesCheck.Contains("-") = True Then
                VersesFrom = VersesCheck.Split("-")(0)
                VersesTo = VersesCheck.Split("-")(1)
            ElseIf VersesCheck.Contains("،") = True Then
                VersesFrom = VersesCheck.Split("،")(0)
                VersesTo = VersesCheck.Split("،")(1)
            Else
                VersesFrom = VersesCheck
                VersesTo = 0
            End If
            '
            Result = Result & Word & " * " & MyItem & " - " & StrReverse(MyChapter.ToString) & " - " & VersesFrom & " - " & VersesTo & vbCrLf

            MyChapter.Clear()
            MyStr.Clear()
            IsCheck = False
            '
        Next

    Catch ex As Exception
        Result = InputString
    End Try
    '
    Return Result
    '
End Function


来源: stackexchange

问:
Java 8 Streams map versus peek
Can someone explain to me why peek and map produce different outcomes in this code ?</p>

```<code>List<String> alphabets = Arrays.asList(new String[]{"a","b","c"});

List<String> upper1 = alphabets.stream().peek(l -> l.toUpperCase()).collect(Collectors.toList());
upper1.forEach(System.out::println);

List<String> upper2 = alphabets.stream().map(l -> l.toUpperCase()).collect(Collectors.toList());
upper2.forEach(System.out::println);```

Output :-
a
b
c
A
B
C
</code>```

答:
Peek is an intermediate operation and exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.

An example of how peek could be used in your code:

```<code>List<String> alphabets = Arrays.asList(new String[]{"a","b","c"});

List<String> upper = alphabets.stream()
           .peek(l -> System.out.println("Filtered value: " + l))
           .map(l -> l.toUpperCase())
           .peek(l -> System.out.println("Mapped value: " + l))
           .collect(Collectors.toList());
upper.forEach(System.out::println);
</code>```

This outputs:

```<code>Filtered value: a
Mapped value: A
Filtered value: b
Mapped value: B
Filtered value: c
Mapped value: C
A
B
C
</code>```

While the results of map is a stream of the results applying the given function in peak it's just the original stream of the results.
And since strings in java are immutable the result of peak won't be affected by executing the function.

If the elements were references (as objects) and the peek function updated the content of that references they would have been updated, but it's not the case here.

An example of peek with a MyString object:

```<code>class MyString {
    String str;

    MyString(String str) {
        this.str = str;
    }

    public void toUpperCase() {
        str = str.toUpperCase();
    }

    @Override
    public String toString() {
        super.toString();
        return str;
    }
}

List<MyString> alphabets = Arrays.asList(new MyString[]{new MyString("a"), new MyString("b"), new MyString("c")});

List<MyString> upper = alphabets.stream()
        .peek(l -> l.toUpperCase())
        .collect(Collectors.toList());

upper.forEach(System.out::println);

</code>```

see the full code here:

http://tpcg.io/6GlwFizW

You can see there that the output is:

```<code>A
B
C
</code>```

as we are altering the inner state of each element in this case.

Notice that I did on purpose that MyString.toUpperCase() returns void instead of a MyString object, so it would fail with map this way.

ContentLicense: CC BY-SA 4.0

Title: Java 8 Streams map versus peek

Body:
Can someone explain to me why peek and map produce different outcomes in this code ?

List<String> alphabets = Arrays.asList(new String[]{"a","b","c"});

List<String> upper1 = alphabets.stream().peek(l -> l.toUpperCase()).collect(Collectors.toList());
upper1.forEach(System.out::println);

List<String> upper2 = alphabets.stream().map(l -> l.toUpperCase()).collect(Collectors.toList());
upper2.forEach(System.out::println);```

Output :-
a
b
c
A
B
C

Body:
Peek is an intermediate operation and exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.

An example of how peek could be used in your code:

List<String> alphabets = Arrays.asList(new String[]{"a","b","c"});

List<String> upper = alphabets.stream()
           .peek(l -> System.out.println("Filtered value: " + l))
           .map(l -> l.toUpperCase())
           .peek(l -> System.out.println("Mapped value: " + l))
           .collect(Collectors.toList());
upper.forEach(System.out::println);

This outputs:

Filtered value: a
Mapped value: A
Filtered value: b
Mapped value: B
Filtered value: c
Mapped value: C
A
B
C

While the results of map is a stream of the results applying the given function in peak it's just the original stream of the results.
And since strings in java are immutable the result of peak won't be affected by executing the function.

If the elements were references (as objects) and the peek function updated the content of that references they would have been updated, but it's not the case here.

An example of peek with a MyString object:

class MyString {
    String str;

    MyString(String str) {
        this.str = str;
    }

    public void toUpperCase() {
        str = str.toUpperCase();
    }

    @Override
    public String toString() {
        super.toString();
        return str;
    }
}

List<MyString> alphabets = Arrays.asList(new MyString[]{new MyString("a"), new MyString("b"), new MyString("c")});

List<MyString> upper = alphabets.stream()
        .peek(l -> l.toUpperCase())
        .collect(Collectors.toList());

upper.forEach(System.out::println);

see the full code here:

http://tpcg.io/6GlwFizW

You can see there that the output is:

A
B
C

as we are altering the inner state of each element in this case.

Notice that I did on purpose that MyString.toUpperCase() returns void instead of a MyString object, so it would fail with map this way.


问:
Automatically set Entity as modified when updating Bridge Table?
I have two tables (TableA and TableB) with a bridge table between. I have entities setup properly for both, including navigation properties for the Many-To-Many relationship. Both entities extend an 'AuditBase' class that includes 'Modified/Created Date and ModifiedBy/CreatedBy User'.

Using a commit method, this audit info is automatically updated for any Entities that extend 'AuditBase' and are in the Created/Modified states.

Currently, I have code in certain Save methods to manually set the entity for TableB to 'modified' when items are added/removed from the many-to-many relationship via navigation property. This way the audit data is updated automatically, even though nothing in TableB has actually changed.

I could keep using this pattern, but would like to see if there is some way to remove the manual step of checking for updates to bridge table. Is there any way that I could detect pending changes to this Bridge table prior to calling Save (in my commit method), and flag the associated Entity as modified?

Configuration of the Bridge Table in question -

```<code>            this.HasMany(u => u.TableA)
                .WithMany(r => r.TableB)
                .Map(m =>
                     {
                         m.ToTable("TableA_TableB", "dbo");
                         m.MapLeftKey("TableA_Id");
                         m.MapRightKey("TableB_Id");
                     });
</code>```

And here is the code used to find the modified entities right now -

```<code>    this._context.ChangeTracker.DetectChanges();
    var addedAuditedEntities =
        this._context.ChangeTracker.Entries<AuditModelBase>().Where(p => p.State ==
        EntityState.Added).Select(p => p.Entity);
    var modifiedAuditedEntities =
        this._context.ChangeTracker.Entries<AuditModelBase>().Where(p => p.State ==
        EntityState.Modified).Select(p => p.Entity);
</code>```

答:
you didn't provide any sample code but you can override SaveChanges method and control the related entities states.

something like this. eg.

 public class AppDbContext : DbContex
....

        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges();

            var modifiled = ChangeTracker.Entries<BRIDGE_TABLE_ENTITY>().Where(x => x.State == EntityState.Added || x.State == EntityState.Deleted || x.State == EntityState.Modified);
            foreach (var item in modifiled)
            {
                 item.Property("TABLEA_REF_PROP_NAME").EntityEntry.State = EntityState.Modified;
                 item.Property("TABLEB_REF_PROP_NAME").EntityEntry.State = EntityState.Modified;
            }

            ChangeTracker.AutoDetectChangesEnabled =
               false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChanges();
            ChangeTracker.AutoDetectChangesEnabled = true;
            return result;
        }
```

UPDATE

depending on your sample code the short answer is if you need to use ChangeTracker for your bridge table, you must create a separate entity to provide access to it

Body:
I have two tables (TableA and TableB) with a bridge table between. I have entities setup properly for both, including navigation properties for the Many-To-Many relationship. Both entities extend an 'AuditBase' class that includes 'Modified/Created Date and ModifiedBy/CreatedBy User'.

Using a commit method, this audit info is automatically updated for any Entities that extend 'AuditBase' and are in the Created/Modified states.

Currently, I have code in certain Save methods to manually set the entity for TableB to 'modified' when items are added/removed from the many-to-many relationship via navigation property. This way the audit data is updated automatically, even though nothing in TableB has actually changed.

I could keep using this pattern, but would like to see if there is some way to remove the manual step of checking for updates to bridge table. Is there any way that I could detect pending changes to this Bridge table prior to calling Save (in my commit method), and flag the associated Entity as modified?

Configuration of the Bridge Table in question -

            this.HasMany(u => u.TableA)
                .WithMany(r => r.TableB)
                .Map(m =>
                     {
                         m.ToTable("TableA_TableB", "dbo");
                         m.MapLeftKey("TableA_Id");
                         m.MapRightKey("TableB_Id");
                     });

And here is the code used to find the modified entities right now -

    this._context.ChangeTracker.DetectChanges();
    var addedAuditedEntities =
        this._context.ChangeTracker.Entries<AuditModelBase>().Where(p => p.State ==
        EntityState.Added).Select(p => p.Entity);
    var modifiedAuditedEntities =
        this._context.ChangeTracker.Entries<AuditModelBase>().Where(p => p.State ==
        EntityState.Modified).Select(p => p.Entity);

Body:
you didn't provide any sample code but you can override SaveChanges method and control the related entities states.

something like this. eg.

 public class AppDbContext : DbContex
....

        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges();

            var modifiled = ChangeTracker.Entries<BRIDGE_TABLE_ENTITY>().Where(x => x.State == EntityState.Added || x.State == EntityState.Deleted || x.State == EntityState.Modified);
            foreach (var item in modifiled)
            {
                 item.Property("TABLEA_REF_PROP_NAME").EntityEntry.State = EntityState.Modified;
                 item.Property("TABLEB_REF_PROP_NAME").EntityEntry.State = EntityState.Modified;
            }

            ChangeTracker.AutoDetectChangesEnabled =
               false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChanges();
            ChangeTracker.AutoDetectChangesEnabled = true;
            return result;
        }

UPDATE

depending on your sample code the short answer is if you need to use ChangeTracker for your bridge table, you must create a separate entity to provide access to it


问:
HackerRank Weather Observation Station 5
I would like to know why my code isnt working. This question has been asked before here:
Query the two cities in STATION with the shortest and longest CITY names,

and solution here:
https://github.com/chhayac/SQL-hackerrank-problems/blob/master/basic-select.md

But both answers do not work. I have pasted the question below followed by my solution. Thanks for the help!

Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.

Input Format

The STATION table is described as follows:

```<code>Station.jpg
</code>```

where LAT_N is the northern latitude and LONG_W is the western longitude.

Sample Input

Let's say that CITY only has four entries: DEF, ABC, PQRS and WXY

Sample Output

```<code>ABC 3
PQRS 4
</code>```

Explanation

When ordered alphabetically, the CITY names are listed as ABC, DEF, PQRS, and WXY, with the respective lengths  and . The longest-named city is obviously PQRS, but there are  options for shortest-named city; we choose ABC, because it comes first alphabetically.

Note
You can write two separate queries to get the desired output. It need not be a single query.

MY ANSWER:

/shortest character length sorted in alphabetical order/

```<code>SELECT city, LENGTH(city) as length_char
FROM station
ORDER BY LENGTH(city) ASC, city ASC
LIMIT 1;
</code>```

/longest character length sorted in alphabetical order/

```<code>SELECT city, LENGTH(city) as length_char
FROM station
ORDER BY LENGTH(city) DESC
LIMIT 1;
</code>```

答:
You can also use this query as a slightly different answer. I used a subquery in the WHERE clause in MySQL</p>

```<code>select CITY,LENGTH(CITY) from STATION where LENGTH(CITY)= (select min(LENGTH(CITY))from STATION) order by CITY LIMIT 1;
select CITY,LENGTH(CITY) from STATION where LENGTH(CITY)= (select max(LENGTH(CITY))from STATION) order by CITY LIMIT 1;
</code>```

Body:
I would like to know why my code isnt working. This question has been asked before here:
Query the two cities in STATION with the shortest and longest CITY names,

and solution here:
https://github.com/chhayac/SQL-hackerrank-problems/blob/master/basic-select.md

But both answers do not work. I have pasted the question below followed by my solution. Thanks for the help!

Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.

Input Format

The STATION table is described as follows:

Station.jpg

where LAT_N is the northern latitude and LONG_W is the western longitude.

Sample Input

Let's say that CITY only has four entries: DEF, ABC, PQRS and WXY

Sample Output

ABC 3
PQRS 4

Explanation

When ordered alphabetically, the CITY names are listed as ABC, DEF, PQRS, and WXY, with the respective lengths  and . The longest-named city is obviously PQRS, but there are  options for shortest-named city; we choose ABC, because it comes first alphabetically.

Note
You can write two separate queries to get the desired output. It need not be a single query.

MY ANSWER:

/shortest character length sorted in alphabetical order/

SELECT city, LENGTH(city) as length_char
FROM station
ORDER BY LENGTH(city) ASC, city ASC
LIMIT 1;

/longest character length sorted in alphabetical order/

SELECT city, LENGTH(city) as length_char
FROM station
ORDER BY LENGTH(city) DESC
LIMIT 1;

Body:
You can also use this query as a slightly different answer. I used a subquery in the WHERE clause in MySQL

select CITY,LENGTH(CITY) from STATION where LENGTH(CITY)= (select min(LENGTH(CITY))from STATION) order by CITY LIMIT 1;
select CITY,LENGTH(CITY) from STATION where LENGTH(CITY)= (select max(LENGTH(CITY))from STATION) order by CITY LIMIT 1;


问:
How to explicitly compile stack scripts, or cache the compiled object code?
I'm currently using a stack script, and am wondering if this could be sped up by explicitly compiling it to an executable, or alternatively caching the object code so that stack will not recompile every time. Maybe it is already doing the latter - certainly it is for dependencies, just not sure about the object code of the script itself. In which case, I guess I just need to write faster code!</p>

答:
You can use stack exec ghc to call the ghc installed by stack. Example usage:

```<code>stack exec ghc --resolver lts-15.0 -- -o test Test.hs
</code>```

Body:
You can use stack exec ghc to call the ghc installed by stack. Example usage:

stack exec ghc --resolver lts-15.0 -- -o test Test.hs


问:
How to implement draggable tab using Java Swing?
How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.

EDIT: The Java Tutorials - Drag and Drop and Data Transfer.

答:
Curses! Beaten to the punch by a Google search.  Unfortunately it's true there is no easy way to create draggable tab panes (or any other components) in Swing.  So whilst the example above is complete this one I've just written is a bit simpler. So it will hopefully demonstrate the more advanced techniques involved a bit clearer.  The steps are:

Detect that a drag has occurred

Draw the dragged tab to an offscreen buffer

Track the mouse position whilst dragging occurs

Draw the tab in the buffer on top of the component.

The above example will give you what you want but if you want to really understand the techniques applied here it might be a better exercise to round off the edges of this example and add the extra features demonstrated above to it.

Or maybe I'm just disappointed because I spent time writing this solution when one already existed :p

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;

public class DraggableTabbedPane extends JTabbedPane {

  private boolean dragging = false;
  private Image tabImage = null;
  private Point currentMouseLocation = null;
  private int draggedTabIndex = 0;

  public DraggableTabbedPane() {
    super();
    addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseDragged(MouseEvent e) {

        if(!dragging) {
          // Gets the tab index based on the mouse position
          int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY());

          if(tabNumber >= 0) {
            draggedTabIndex = tabNumber;
            Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber);

            // Paint the tabbed pane to a buffer
            Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics totalGraphics = totalImage.getGraphics();
            totalGraphics.setClip(bounds);
            // Don't be double buffered when painting to a static image.
            setDoubleBuffered(false);
            paintComponent(totalGraphics);

            // Paint just the dragged tab to the buffer
            tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
            Graphics graphics = tabImage.getGraphics();
            graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this);

            dragging = true;
            repaint();
          }
        } else {
          currentMouseLocation = e.getPoint();

          // Need to repaint
          repaint();
        }

        super.mouseDragged(e);
      }
    });

    addMouseListener(new MouseAdapter() {
      public void mouseReleased(MouseEvent e) {

        if(dragging) {
          int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10);

          if(tabNumber >= 0) {
            Component comp = getComponentAt(draggedTabIndex);
            String title = getTitleAt(draggedTabIndex);
            removeTabAt(draggedTabIndex);
            insertTab(title, null, comp, null, tabNumber);
          }
        }

        dragging = false;
        tabImage = null;
      }
    });
  }

  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Are we dragging?
    if(dragging && currentMouseLocation != null && tabImage != null) {
      // Draw the dragged tab
      g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this);
    }
  }

  public static void main(String[] args) {
    JFrame test = new JFrame("Tab test");
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    test.setSize(400, 400);

    DraggableTabbedPane tabs = new DraggableTabbedPane();
    tabs.addTab("One", new JButton("One"));
    tabs.addTab("Two", new JButton("Two"));
    tabs.addTab("Three", new JButton("Three"));
    tabs.addTab("Four", new JButton("Four"));

    test.add(tabs);
    test.setVisible(true);
  }
}
```

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Tom Martin

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Tom Martin


问:
Glyph not shown in PDF
In the creation of PDF document based on information of a specific system, using fop, i cannot show special characters, showing '#' instead of the character and giving me this WARNS when i create the pdf.

```<code>12:49:18,637 WARN  [org.apache.fop.apps.FOUserAgent] (default task-3) Glyph "?" (0x11f, gbreve) not available in font "Helvetica".
12:49:18,640 WARN  [org.apache.fop.apps.FOUserAgent] (default task-3) Glyph "?" (0x15e, Scedilla) not available in font "Helvetica".
12:49:19,041 INFO  [org.apache.fop.apps.FOUserAgent] (default task-3) Rendered page #1.
12:49:19,203 WARN  [org.apache.fop.apps.FOUserAgent] (default task-3) Glyph "?" (0x11f, gbreve) not available in font "Helvetica-Bold".
12:49:19,206 WARN  [org.apache.fop.apps.FOUserAgent] (default task-3) Glyph "?" (0x15e, Scedilla) not available in font "Helvetica-Bold".
</code>```

I already changed font family in .xsl but no progress, now it sits like that, i think this uses fop.xconf, which has all the fonts and types.

```<code> <!-- Helvetica -->
        <font>
          <afp-font name="Helvetica" type="raster" codepage="T1V10500" encoding="Cp500">
....
</font>
</code>```

and .xsl:

```<code><fo:block-container absolute-position="absolute" left="25mm" top="42mm" width="160mm" height="100mm"
                                        background-color="rgb(178,178,178)">
                        <fo:block color="white" font-size="29pt">
                            <fo:inline font-weight="bold">PDF</fo:inline> Report <xsl:value-of select="year"/>
                        </fo:block>
                        <fo:block color="white" font-size="16pt" margin-top="3mm">
                            <xsl:value-of select="name"/>
                        </fo:block>
                        <fo:block color="white" font-size="16pt">
                            <xsl:value-of select="address"/>
                        </fo:block>
                    </fo:block-container>
</code>```

what can i do more? this is new to me, and already saw some similar threads in Stackoverflow, but none of them really helped.

EDIT: Quick update, maybe the xconf is not used at all? because i already removed all from there and there's no change, cause i am trying to add FreeSerif but none happened..

答:
lfurini, i saw your  old answer and i'am stuck an step 2, because i don't have that 'conf' dir.
I'am using it on a Java program, i got it in src/main/resources/pdf/fopfactorybasedir inside that dir i have one folder to display the images on my pdf and fop.xconf file ( that  i can't find anywhere in the code.. so that's why i am saying that is not used at all.. ) here's my code..

FopFactoryWithUserAgentAndTransformerFactoryService

```<code>@ApplicationScoped
        public class FopFactoryWithUserAgentAndTransformerFactoryService {
            private static final Logger LOG =
    LoggerFactory.getLogger(FopFactoryWithUserAgentAndTransformerFactoryService.class);
            private static final String ROOT_PATH = "/pdf/fopfactorybasedir/";
            private final FopFactory fopFactory;
            private final FOUserAgent foUserAgent;
            private final TransformerFactory transformerFactory;

            public FopFactoryWithUserAgentAndTransformerFactoryService() throws URISyntaxException {
                final URI uri = FopFactoryWithUserAgentAndTransformerFactoryService.class.getResource(ROOT_PATH).toURI();
                LOG.info("fopBaseUri={}", uri);
                fopFactory = FopFactory.newInstance(uri);
                foUserAgent = fopFactory.newFOUserAgent();
                transformerFactory = TransformerFactory.newInstance();
            }

            public FopFactory getFopFactory() {
                return fopFactory;
            }
        public Fop newFop(final String outputFormat, final OutputStream out) throws FOPException {
                return fopFactory.newFop(outputFormat, foUserAgent, out);
            }
            ...
</code>```

PDFFactory:

```<code>@ApplicationScoped
public class PdfFactory {

@Inject
private FopFactoryWithUserAgentAndTransformerFactoryService fopFactoryEtAl;

public PdfFactory() {

}

public PdfFactory(final FopFactoryWithUserAgentAndTransformerFactoryService fopFactoryEtAl) {
    this.fopFactoryEtAl = fopFactoryEtAl;
}
public ByteArrayDto generatePdfFromModelObject(final Object model, final String xslFileName)
....
</code>```

The question is, how can i use my fop.xconf file? maybe if i use it, the   will be enough... ?

Title: Glyph not shown in PDF

Body:
In the creation of PDF document based on information of a specific system, using fop, i cannot show special characters, showing '#' instead of the character and giving me this WARNS when i create the pdf.

12:49:18,637 WARN  [org.apache.fop.apps.FOUserAgent] (default task-3) Glyph "?" (0x11f, gbreve) not available in font "Helvetica".
12:49:18,640 WARN  [org.apache.fop.apps.FOUserAgent] (default task-3) Glyph "?" (0x15e, Scedilla) not available in font "Helvetica".
12:49:19,041 INFO  [org.apache.fop.apps.FOUserAgent] (default task-3) Rendered page #1.
12:49:19,203 WARN  [org.apache.fop.apps.FOUserAgent] (default task-3) Glyph "?" (0x11f, gbreve) not available in font "Helvetica-Bold".
12:49:19,206 WARN  [org.apache.fop.apps.FOUserAgent] (default task-3) Glyph "?" (0x15e, Scedilla) not available in font "Helvetica-Bold".

I already changed font family in .xsl but no progress, now it sits like that, i think this uses fop.xconf, which has all the fonts and types.

          <afp-font name="Helvetica" type="raster" codepage="T1V10500" encoding="Cp500">
....

and .xsl:

<fo:block-container absolute-position="absolute" left="25mm" top="42mm" width="160mm" height="100mm"
                                        background-color="rgb(178,178,178)">
                        <fo:block color="white" font-size="29pt">
                            <fo:inline font-weight="bold">PDF</fo:inline> Report <xsl:value-of select="year"/>
                        </fo:block>
                        <fo:block color="white" font-size="16pt" margin-top="3mm">
                            <xsl:value-of select="name"/>
                        </fo:block>
                        <fo:block color="white" font-size="16pt">
                            <xsl:value-of select="address"/>
                        </fo:block>
                    </fo:block-container>

what can i do more? this is new to me, and already saw some similar threads in Stackoverflow, but none of them really helped.

EDIT: Quick update, maybe the xconf is not used at all? because i already removed all from there and there's no change, cause i am trying to add FreeSerif but none happened..

Body:
lfurini, i saw your  old answer and i'am stuck an step 2, because i don't have that 'conf' dir.
I'am using it on a Java program, i got it in src/main/resources/pdf/fopfactorybasedir inside that dir i have one folder to display the images on my pdf and fop.xconf file ( that  i can't find anywhere in the code.. so that's why i am saying that is not used at all.. ) here's my code..

FopFactoryWithUserAgentAndTransformerFactoryService

@ApplicationScoped
        public class FopFactoryWithUserAgentAndTransformerFactoryService {
            private static final Logger LOG =
    LoggerFactory.getLogger(FopFactoryWithUserAgentAndTransformerFactoryService.class);
            private static final String ROOT_PATH = "/pdf/fopfactorybasedir/";
            private final FopFactory fopFactory;
            private final FOUserAgent foUserAgent;
            private final TransformerFactory transformerFactory;

            public FopFactoryWithUserAgentAndTransformerFactoryService() throws URISyntaxException {
                final URI uri = FopFactoryWithUserAgentAndTransformerFactoryService.class.getResource(ROOT_PATH).toURI();
                LOG.info("fopBaseUri={}", uri);
                fopFactory = FopFactory.newInstance(uri);
                foUserAgent = fopFactory.newFOUserAgent();
                transformerFactory = TransformerFactory.newInstance();
            }

            public FopFactory getFopFactory() {
                return fopFactory;
            }
        public Fop newFop(final String outputFormat, final OutputStream out) throws FOPException {
                return fopFactory.newFop(outputFormat, foUserAgent, out);
            }
            ...

PDFFactory:

@ApplicationScoped
public class PdfFactory {

@Inject
private FopFactoryWithUserAgentAndTransformerFactoryService fopFactoryEtAl;

public PdfFactory() {

}

public PdfFactory(final FopFactoryWithUserAgentAndTransformerFactoryService fopFactoryEtAl) {
    this.fopFactoryEtAl = fopFactoryEtAl;
}
public ByteArrayDto generatePdfFromModelObject(final Object model, final String xslFileName)
....

The question is, how can i use my fop.xconf file? maybe if i use it, the   will be enough... ?


问:
How do I solve [EIdSMTPReplyError] Authentication unsuccessful?
I'm trying to use SMTP with TLS and Office365. I'm able to successfully send an email using powershell and TLS but with the below example I'm currently stuck with error:

Project SMTP_SSL_Example.exe raised exception class EIdSMTPReplyError
  with message 'Authentication unsuccessful
  [JN2P275CA0026.ZAFP275.PROD.OUTLOOK.COM]'

The connection is successful but the authentication part in the code fails.  I've previously been told that the response is coming from the server. If I get a successful mail using PowerShell how come this differs?  Any ideas?

I'm using Indy 10.6.2.5366.

Update: I'm also getting the same kind of error with another component suit.  I just don't understand why Powershell is allowing me to send the mail but I can't programmatically.

```<code>procedure TForm28.Method2Click(Sender: TObject);
var
  idSMTP1: TIdSMTP;
  idSASLLogin: TIdSASLLogin;
  idUserPassProvider: TIdUserPassProvider;
begin
  idSMTP1 := TIdSMTP.Create(nil);
  try
    idSMTP1.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(idSMTP1);
    idSMTP1.UseTLS := utUseExplicitTLS;
    TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.Method := sslvTLSv1;

    idSMTP1.Host := 'smtp.office365.com';
    idSMTP1.Port := StrToInt(cbPort.Text);

    idSASLLogin := TIdSASLLogin.Create(idSMTP1);
    idUserPassProvider := TIdUserPassProvider.Create(idSASLLogin);

    idSASLLogin.UserPassProvider := idUserPassProvider;
    idUserPassProvider.Username := 'my username';
    idUserPassProvider.Password := 'my passowrd';

    idSMTP1.AuthType := satSASL;
    idSMTP1.SASLMechanisms.Add.SASL := idSASLLogin;

    try
      idSMTP1.Connect;
      try
        idSMTP1.Authenticate;
        SendEmail(idSMTP1);
      finally
        idSMTP1.Disconnect;
      end;
      ShowMessage('OK');
    except
      on E: Exception do
      begin
        ShowMessage(Format('Failed!'#13'[%s] %s', [E.ClassName, E.Message]));
        raise;
      end;
    end;
  finally
    idSMTP1.Free;
  end;
end;

procedure TForm28.Mehod1Click(Sender: TObject);
var
  idSMTP1: TIdSMTP;
begin
  idSMTP1 := TIdSMTP.Create(nil);
  try
    idSMTP1.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(idSMTP1);
    idSMTP1.UseTLS := utUseExplicitTLS;
    TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.Method := sslvTLSv1;

    idSMTP1.Host := 'smtp.office365.com';
    idSMTP1.Port := StrToInt(cbPort.Text);

    idSMTP1.AuthType := satDefault;
    idSMTP1.Username := 'my username';
    idSMTP1.Password := 'my password';

    try
      idSMTP1.Connect;
      try
        idSMTP1.Authenticate;
        SendEmail(idSMTP1);
      finally
        idSMTP1.Disconnect;
      end;
      ShowMessage('OK');
    except
      on E: Exception do
      begin
        ShowMessage(Format('Failed!'#13'[%s] %s', [E.ClassName, E.Message]));
        raise;
      end;
    end;
  finally
    idSMTP1.Free;
  end;
end;
</code>```

答:
Office 365 will soon require TLS 1.2, but your code is forcing Indy to use TLS 1.0 instead. Office 365 officially does not support TLS 1.0 or 1.1 anymore, but it still accepts 1.0/1.1 sessions for the time being, but that will change in the coming months.

So, at the very least, you need to change this:

TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.Method := sslvTLSv1;
```

<p>To this:</p>

<pre class="lang-pascal prettyprint-override"><code>TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.Method := sslvTLSv1_2;
</code>```

Or better, to this:

TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];
```

That being said, using TIdSASLLogin as the sole SASL mechanism is exactly the same as using TIdSMTP.AuthType=satDefault. They both send the same AUTH LOGIN command to the server. And that command is what is failing. But there is no way to know for sure exactly why that is happening. "Authentication unsuccessful" is too generic an error message, and there are many reasons why that error occurs in Office 365. Maybe you are using the wrong username/password. Maybe the IP address resolved from the hostname being sent by TIdSMTP in its EHLO command 1 is not whitelisted on the server. Who knows.

1: try setting the TIdSMTP.HeloName property to a FQDN for your client machine, which you can get from GetComputerNameEx().

Body:
I'm trying to use SMTP with TLS and Office365. I'm able to successfully send an email using powershell and TLS but with the below example I'm currently stuck with error:

Project SMTP_SSL_Example.exe raised exception class EIdSMTPReplyError
  with message 'Authentication unsuccessful
  [JN2P275CA0026.ZAFP275.PROD.OUTLOOK.COM]'

The connection is successful but the authentication part in the code fails.  I've previously been told that the response is coming from the server. If I get a successful mail using PowerShell how come this differs?  Any ideas?

I'm using Indy 10.6.2.5366.

Update: I'm also getting the same kind of error with another component suit.  I just don't understand why Powershell is allowing me to send the mail but I can't programmatically.

procedure TForm28.Method2Click(Sender: TObject);
var
  idSMTP1: TIdSMTP;
  idSASLLogin: TIdSASLLogin;
  idUserPassProvider: TIdUserPassProvider;
begin
  idSMTP1 := TIdSMTP.Create(nil);
  try
    idSMTP1.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(idSMTP1);
    idSMTP1.UseTLS := utUseExplicitTLS;
    TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.Method := sslvTLSv1;

    idSMTP1.Host := 'smtp.office365.com';
    idSMTP1.Port := StrToInt(cbPort.Text);

    idSASLLogin := TIdSASLLogin.Create(idSMTP1);
    idUserPassProvider := TIdUserPassProvider.Create(idSASLLogin);

    idSASLLogin.UserPassProvider := idUserPassProvider;
    idUserPassProvider.Username := 'my username';
    idUserPassProvider.Password := 'my passowrd';

    idSMTP1.AuthType := satSASL;
    idSMTP1.SASLMechanisms.Add.SASL := idSASLLogin;

    try
      idSMTP1.Connect;
      try
        idSMTP1.Authenticate;
        SendEmail(idSMTP1);
      finally
        idSMTP1.Disconnect;
      end;
      ShowMessage('OK');
    except
      on E: Exception do
      begin
        ShowMessage(Format('Failed!'#13'[%s] %s', [E.ClassName, E.Message]));
        raise;
      end;
    end;
  finally
    idSMTP1.Free;
  end;
end;

procedure TForm28.Mehod1Click(Sender: TObject);
var
  idSMTP1: TIdSMTP;
begin
  idSMTP1 := TIdSMTP.Create(nil);
  try
    idSMTP1.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(idSMTP1);
    idSMTP1.UseTLS := utUseExplicitTLS;
    TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.Method := sslvTLSv1;

    idSMTP1.Host := 'smtp.office365.com';
    idSMTP1.Port := StrToInt(cbPort.Text);

    idSMTP1.AuthType := satDefault;
    idSMTP1.Username := 'my username';
    idSMTP1.Password := 'my password';

    try
      idSMTP1.Connect;
      try
        idSMTP1.Authenticate;
        SendEmail(idSMTP1);
      finally
        idSMTP1.Disconnect;
      end;
      ShowMessage('OK');
    except
      on E: Exception do
      begin
        ShowMessage(Format('Failed!'#13'[%s] %s', [E.ClassName, E.Message]));
        raise;
      end;
    end;
  finally
    idSMTP1.Free;
  end;
end;

Body:
Office 365 will soon require TLS 1.2, but your code is forcing Indy to use TLS 1.0 instead. Office 365 officially does not support TLS 1.0 or 1.1 anymore, but it still accepts 1.0/1.1 sessions for the time being, but that will change in the coming months.

So, at the very least, you need to change this:

TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.Method := sslvTLSv1;

To this:

TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.Method := sslvTLSv1_2;

Or better, to this:

TIdSSLIOHandlerSocketOpenSSL(idSMTP1.IOHandler).SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];

That being said, using TIdSASLLogin as the sole SASL mechanism is exactly the same as using TIdSMTP.AuthType=satDefault. They both send the same AUTH LOGIN command to the server. And that command is what is failing. But there is no way to know for sure exactly why that is happening. "Authentication unsuccessful" is too generic an error message, and there are many reasons why that error occurs in Office 365. Maybe you are using the wrong username/password. Maybe the IP address resolved from the hostname being sent by TIdSMTP in its EHLO command 1 is not whitelisted on the server. Who knows.

1: try setting the TIdSMTP.HeloName property to a FQDN for your client machine, which you can get from GetComputerNameEx().


问:
How to remove test IAP purchase from Android Google Play
I set up a beta account to test IAP for google app that I am working on, the issue I have is, once I have purchased One-time products(non-recurring charge) the test IAP, I cannot 'remove it' as such, so now, even when I delete the app and re-install, it remembers the purchase, that's great in the real world for a user, but not great when trying to fix the bugs! </p>

<p>Is there any way (short of making a ton of gmail accounts to test with) to remove the purchase from the account? </p>

答:
I encountered the same situation and started to research. Unfortunately, the directions made here did not produce a solution.

I want to share the solution that worked for me.

If you call the method below in the right place, the solution will be produced. Source : Link

```<code>/**
     * Recall that Google Play Billing only supports two SKU types:
     * [in-app products][BillingClient.SkuType.INAPP] and
     * [subscriptions][BillingClient.SkuType.SUBS]. In-app products are actual items that a
     * user can buy, such as a house or food; subscriptions refer to services that a user must
     * pay for regularly, such as auto-insurance. Subscriptions are not consumable.
     *
     * Play Billing provides methods for consuming in-app products because they understand that
     * apps may sell items that users will keep forever (i.e. never consume) such as a house,
     * and consumable items that users will need to keep buying such as food. Nevertheless, Google
     * Play leaves the distinction for which in-app products are consumable entirely up to you.
     *
     * If an app wants its users to be able to keep buying an item, it must call
     * [BillingClient.consumeAsync] each time they buy it. This is because Google Play won't let
     * users buy items that they've previously bought but haven't consumed. In Trivial Drive, for
     * example, consumeAsync is called each time the user buys gas; otherwise they would never be
     * able to buy gas or drive again once the tank becomes empty.
     */

    private fun clearIapHistory() {
            billingClient!!.queryPurchases(BillingClient.SkuType.INAPP).purchasesList
                .forEach {
                    val params =
                        ConsumeParams.newBuilder().setPurchaseToken(it.purchaseToken).build()
                    billingClient!!.consumeAsync(params) { responseCode, purchaseToken ->
                        when (responseCode.responseCode) {
                            BillingClient.BillingResponseCode.OK -> {

                            }
                            else -> {
                                Log.w(LOG_TAG, responseCode.debugMessage)
                            }
                        }
                    }
                }
        }
</code>```

Body:
I set up a beta account to test IAP for google app that I am working on, the issue I have is, once I have purchased One-time products(non-recurring charge) the test IAP, I cannot 'remove it' as such, so now, even when I delete the app and re-install, it remembers the purchase, that's great in the real world for a user, but not great when trying to fix the bugs!

Is there any way (short of making a ton of gmail accounts to test with) to remove the purchase from the account?

Body:
I encountered the same situation and started to research. Unfortunately, the directions made here did not produce a solution.

I want to share the solution that worked for me.

If you call the method below in the right place, the solution will be produced. Source : Link

/**
     * Recall that Google Play Billing only supports two SKU types:
     * [in-app products][BillingClient.SkuType.INAPP] and
     * [subscriptions][BillingClient.SkuType.SUBS]. In-app products are actual items that a
     * user can buy, such as a house or food; subscriptions refer to services that a user must
     * pay for regularly, such as auto-insurance. Subscriptions are not consumable.
     *
     * Play Billing provides methods for consuming in-app products because they understand that
     * apps may sell items that users will keep forever (i.e. never consume) such as a house,
     * and consumable items that users will need to keep buying such as food. Nevertheless, Google
     * Play leaves the distinction for which in-app products are consumable entirely up to you.
     *
     * If an app wants its users to be able to keep buying an item, it must call
     * [BillingClient.consumeAsync] each time they buy it. This is because Google Play won't let
     * users buy items that they've previously bought but haven't consumed. In Trivial Drive, for
     * example, consumeAsync is called each time the user buys gas; otherwise they would never be
     * able to buy gas or drive again once the tank becomes empty.
     */

    private fun clearIapHistory() {
            billingClient!!.queryPurchases(BillingClient.SkuType.INAPP).purchasesList
                .forEach {
                    val params =
                        ConsumeParams.newBuilder().setPurchaseToken(it.purchaseToken).build()
                    billingClient!!.consumeAsync(params) { responseCode, purchaseToken ->
                        when (responseCode.responseCode) {
                            BillingClient.BillingResponseCode.OK -> {

                            }
                            else -> {
                                Log.w(LOG_TAG, responseCode.debugMessage)
                            }
                        }
                    }
                }
        }


问:
Making the configuration available to all classes
I'm writing a small web server, and it takes a configuration file with all sorts of different options: how many threads to run, which class deals which each file extension, which file to display by default and so on and so forth. To represent this, I'm parsing the config file into a Configuration object which contains all these settings, and the main class holds this object.

However, the config data is required on almost every level of the server - classes within classes within classes...

My question is, what is the best practice to use here? Should I give the config as a parameter for many many classes and pass it back and forth? Should I make it a singleton? Is there another solution I don't see?

答:
Configuration not, but It's good to have one singleton object ServerManager. Too many globally accessible objects are are little bit confusing. Configuration should by owned by "component":

```<code>ServerManager.getServerManager.getConfigurationComponent(Configuration.class);
</code>```

ServerManager should create and read configuration object at start time. Save and close it before leaving.

If you use it more than once in any class store it as private final field.

Body:
Configuration not, but It's good to have one singleton object ServerManager. Too many globally accessible objects are are little bit confusing. Configuration should by owned by "component":

ServerManager.getServerManager.getConfigurationComponent(Configuration.class);

ServerManager should create and read configuration object at start time. Save and close it before leaving.

If you use it more than once in any class store it as private final field.


问:
SSRS SQL closest future date to current date
I have a table of securities (added spaces for better readability) with coupon payment dates (if it's a bond) and I need to make a table where for every client and security he owns, there is a column with only next coupon payment. If its a share, it will  be in the table but with no payment.
So from column coupon payment date, I need to select only the next coupon payment date.

from this(let's call it table 'Coupons':

    ClientName I SecID I  SecType I   CouponPaymentdate

    Client1 I US00001 I Bond I 06/2017

    Client1 I US00001 I Bond I 06/2018

Client1 I US00001 I Bond I 06/2019

Client1 I US00001 I Bond I 06/2020

Client1 I US00001 I Bond I 06/2021

Client1 I US00002 I Bond I 03/2019

Client1 I US00002 I Bond I 03/2020

Client1 I US00002 I Bond I 03/2021

Client2 I US00003 I Share I -

Client3 I US00004 I Bond I 01/2017

Client3 I US00004 I Bond I 01/2018

desired result

ClientName I SecID I SecType I NextCouponPaymentdate

Client1 I US00001 I Bond I 06/2020

Client1 I US00002 I Bond I 03/2020

Client2 I US00003 I Share I -

for this column I tried this, but I need to break ClientName and SecID

   (SELECT TOP 1 Coupons.CouponPaymentDate FROM Coupons as CPN
   WHERE CPN.CouponPaymentDate > GETDATE()
   ORDER BY CPN.CouponPaymentDate)

Any advice? I use SSRS, so maybe even an expression for this would be helpful but I have no idea. Thank you (Sorry for formatting)

答:
The following should work. Just replace @t with your actual table name

```<code>SELECT
        ClientName, SecID, SecType, NextCouponPaymentDate = CouponPaymentdate
    FROM (
            SELECT
                *
                , RowN = ROW_NUMBER() OVER(PARTITION BY ClientName, SecID ORDER BY CouponPaymentdate)
            FROM @t WHERE CouponPaymentdate > getdate() OR SecType = 'Share'
            ) x
    WHERE RowN =1
</code>```

Ignoring the date format I used (YYYY-MM-DD) and the fact that I set the payments dates to hte first of each month, this gives you what you wanted

Body:
The following should work. Just replace @t with your actual table name

SELECT
        ClientName, SecID, SecType, NextCouponPaymentDate = CouponPaymentdate
    FROM (
            SELECT
                *
                , RowN = ROW_NUMBER() OVER(PARTITION BY ClientName, SecID ORDER BY CouponPaymentdate)
            FROM @t WHERE CouponPaymentdate > getdate() OR SecType = 'Share'
            ) x
    WHERE RowN =1

Ignoring the date format I used (YYYY-MM-DD) and the fact that I set the payments dates to hte first of each month, this gives you what you wanted


问:
oracle: get a specific date with a condition
I have this table with the information of each flight movement and the information of the origin and destination for a plane ticket for that flight.

```<code>   RESERVATION  FLIGHT ORIG  DEST   DT                PASSENGER_CODE PASSEN_ORI  PASSEN_DEST
    --------------------------------------------------------------------------------------------
    111         LA111   MSP   LAX   01/01/2020 21:30   ABC            LAX          MIA
    111         LA111   LAX   JFK   01/01/2020 23:00   ABC            LAX          MIA
    111         LA111   JFK   MIA   02/01/2020 01:00   ABC            LAX          MIA
    111         LA111   MIA   ATL   02/01/2020 02:00   ABC            LAX          MIA
    111         LA112   MIA   PHX   02/01/2020 03:00   ABC            MIA          ARG
    111         LA112   PHX   SCL   02/01/2020 18:45   ABC            MIA          ARG
    111         LA112   SCL   ARG   02/01/2020 23:00   ABC            MIA          ARG
    111         LA112   ARG   LIM   03/01/2020 03:00   ABC            MIA          ARG
</code>```

i need get the info for the flight but only the date time of the departure and arrival made by the person associated with the plane ticket

```<code>   RESERVATION  FLIGHTS   FL_INI_ROU  FL_END_ROU PASSEN_ROUTE PASSEN_DEPARTURE_DT PASSEN_ARRIVAL_DT
    ------------------------------------------------------------------------------------------------
    111       LA111-LA112   MSP-ATL   MIA-LIM  LAX-ARG        01/01/2020 23:00    02/01/2020 23:00
</code>```

I tried to get the dates for departure and arrival in 2 queries and then join them with union, but I find it inefficient.

THX!

答:
Group data by reservation and flight at first, then in next step only by reservation. This way you can find all needed values:

```<code>select reservation, listagg(flight, '-') within group (order by mnd) flights,
       min(orig) keep (dense_rank first order by r1) || ' - '
         || min(dest) keep (dense_rank first order by r1) as ini_rt,
       min(orig) keep (dense_rank first order by r2) || ' - '
         || min(dest) keep (dense_rank first order by r2) as end_rt,
       min(o1) keep (dense_rank first order by r1) || ' - '
         || min(o2) keep (dense_rank first order by r2) as route,
       min(mnd) dep_dt, max(mxd) arr_dt
  from (
    select reservation, flight,
           min(orig) keep (dense_rank first order by dt) orig,
           min(dest) keep (dense_rank last order by dt) dest,
           row_number() over (order by min(dt)) r1,
           row_number() over (order by min(dt) desc) r2,
           min(passen_ori) keep (dense_rank first order by dt) o1,
           min(passen_dest) keep (dense_rank last order by dt) o2,
           min(dt) mnd, max(dt) mxd
      from flights
      group by reservation, flight )
  group by reservation
</code>```

dbfiddle

Body:
I have this table with the information of each flight movement and the information of the origin and destination for a plane ticket for that flight.

   RESERVATION  FLIGHT ORIG  DEST   DT                PASSENGER_CODE PASSEN_ORI  PASSEN_DEST
    --------------------------------------------------------------------------------------------
    111         LA111   MSP   LAX   01/01/2020 21:30   ABC            LAX          MIA
    111         LA111   LAX   JFK   01/01/2020 23:00   ABC            LAX          MIA
    111         LA111   JFK   MIA   02/01/2020 01:00   ABC            LAX          MIA
    111         LA111   MIA   ATL   02/01/2020 02:00   ABC            LAX          MIA
    111         LA112   MIA   PHX   02/01/2020 03:00   ABC            MIA          ARG
    111         LA112   PHX   SCL   02/01/2020 18:45   ABC            MIA          ARG
    111         LA112   SCL   ARG   02/01/2020 23:00   ABC            MIA          ARG
    111         LA112   ARG   LIM   03/01/2020 03:00   ABC            MIA          ARG

i need get the info for the flight but only the date time of the departure and arrival made by the person associated with the plane ticket

   RESERVATION  FLIGHTS   FL_INI_ROU  FL_END_ROU PASSEN_ROUTE PASSEN_DEPARTURE_DT PASSEN_ARRIVAL_DT
    ------------------------------------------------------------------------------------------------
    111       LA111-LA112   MSP-ATL   MIA-LIM  LAX-ARG        01/01/2020 23:00    02/01/2020 23:00

I tried to get the dates for departure and arrival in 2 queries and then join them with union, but I find it inefficient.

THX!

Body:
Group data by reservation and flight at first, then in next step only by reservation. This way you can find all needed values:

select reservation, listagg(flight, '-') within group (order by mnd) flights,
       min(orig) keep (dense_rank first order by r1) || ' - '
         || min(dest) keep (dense_rank first order by r1) as ini_rt,
       min(orig) keep (dense_rank first order by r2) || ' - '
         || min(dest) keep (dense_rank first order by r2) as end_rt,
       min(o1) keep (dense_rank first order by r1) || ' - '
         || min(o2) keep (dense_rank first order by r2) as route,
       min(mnd) dep_dt, max(mxd) arr_dt
  from (
    select reservation, flight,
           min(orig) keep (dense_rank first order by dt) orig,
           min(dest) keep (dense_rank last order by dt) dest,
           row_number() over (order by min(dt)) r1,
           row_number() over (order by min(dt) desc) r2,
           min(passen_ori) keep (dense_rank first order by dt) o1,
           min(passen_dest) keep (dense_rank last order by dt) o2,
           min(dt) mnd, max(dt) mxd
      from flights
      group by reservation, flight )
  group by reservation

dbfiddle


问:
Convert List<String[]> to Object[][] 2d array in Java
I am trying to transform a List of string arrays to 2D object arrays  Object[][].

Here is what I have so far. Is this correct?

```<code>private static Object[][] listToObject2dConvert(List<String[]> convertor) {
    Object[][] array = new Object[convertor.size()][];

    for (int i = 0; i < array.length; i++) {
        array[i] = new Object[convertor.get(i).length];
    }

    for (int i = 0; i < convertor.size(); i++){
        for (int j = 0; j < convertor.get(i).length; j++) {
            array[i][j] = convertor.get(i).length;
        }
    }
    return array;
}
</code>```

答:
Try this.</p>

```<code>    public static void main(String[] args) {
        List<String[]> convertor =
              List.of(new String[]{"a","b","c"}, new String[]{"e","f","g"});
        Object[][] objs = listToObject2dConvert(convertor);
        for (Object[] o : objs) {
            System.out.println(Arrays.toString(o));
        }
    }
    // just assign the array that's in the List to the 2D array column entry.
    private static Object[][] listToObject2dConvert(List<String[]> convertor){
        Object[][] array= new Object[convertor.size()][];
        int i = 0;
        for (String[] s : convertor) {
            array[i++] = s;
        }
        return array;
    }
</code>```

Body:
I am trying to transform a List of string arrays to 2D object arrays  Object[][].

Here is what I have so far. Is this correct?

private static Object[][] listToObject2dConvert(List<String[]> convertor) {
    Object[][] array = new Object[convertor.size()][];

    for (int i = 0; i < array.length; i++) {
        array[i] = new Object[convertor.get(i).length];
    }

    for (int i = 0; i < convertor.size(); i++){
        for (int j = 0; j < convertor.get(i).length; j++) {
            array[i][j] = convertor.get(i).length;
        }
    }
    return array;
}

Body:
Try this.

    public static void main(String[] args) {
        List<String[]> convertor =
              List.of(new String[]{"a","b","c"}, new String[]{"e","f","g"});
        Object[][] objs = listToObject2dConvert(convertor);
        for (Object[] o : objs) {
            System.out.println(Arrays.toString(o));
        }
    }
    // just assign the array that's in the List to the 2D array column entry.
    private static Object[][] listToObject2dConvert(List<String[]> convertor){
        Object[][] array= new Object[convertor.size()][];
        int i = 0;
        for (String[] s : convertor) {
            array[i++] = s;
        }
        return array;
    }


问:
Laravel 'popper.js is null' when clicking on a bootstrap 4 div with class 'input-group-prepend'
I receive the following error in the console when I click on element that's surrounded by a div with the class input-group-prepend:

TypeError: popper is null app.js:50778:3

If I remove the surrounding div the click function works, but I need the div for UI reasons.

The element

```<code>...
<div class="input-group-prepend">
   <button class="btn btn-outline-secondary dropdown-toggle"
           type="button" data-toggle="dropdown"
           aria-haspopup="true" aria-expanded="false">Filter
   </button>
</div>
...
</code>```

Jquery click function

```<code>...
$(".dropdown-item-container").click(function(event) {
  event.stopPropagation();
  console.log($(this));
});
...
</code>```

My guess was that I hadn't included popper.js correctly in boostrap.js.

My bootstrap.js file:

```<code>...
try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}
...
</code>```

I tried some of the seemingly related solutions described here, but I wasn't able to get them to work: Can't load popper.js with webpack and Laravel mix.

I use:

Laravel version: 6.7.0

Popper.js version: ^1.16.0

Bootstrap version: ^4.0.0

答:
By default, the div.dropdown-menu should be sibling to the button[data-toggle="dropdown"]. Maybe that's the problem.

If you don't want to change the HTML structure, you'll have to define the reference setting on dropdown options (e.g. data-reference="parent"). See https://getbootstrap.com/docs/4.4/components/dropdowns/#options

Body:
I receive the following error in the console when I click on element that's surrounded by a div with the class input-group-prepend:

TypeError: popper is null app.js:50778:3

If I remove the surrounding div the click function works, but I need the div for UI reasons.

The element

...

   <button class="btn btn-outline-secondary dropdown-toggle"
           type="button" data-toggle="dropdown"
           aria-haspopup="true" aria-expanded="false">Filter
   </button>

...

Jquery click function

...
$(".dropdown-item-container").click(function(event) {
  event.stopPropagation();
  console.log($(this));
});
...

My guess was that I hadn't included popper.js correctly in boostrap.js.

My bootstrap.js file:

...
try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}
...

I tried some of the seemingly related solutions described here, but I wasn't able to get them to work: Can't load popper.js with webpack and Laravel mix.

I use:

Laravel version: 6.7.0

Popper.js version: ^1.16.0

Bootstrap version: ^4.0.0


答:
Just add ( in the character class:

```<code>(?<=\()[^(:]+
//     __^
</code>```

Demo & explanation

Title: Regular expression to match a string between parenthesis and comma, but with multiple parenthesis present

Body:
I am trying to use regex to match strings (which are species names+codes, e.g. diadema1479) in a phylogenetic tree in parenthetical notation, but I'm not being successful to deal with all the parenthesis.

Here's a sample of my data

(diadema1479:0.20268621848058304691,longipes1483:0.18941326141716441356):0.05754190478991345892,((sp1_11269:0.08954446656323425402,(davidovi11375:0.12866818058352805232):0.02407442773179632040):0.11326732171695803875,(((S_willeyi:0.16019503647856672690,(((((S_sp2:0.13155607959902493320,S_sp3:0.04602288122852762897):0.09795419683476988548,S_sp4:0.03464730266968370220):0.06696262102745857703,S_sp5_Lombok:0.00000100000050002909):0.01699644302538915949,((S_javensis:0.12205647213742974733,(S_sp6:0.07046365005123975123,((yayukae12168:0.01496242382530112158,(yayukae12109:0.01287526689678352571...

When I use:

/(?<=\()[^:]+/g

It matches, for example, 'diadema1479' and 'davidovi11375', but includes all extra parenthesis in '((((S_sp2'. How can I set it not to match any parenthesis at all?

Thanks!

Body:
Just add ( in the character class:

(?<=\()[^(:]+
//     __^

Demo & explanation


问:
KiteWorks API using HttpWebRequest and MultipartFormDataContent
```<code>jsonWebClient.DataContent = new System.Net.Http.MultipartFormDataContent();
ByteArrayContent bytes = new ByteArrayContent(File.ReadAllBytes(data.LocalFile));
bytes.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
jsonWebClient.DataContent.Add(bytes, "file", data.FileName);
jsonWebClient.DataContent.Add(bytes, "name", data.FileName);
jsonWebClient.DataContent.Add(new StringContent($"{Connection.UserId}"), "userId");
jsonWebClient.DataContent.Add(new StringContent($"{data.ParentId}"), "parentId");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.CreationTime}"), "created");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.LastWriteTime}"), "modified");
jsonWebClient.DataContent.Add(new StringContent($"{DateTime.Now}"), "clientCreated");
jsonWebClient.DataContent.Add(new StringContent($"{DateTime.Now}"), "clientModified");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.Length}"), "size");
</code>```

So I am trying generate a MultipartFormDataContent to convert to a Byte Array or stream. When I do the stream:

```<code>Stream stream = _dataContent.ReadAsStreamAsync().Result;
</code>```

I get a out of memory exception.

When I try to do:

```<code>byte[] bytes = _dataContent.ReadAsByteArrayAsync().Result;
</code>```

or

```<code>byte[] bytes = _dataContent.ReadAsByteArrayAsync().GetAwaiter().GetResult();
</code>```

It just sits there forever and does nothing. What can I do to make it convert to the proper byte array?

答:
Original source [How would I run an async Task method synchronously?][Rachel]How would I run an async Task<T> method synchronously?     method-synchronously

```<code>public static class AsyncHelpers
{
   /// <summary>
   /// Execute's an async Task<T> method which has a void return value synchronously
   /// </summary>
   /// <param name="task">Task<T> method to execute</param>
   public static void RunSync(Func<Task> task)
   {
      var oldContext = SynchronizationContext.Current;
      var synch = new ExclusiveSynchronizationContext();
      SynchronizationContext.SetSynchronizationContext(synch);
      synch.Post(async _ =>
      {
          try
          {
              await task();
          }
          catch (Exception e)
          {
              synch.InnerException = e;
              throw;
          }
          finally
          {
              synch.EndMessageLoop();
          }
       }, null);
      synch.BeginMessageLoop();

      SynchronizationContext.SetSynchronizationContext(oldContext);
  }

  /// <summary>
  /// Execute's an async Task<T> method which has a T return type synchronously
  /// </summary>
  /// <typeparam name="T">Return Type</typeparam>
  /// <param name="task">Task<T> method to execute</param>
  /// <returns></returns>
  public static T RunSync<T>(Func<Task<T>> task)
  {
     var oldContext = SynchronizationContext.Current;
     var synch = new ExclusiveSynchronizationContext();
     SynchronizationContext.SetSynchronizationContext(synch);
     T ret = default(T);
     synch.Post(async _ =>
     {
         try
         {
             ret = await task();
         }
         catch (Exception e)
         {
             synch.InnerException = e;
             throw;
         }
         finally
         {
             synch.EndMessageLoop();
         }
     }, null);
     synch.BeginMessageLoop();
     SynchronizationContext.SetSynchronizationContext(oldContext);
     return ret;
 }

 private class ExclusiveSynchronizationContext : SynchronizationContext
 {
    private bool done;
    public Exception InnerException { get; set; }
    readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false);
    readonly Queue<Tuple<SendOrPostCallback, object>> items =
        new Queue<Tuple<SendOrPostCallback, object>>();

    public override void Send(SendOrPostCallback d, object state)
    {
        throw new NotSupportedException("We cannot send to our same thread");
    }

    public override void Post(SendOrPostCallback d, object state)
    {
        lock (items)
        {
            items.Enqueue(Tuple.Create(d, state));
        }
        workItemsWaiting.Set();
    }

    public void EndMessageLoop()
    {
        Post(_ => done = true, null);
    }

    public void BeginMessageLoop()
    {
        while (!done)
        {
            Tuple<SendOrPostCallback, object> task = null;
            lock (items)
            {
                if (items.Count > 0)
                {
                    task = items.Dequeue();
                }
            }
            if (task != null)
            {
                task.Item1(task.Item2);
                if (InnerException != null) // the method threw an exeption
                {
                    throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
                }
            }
            else
            {
                workItemsWaiting.WaitOne();
            }
        }
    }

    public override SynchronizationContext CreateCopy()
    {
        return this;
    }
  }
}
</code>```

With this class I was able to convert it right away without waiting and there was no issues with Out of Memory Exception.

Body:
jsonWebClient.DataContent = new System.Net.Http.MultipartFormDataContent();
ByteArrayContent bytes = new ByteArrayContent(File.ReadAllBytes(data.LocalFile));
bytes.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
jsonWebClient.DataContent.Add(bytes, "file", data.FileName);
jsonWebClient.DataContent.Add(bytes, "name", data.FileName);
jsonWebClient.DataContent.Add(new StringContent($"{Connection.UserId}"), "userId");
jsonWebClient.DataContent.Add(new StringContent($"{data.ParentId}"), "parentId");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.CreationTime}"), "created");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.LastWriteTime}"), "modified");
jsonWebClient.DataContent.Add(new StringContent($"{DateTime.Now}"), "clientCreated");
jsonWebClient.DataContent.Add(new StringContent($"{DateTime.Now}"), "clientModified");
jsonWebClient.DataContent.Add(new StringContent($"{fileInfo.Length}"), "size");

So I am trying generate a MultipartFormDataContent to convert to a Byte Array or stream. When I do the stream:

Stream stream = _dataContent.ReadAsStreamAsync().Result;

I get a out of memory exception.

When I try to do:

byte[] bytes = _dataContent.ReadAsByteArrayAsync().Result;

or

byte[] bytes = _dataContent.ReadAsByteArrayAsync().GetAwaiter().GetResult();

It just sits there forever and does nothing. What can I do to make it convert to the proper byte array?

Body:
Original source [How would I run an async Task method synchronously?][Rachel]How would I run an async Task<T> method synchronously?     method-synchronously

public static class AsyncHelpers
{
   /// <summary>
   /// Execute's an async Task<T> method which has a void return value synchronously
   /// </summary>
   /// <param name="task">Task<T> method to execute</param>
   public static void RunSync(Func<Task> task)
   {
      var oldContext = SynchronizationContext.Current;
      var synch = new ExclusiveSynchronizationContext();
      SynchronizationContext.SetSynchronizationContext(synch);
      synch.Post(async _ =>
      {
          try
          {
              await task();
          }
          catch (Exception e)
          {
              synch.InnerException = e;
              throw;
          }
          finally
          {
              synch.EndMessageLoop();
          }
       }, null);
      synch.BeginMessageLoop();

      SynchronizationContext.SetSynchronizationContext(oldContext);
  }

  /// <summary>
  /// Execute's an async Task<T> method which has a T return type synchronously
  /// </summary>
  /// <typeparam name="T">Return Type</typeparam>
  /// <param name="task">Task<T> method to execute</param>
  /// <returns></returns>
  public static T RunSync<T>(Func<Task<T>> task)
  {
     var oldContext = SynchronizationContext.Current;
     var synch = new ExclusiveSynchronizationContext();
     SynchronizationContext.SetSynchronizationContext(synch);
     T ret = default(T);
     synch.Post(async _ =>
     {
         try
         {
             ret = await task();
         }
         catch (Exception e)
         {
             synch.InnerException = e;
             throw;
         }
         finally
         {
             synch.EndMessageLoop();
         }
     }, null);
     synch.BeginMessageLoop();
     SynchronizationContext.SetSynchronizationContext(oldContext);
     return ret;
 }

 private class ExclusiveSynchronizationContext : SynchronizationContext
 {
    private bool done;
    public Exception InnerException { get; set; }
    readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false);
    readonly Queue<Tuple<SendOrPostCallback, object>> items =
        new Queue<Tuple<SendOrPostCallback, object>>();

    public override void Send(SendOrPostCallback d, object state)
    {
        throw new NotSupportedException("We cannot send to our same thread");
    }

    public override void Post(SendOrPostCallback d, object state)
    {
        lock (items)
        {
            items.Enqueue(Tuple.Create(d, state));
        }
        workItemsWaiting.Set();
    }

    public void EndMessageLoop()
    {
        Post(_ => done = true, null);
    }

    public void BeginMessageLoop()
    {
        while (!done)
        {
            Tuple<SendOrPostCallback, object> task = null;
            lock (items)
            {
                if (items.Count > 0)
                {
                    task = items.Dequeue();
                }
            }
            if (task != null)
            {
                task.Item1(task.Item2);
                if (InnerException != null) // the method threw an exeption
                {
                    throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
                }
            }
            else
            {
                workItemsWaiting.WaitOne();
            }
        }
    }

    public override SynchronizationContext CreateCopy()
    {
        return this;
    }
  }
}

With this class I was able to convert it right away without waiting and there was no issues with Out of Memory Exception.


问:
Laravel - How to Resolve Object of class stdClass could not be converted to string Error
When I run this code:

```<code>   public function manager_employee_list()
   {
       $userCompany = Auth::user()->company_id;
       $userEmployee = Auth::user()->employee_id;
       $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();

       $linemanager = DB::table('hr_employees')->select('line_manager_id')->where('id', $userEmployee)->first();
       $linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->get();
       $goals = AppraisalGoal::where('employee_id', $linemanageremployee)->where('appraisal_identity_id',
       return view('appraisal.appraisal_goals.manager_employee_list')->with('goals', $goals);
}
</code>```

I got this error:

Object of class stdClass could not be converted to string

When I did:

dd($linemanageremployee);

I got:

```<code>Illuminate\Support\Collection {#880 ▼
  #items: array:3 [▼
    0 => {#2312 ▼
  +"id": 2
}
1 => {#2326 ▼
  +"id": 3
}
2 => {#2313 ▼
  +"id": 6
    }
  ]
}
</code>```

How do I resolve it?

Thank you.

答:
Try changing:

```<code>$linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->get();
</code>```

to

```<code>$linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->pluck('id');
</code>```

Then change:

```<code>$goals = AppraisalGoal::where('employee_id', $linemanageremployee) ...
</code>```

to

```<code>$goals = AppraisalGoal::whereIn('employee_id', $linemanageremployee) ...
</code>```

Explanation:

->get() method returns an Eloquent Collection, which cannot be directly used inside of where() to make a query.

->pluck() method returns an array, which can be used to make a query with whereIn()

Body:
When I run this code:

   public function manager_employee_list()
   {
       $userCompany = Auth::user()->company_id;
       $userEmployee = Auth::user()->employee_id;
       $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();

       $linemanager = DB::table('hr_employees')->select('line_manager_id')->where('id', $userEmployee)->first();
       $linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->get();
       $goals = AppraisalGoal::where('employee_id', $linemanageremployee)->where('appraisal_identity_id',
       return view('appraisal.appraisal_goals.manager_employee_list')->with('goals', $goals);
}

I got this error:

Object of class stdClass could not be converted to string

When I did:

dd($linemanageremployee);

I got:

Illuminate\Support\Collection {#880 ▼
  #items: array:3 [▼
    0 => {#2312 ▼
  +"id": 2
}
1 => {#2326 ▼
  +"id": 3
}
2 => {#2313 ▼
  +"id": 6
    }
  ]
}

How do I resolve it?

Thank you.

Body:
Try changing:

$linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->get();

to

$linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->pluck('id');

Then change:

$goals = AppraisalGoal::where('employee_id', $linemanageremployee) ...

to

$goals = AppraisalGoal::whereIn('employee_id', $linemanageremployee) ...

Explanation:

->get() method returns an Eloquent Collection, which cannot be directly used inside of where() to make a query.

->pluck() method returns an array, which can be used to make a query with whereIn()


问:
Tool for edit lvm.conf file
is there any lvm.conf editor?

I'm trying to set global_filter, use_lvmtad and some other options, currently using sed:

sed -i /etc/lvm/lvm.conf \
      -e "s/use_lvmetad = 1/use_lvmetad = 0/" \
      -e "/^ *[^#] *global_filter/d" \
      -e "/^devices {/a\        global_filter = [ \"r|/dev/drbd.*|\", \"r|/dev/dm-.*|\", \"r|/dev/zd.*|\" ]"
```

but I don't like this too much, is there any better way?

I found only lvmconfig tool, but it can only display certain configuration sections, and can't edit them.

答:
It seems that augtool is exactly what I was looking for.

These two packages should be enough to proper processing lvm.conf file:

```<code>apt install augeas-tools augeas-lenses
</code>```

Example usage:

augtool print /files/etc/lvm/lvm.conf
```

<p>And you should get the whole parse tree on stdout.</p>

<p>If the parser fails you won’t get any output, print the error message using:</p>

<pre class="lang-sh prettyprint-override"><code>augtool print /files/etc/lvm/lvm.conf/error
</code>```

The augtool equivalent for the sed command from the original question:

augtool -s <<EOT
set /files/etc/lvm/lvm.conf/global/dict/use_lvmetad/int "0"
rm /files/etc/lvm/lvm.conf/devices/dict/global_filter
set /files/etc/lvm/lvm.conf/devices/dict/global_filter/list/0/str "r|^/dev/drbd.*|"
set /files/etc/lvm/lvm.conf/devices/dict/global_filter/list/1/str "r|/dev/dm-.*|"
set /files/etc/lvm/lvm.conf/devices/dict/global_filter/list/2/str "r|/dev/zd.*|"
EOT
```

Title: Tool for edit lvm.conf file

Body:
is there any lvm.conf editor?

I'm trying to set global_filter, use_lvmtad and some other options, currently using sed:

sed -i /etc/lvm/lvm.conf \
      -e "s/use_lvmetad = 1/use_lvmetad = 0/" \
      -e "/^ *[^#] *global_filter/d" \
      -e "/^devices {/a\        global_filter = [ \"r|/dev/drbd.*|\", \"r|/dev/dm-.*|\", \"r|/dev/zd.*|\" ]"

but I don't like this too much, is there any better way?

I found only lvmconfig tool, but it can only display certain configuration sections, and can't edit them.

Body:
It seems that augtool is exactly what I was looking for.

These two packages should be enough to proper processing lvm.conf file:

apt install augeas-tools augeas-lenses

Example usage:

augtool print /files/etc/lvm/lvm.conf

And you should get the whole parse tree on stdout.

If the parser fails you won’t get any output, print the error message using:

augtool print /files/etc/lvm/lvm.conf/error

The augtool equivalent for the sed command from the original question:

augtool -s <<EOT
set /files/etc/lvm/lvm.conf/global/dict/use_lvmetad/int "0"
rm /files/etc/lvm/lvm.conf/devices/dict/global_filter
set /files/etc/lvm/lvm.conf/devices/dict/global_filter/list/0/str "r|^/dev/drbd.*|"
set /files/etc/lvm/lvm.conf/devices/dict/global_filter/list/1/str "r|/dev/dm-.*|"
set /files/etc/lvm/lvm.conf/devices/dict/global_filter/list/2/str "r|/dev/zd.*|"
EOT


问:
Run Moving Average Accross Multiple Columns - R
I'm after a method  to perform a moving average calculation for each column in my data frame and append the results to the original data frame

R is not looping all the columns giving me this error that I don't understand

2: In if (type == "s") { :   the condition has length > 1 and only the
  first element will be used
  3: In colnames(temp_df)[1] <- new_colname :
  number of items to replace is not a multiple of replacement length

I understand the for Loop works with Logical elements, but I have no idea how to solve this using a loop.

```<code>    library(lubridate)
    library(pracma)
    library(dplyr)

  # ---- Fake Data Frame

    date       a         b         c                  d                         e
    01/01/2018 0.2087381 0.2892251 0.003478307        0.1186026                 0
    02/01/2018 0.3213273 0.4482369 0.005533266        0.2137506                 0
    03/01/2018 0.2516612 0.3508488 0.004430171        0.1671371                 0
    04/01/2018 0.2436500 0.3375996 0.004323420        0.1580058                 0
    05/01/2018 0.2542939 0.3509883 0.004421275        0.1621509                 0
    06/01/2018 0.2385525 0.3277567 0.004154398        0.1676672                 0

        #add index to allow merge after looping
        rawData <- rawData %>%
          mutate(index = row_number())

        for (i in colnames(rawData)) {

          #define the column in the loop
          data <- rawData[, i]

          #transform to data series
          ts_data <- ts(data, frequency = 365)

          #create mvg avg
          ts_data_mvgavg <- movavg(ts_data,n=7)

          #store result in a data frame
          temp_df <- as.data.frame(ts_data_mvgavg)

          #create a row index to allow merge with raw data
          temp_df <- temp_df %>%
            mutate(index = row_number())

          #define new column name based on variable
          new_colname <- paste0("mvg_avg_", i)

          #rename the column so that it's unique
          colnames(temp_df)[1]<- new_colname

          #merge temp_df and rawData dataframe
          main_DF <- merge(rawData, temp_df, by.x = "index", by.y = "index")

        }
</code>```

Body:
I'm after a method  to perform a moving average calculation for each column in my data frame and append the results to the original data frame

R is not looping all the columns giving me this error that I don't understand

2: In if (type == "s") { :   the condition has length > 1 and only the
  first element will be used
  3: In colnames(temp_df)[1] <- new_colname :
  number of items to replace is not a multiple of replacement length

I understand the for Loop works with Logical elements, but I have no idea how to solve this using a loop.

    library(lubridate)
    library(pracma)
    library(dplyr)

  # ---- Fake Data Frame

    date       a         b         c                  d                         e
    01/01/2018 0.2087381 0.2892251 0.003478307        0.1186026                 0
    02/01/2018 0.3213273 0.4482369 0.005533266        0.2137506                 0
    03/01/2018 0.2516612 0.3508488 0.004430171        0.1671371                 0
    04/01/2018 0.2436500 0.3375996 0.004323420        0.1580058                 0
    05/01/2018 0.2542939 0.3509883 0.004421275        0.1621509                 0
    06/01/2018 0.2385525 0.3277567 0.004154398        0.1676672                 0

        #add index to allow merge after looping
        rawData <- rawData %>%
          mutate(index = row_number())

        for (i in colnames(rawData)) {

          #define the column in the loop
          data <- rawData[, i]

          #transform to data series
          ts_data <- ts(data, frequency = 365)

          #create mvg avg
          ts_data_mvgavg <- movavg(ts_data,n=7)

          #store result in a data frame
          temp_df <- as.data.frame(ts_data_mvgavg)

          #create a row index to allow merge with raw data
          temp_df <- temp_df %>%
            mutate(index = row_number())

          #define new column name based on variable
          new_colname <- paste0("mvg_avg_", i)

          #rename the column so that it's unique
          colnames(temp_df)[1]<- new_colname

          #merge temp_df and rawData dataframe
          main_DF <- merge(rawData, temp_df, by.x = "index", by.y = "index")

        }

Body:
Fixing the input data in the question, we cbind the input to the rolling mean of it.

library(zoo)
rawData <- data.frame(a = 101:465, b = 1001:1365, c = 1:365) # test data

rawData2 <- cbind(rawData, roll = rollmeanr(rawData, 7, fill = NA))

giving:

     a    b  c roll.a roll.b roll.c
1  101 1001  1     NA     NA     NA
2  102 1002  2     NA     NA     NA
3  103 1003  3     NA     NA     NA
4  104 1004  4     NA     NA     NA
5  105 1005  5     NA     NA     NA
6  106 1006  6     NA     NA     NA
7  107 1007  7    104   1004      4
8  108 1008  8    105   1005      5
9  109 1009  9    106   1006      6
10 110 1010 10    107   1007      7
11 111 1011 11    108   1008      8
12 112 1012 12    109   1009      9
... etc ...


问:
Is it necessary to install X Code for c++ compiler? What if I install X Code and Uninstall it? Will g++ compiler will also get deleted?
I am not sure if I should delete the X Code as it takes a lot of space on MacBook. I want to use g++ compiler for compiling my c++ program.</p>

答:
It is possible to install just the Xcode command line tools. Open Terminal and execute xcode-select --install. This will get you your compiler (clang, not g++. g++ is just an alias for clang++ on Macs), linker, make, etc.

To actually answer your question, yes. If you install something and then uninstall it, the stuff that got installed will get uninstalled.

If you want the actual g++ compiler, you will need to install it yourself, homebrew is the easiest way. The gcc package will create versioned symlinks for you (g++-9), and you can just use that, or create another symlink that redirects g++ to g++-9. If you did that, you'll have to remember to manually update that symlink when the major version changes. All this is found in usr/local/bin after installing homebrew and the gcc package.