问:
Solving a logic riddle in Prolog
I'm in the "early phase" of learning prolog and came across a logic riddle that seams easy to implement:

Link to the riddle | Link to solution

We are looking for the 10-digit number which satisfies the following conditions:

All digits from 0-9 occur exactly once.

The first 2 digits are divisible by 2.

The first 3 digits are divisible by 3.

...

The first 10 digits are divisible by 10.

I think I would first need to implement the rules to the .pl file right?
The rules from the solution are:

An integer can be divided by 1 without remainder.

An integer is divisible by 2 without remainder, if the last digit is straight.

An integer can be divided by 3 without a remainder if its transverse sum is divisible by 3.

An integer can be divided by 4 without a remainder if the last two digits are divisible by 4.

An integer is divisible by 5 if the last digit is divisible by 5.

An integer is divisible by 6 without a remainder if its transverse sum is divisible by 3 and the last digit by 2.

An integer is divisible by 8 without a remainder if the last three digits are divisible by 8.

An integer is divisible by 9 without a remainder if its transverse sum is divisible by 9.

An integer is divisible by 10 without a remainder if the last digit is a 0.

I read multiple introductions to rules in prolog but still dont get how do it. Can anyone help? Would be great :)

答:
The basic approach to solving this kind of problem in Prolog is to generate all possibilities, and then filter them. In this case we need a list of the ten digits with no repetitions, and each prefix of length N should be evenly divisible by N.

```<code>puzzle([A,B,C,D,E,F,G,H,I,J]) :-
  select(A,[0,1,2,3,4,5,6,7,8,9],List1),
  select(B,List1,List2), select(C,List2,List3), select(D,List3,List4),
  select(E,List4,List5), select(F,List5,List6), select(G,List6,List7),
  select(H,List7,List8), select(I,List8,List9), List9 = [J],
  divisible([A,B],2),
  divisible([A,B,C],3),
  divisible([A,B,C,D],4),
  divisible([A,B,C,D,E],5),
  divisible([A,B,C,D,E,F],6),
  divisible([A,B,C,D,E,F,G],7),
  divisible([A,B,C,D,E,F,G,H],8),
  divisible([A,B,C,D,E,F,G,H,I],9),
  divisible([A,B,C,D,E,F,G,H,I,J],10).
</code>```

Even divisibility can be easily implemented:

```<code>divisible(Is,D) :-
  combine(Is,N),
  R is N rem D, R == 0.
</code>```

But then we also need a bunch of technicalities to convert between integers, characters, and atoms.

```<code>:- use_module(library(lists)).

combine(Is,N) :-
  maplist(conv,Is,As), concat_list(As,A),
  atom_chars(A,Cs), number_chars(N,Cs).

conv(I,A) :-
  number_chars(I,[C]), atom_chars(A,[C]).

concat_list([A1,A2|As],Atom) :-
  atom_concat(A1,A2,A3),
  concat_list([A3|As],Atom).
concat_list([A],A).
</code>```

This produces the result indicated in your link:

```<code>| ?- puzzle(X).
X = [3,8,1,6,5,4,7,2,9,0] ? ;
no
| ?-
</code>```

Addition: if you want to make it faster, rather than just buying a bigger computer like everybody else, you can interleave the generation & test parts of the code:

```<code>puzzle2([A,B,C,D,E,F,G,H,I,J]) :-
  select(A,[0,1,2,3,4,5,6,7,8,9],List1),
  select(B,List1,List2), divisible([A,B],2),
  select(C,List2,List3), divisible([A,B,C],3),
  select(D,List3,List4), divisible([A,B,C,D],4),
  select(E,List4,List5), divisible([A,B,C,D,E],5),
  select(F,List5,List6), divisible([A,B,C,D,E,F],6),
  select(G,List6,List7), divisible([A,B,C,D,E,F,G],7),
  select(H,List7,List8), divisible([A,B,C,D,E,F,G,H],8),
  select(I,List8,List9), divisible([A,B,C,D,E,F,G,H,I],9),
  List9 = [J], divisible([A,B,C,D,E,F,G,H,I,J],10).
</code>```

Using SWI Prolog, I get the following timings:

```<code>?- time((puzzle(_),false)).
32m% 142,709,118 inferences, 76.333 CPU in 76.650 seconds (100% CPU, 1869553 Lips)

?- time((puzzle2(_),false)).
32m% 157,172 inferences, 0.142 CPU in 0.144 seconds (98% CPU, 1108945 Lips)

?- time((num(_),false)).
32m% 2,802,204 inferences, 1.008 CPU in 1.028 seconds (98% CPU, 2779208 Lips)
</code>```

which would seem to suggest that the puzzle2 version is several times faster than the num version given below.

Title: Solving a logic riddle in Prolog

Body:
The basic approach to solving this kind of problem in Prolog is to generate all possibilities, and then filter them. In this case we need a list of the ten digits with no repetitions, and each prefix of length N should be evenly divisible by N.

puzzle([A,B,C,D,E,F,G,H,I,J]) :-
  select(A,[0,1,2,3,4,5,6,7,8,9],List1),
  select(B,List1,List2), select(C,List2,List3), select(D,List3,List4),
  select(E,List4,List5), select(F,List5,List6), select(G,List6,List7),
  select(H,List7,List8), select(I,List8,List9), List9 = [J],
  divisible([A,B],2),
  divisible([A,B,C],3),
  divisible([A,B,C,D],4),
  divisible([A,B,C,D,E],5),
  divisible([A,B,C,D,E,F],6),
  divisible([A,B,C,D,E,F,G],7),
  divisible([A,B,C,D,E,F,G,H],8),
  divisible([A,B,C,D,E,F,G,H,I],9),
  divisible([A,B,C,D,E,F,G,H,I,J],10).

Even divisibility can be easily implemented:

divisible(Is,D) :-
  combine(Is,N),
  R is N rem D, R == 0.

But then we also need a bunch of technicalities to convert between integers, characters, and atoms.

:- use_module(library(lists)).

combine(Is,N) :-
  maplist(conv,Is,As), concat_list(As,A),
  atom_chars(A,Cs), number_chars(N,Cs).

conv(I,A) :-
  number_chars(I,[C]), atom_chars(A,[C]).

concat_list([A1,A2|As],Atom) :-
  atom_concat(A1,A2,A3),
  concat_list([A3|As],Atom).
concat_list([A],A).

This produces the result indicated in your link:

| ?- puzzle(X).
X = [3,8,1,6,5,4,7,2,9,0] ? ;
no
| ?-

Addition: if you want to make it faster, rather than just buying a bigger computer like everybody else, you can interleave the generation & test parts of the code:

puzzle2([A,B,C,D,E,F,G,H,I,J]) :-
  select(A,[0,1,2,3,4,5,6,7,8,9],List1),
  select(B,List1,List2), divisible([A,B],2),
  select(C,List2,List3), divisible([A,B,C],3),
  select(D,List3,List4), divisible([A,B,C,D],4),
  select(E,List4,List5), divisible([A,B,C,D,E],5),
  select(F,List5,List6), divisible([A,B,C,D,E,F],6),
  select(G,List6,List7), divisible([A,B,C,D,E,F,G],7),
  select(H,List7,List8), divisible([A,B,C,D,E,F,G,H],8),
  select(I,List8,List9), divisible([A,B,C,D,E,F,G,H,I],9),
  List9 = [J], divisible([A,B,C,D,E,F,G,H,I,J],10).

Using SWI Prolog, I get the following timings:

?- time((puzzle(_),false)).
32m% 142,709,118 inferences, 76.333 CPU in 76.650 seconds (100% CPU, 1869553 Lips)

?- time((puzzle2(_),false)).
32m% 157,172 inferences, 0.142 CPU in 0.144 seconds (98% CPU, 1108945 Lips)

?- time((num(_),false)).
32m% 2,802,204 inferences, 1.008 CPU in 1.028 seconds (98% CPU, 2779208 Lips)

which would seem to suggest that the puzzle2 version is several times faster than the num version given below.


来源: stackexchange

问:
How to fetch different records in same row in sql?
I have a table structure similar to one given below

```<code>1001    Jon
1002    Jacob
1003    Cayle
</code>```

I want to fetch records from table in a way that it should look like

```<code>1001 – Jon,   1002 – Jacob,  1003 – Cayle
</code>```

Can anybody suggest some easy way.

答:
In SQL Server you can get it using STUFF and FOR XML

```<code> select STUFF((
           SELECT ', ' + CONCAT(CAST(id as varchar(10)), ' - ', name)
           FROM mytable md
           FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
 ;
 GO

 | (No column name)                        |
 | :-------------------------------------- |
 |  1001 - Jon, 1002 - Jacob, 1003 - Cayle |
</code>```

dbfiddle here

ContentLicense: CC BY-SA 3.0

Body:
I have a table structure similar to one given below

1001    Jon
1002    Jacob
1003    Cayle

I want to fetch records from table in a way that it should look like

1001 – Jon,   1002 – Jacob,  1003 – Cayle

Can anybody suggest some easy way.

Body:
In SQL Server you can get it using STUFF and FOR XML

 select STUFF((
           SELECT ', ' + CONCAT(CAST(id as varchar(10)), ' - ', name)
           FROM mytable md
           FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
 ;
 GO

 | (No column name)                        |
 | :-------------------------------------- |
 |  1001 - Jon, 1002 - Jacob, 1003 - Cayle |

dbfiddle here


问:
How to grab laptop webcam video with ffmpeg in windows
I have a small python program that works very well to capture short videos from webcams in linux (at least for laptops that have built-in webcams) using a sub-process with ffmpeg.

Now i'm trying to write the same program to capture webcams in windows, and i know i can't use the generic "/dev/video0" that works pretty well in linux, but i thought something like naming it "Integrated Camera" should be enough, but it fails.

Here's my linux code (that works):

```<code>    import sys
    from subprocess import call
    from datetime import datetime
    def record_webcam(seconds):
        cam = '/dev/video0'
        timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
        filename = timestamp + 'something.mkv' #generated with more complexity in the actual code, but that isn't important
        ffmpeg_cmd = 'ffmpeg -t {} -an -i {} -c:v libx264 -preset veryslow -crf 25 {}'.format(seconds, cam, filename).split()
        p = call(ffmpeg_cmd)
        return filename if p == 0 else False

    if __name__ == '__main__':
        record_webcam(sys.argv[1])
</code>```

I have looked at the documentation for ffmpeg and tried to search for solution but so far i'm lost...

I know that "Integrated Camera"s are only available on some laptops and not others, and that it won't capture other cameras connected, but it's enough for my use case... but if you want a challenge I would also like to know how to apply it to any windows-pc with a camera regardless of what it's called.

Also, is it easier or more recommended to do what i'm trying here only with python tools, like OpenCV?

Thanks in advance!
Edit: I answered my own question with a partial solution if anyone is interested based on a comment from @Mulvya, but if anyone can still explain to me the part about OpenCV I would still like to hear it...

Follow up question here: ffmpeg through python subprocess fails to find camera

答:
I did it... based on what @Mulvya commented, i was able to list all cameras withing the code and extract a command from them, i now have a different issue about that, but i will ask another question for it. In the meanwhile, if anyone is interested in automatically selecting the first available camera on windows through python and ffmpeg, my solution is this:

```<code>    import re
    from subprocess import Popen, PIPE
    list_cmd = 'ffmpeg -list_devices true -f dshow -i dummy'.split()
    p = Popen(list_cmd, stderr=PIPE)
    for line in iter(p.stderr.readline,''):
        if flagcam:
            cam = re.search('".*"',line.decode(encoding='UTF-8')).group(0)
            cam = 'video=' + cam if cam else ''
            flagcam = False
        elif 'DirectShow video devices'.encode(encoding='UTF-8') in line:
            flagcam = True
        elif 'Immediate exit requested'.encode(encoding='UTF-8') in line:
            break
</code>```

the variable "cam" now holds the name of the cam as it is in DirectShow on windows

Follow up question here if anyone wants to help EDIT: also solved

Body:
I have a small python program that works very well to capture short videos from webcams in linux (at least for laptops that have built-in webcams) using a sub-process with ffmpeg.

Now i'm trying to write the same program to capture webcams in windows, and i know i can't use the generic "/dev/video0" that works pretty well in linux, but i thought something like naming it "Integrated Camera" should be enough, but it fails.

Here's my linux code (that works):

    import sys
    from subprocess import call
    from datetime import datetime
    def record_webcam(seconds):
        cam = '/dev/video0'
        timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
        filename = timestamp + 'something.mkv' #generated with more complexity in the actual code, but that isn't important
        ffmpeg_cmd = 'ffmpeg -t {} -an -i {} -c:v libx264 -preset veryslow -crf 25 {}'.format(seconds, cam, filename).split()
        p = call(ffmpeg_cmd)
        return filename if p == 0 else False

    if __name__ == '__main__':
        record_webcam(sys.argv[1])

I have looked at the documentation for ffmpeg and tried to search for solution but so far i'm lost...

I know that "Integrated Camera"s are only available on some laptops and not others, and that it won't capture other cameras connected, but it's enough for my use case... but if you want a challenge I would also like to know how to apply it to any windows-pc with a camera regardless of what it's called.

Also, is it easier or more recommended to do what i'm trying here only with python tools, like OpenCV?

Thanks in advance!
Edit: I answered my own question with a partial solution if anyone is interested based on a comment from @Mulvya, but if anyone can still explain to me the part about OpenCV I would still like to hear it...

Follow up question here: ffmpeg through python subprocess fails to find camera

Body:
I did it... based on what @Mulvya commented, i was able to list all cameras withing the code and extract a command from them, i now have a different issue about that, but i will ask another question for it. In the meanwhile, if anyone is interested in automatically selecting the first available camera on windows through python and ffmpeg, my solution is this:

    import re
    from subprocess import Popen, PIPE
    list_cmd = 'ffmpeg -list_devices true -f dshow -i dummy'.split()
    p = Popen(list_cmd, stderr=PIPE)
    for line in iter(p.stderr.readline,''):
        if flagcam:
            cam = re.search('".*"',line.decode(encoding='UTF-8')).group(0)
            cam = 'video=' + cam if cam else ''
            flagcam = False
        elif 'DirectShow video devices'.encode(encoding='UTF-8') in line:
            flagcam = True
        elif 'Immediate exit requested'.encode(encoding='UTF-8') in line:
            break

the variable "cam" now holds the name of the cam as it is in DirectShow on windows

Follow up question here if anyone wants to help EDIT: also solved


问:
Display values without array (print_r)
I have a function that displays the actors photos from TMDB to my website is there a way that I can make it print without an array, it prints only with print_r I want to know if I can print it like echo or print.

This is the code:

```<code>    public function getCasts($movieID)
{
    if (empty($movieID)) return;

    function cmpcast($a, $b)
    {
        return ($a["order"]>$b["order"]);
    }

    $temp = $this->_call("movie/" . $movieID . "/casts");
    $casts = $temp['cast'];

    $temp = array();
    if (count($casts) > 0)
    {
        usort($casts, "cmpcast");
        foreach ($casts as &$actor) {
            if (!empty($actor['profile_path'])) {
                for ($i=6; $i<count($temp['id']); $i++)
                    if ($temp['name'][$i] == $actor['name']) $temp['char'][$i] .= " / ".str_replace('(voice)', '(hang)', $actor['character']);

                if (!in_array($actor['name'], (array) $temp['name'])) {
                        $temp['pic'][] = "<div style='margin-top:15px;' align='center'><div style='width:140px;margin-right:8px;display:inline-block;vertical-align:top;'><img style='width:130px;height:130px;border-radius:50%;' src='".$this->getImageURL().$actor['profile_path']."'><br />".$actor['name']."<br />".$actor['character']."</div></div>";
                    }
            }
        }
    }
    return $temp;
}
</code>```

答:
You could use some kind of loop. Use a for loop if you want to limit the number of item you echo.

For example :

```<code>$casts = getCasts(1);

for ($i = 0; $i < 5; $i++) {
    if (isset($casts['pic'][$i])) {
        echo $casts['pic'][$i];
    }
}
</code>```

Hope it helps.

Title: Display values without array (print_r)

Body:
I have a function that displays the actors photos from TMDB to my website is there a way that I can make it print without an array, it prints only with print_r I want to know if I can print it like echo or print.

This is the code:

    public function getCasts($movieID)
{
    if (empty($movieID)) return;

    function cmpcast($a, $b)
    {
        return ($a["order"]>$b["order"]);
    }

    $temp = $this->_call("movie/" . $movieID . "/casts");
    $casts = $temp['cast'];

    $temp = array();
    if (count($casts) > 0)
    {
        usort($casts, "cmpcast");
        foreach ($casts as &$actor) {
            if (!empty($actor['profile_path'])) {
                for ($i=6; $i<count($temp['id']); $i++)
                    if ($temp['name'][$i] == $actor['name']) $temp['char'][$i] .= " / ".str_replace('(voice)', '(hang)', $actor['character']);

                if (!in_array($actor['name'], (array) $temp['name'])) {
                        $temp['pic'][] = "

getImageURL().$actor['profile_path']."'>
".$actor['name']."
".$actor['character']."

";
                    }
            }
        }
    }
    return $temp;
}

Body:
You could use some kind of loop. Use a for loop if you want to limit the number of item you echo.

For example :

$casts = getCasts(1);

for ($i = 0; $i < 5; $i++) {
    if (isset($casts['pic'][$i])) {
        echo $casts['pic'][$i];
    }
}

Hope it helps.


问:
why the same font-family dispaly different style under IE and firefox?

under IE7:

ie http://run.xxmn.com/images/ie.jpg

under firefox

firefox http://run.xxmn.com/images/firefox.jpg

I made a style on the site like this:

```<code>* {
       font-family:Arial,Helvetica,sans-serif;
       font-size:14px;
       margin:0;padding:0;
}
</code>```

How to make theme show the same style under IE and Firefox?

答:
The two examples you show are the same style.  I.e. they have the same font, same spacing, etc.

However, the rendering of each is different.  One is anti-aliased, and the other is not.  This has to do with how the browser renders text and may be affected by browser and system settings.  You cannot control this from css.  If you want text to look exactly the same on two browsers/platforms, you will have to make an image.

ContentLicense: CC BY-SA 2.5

Body:
under IE7:

ie http://run.xxmn.com/images/ie.jpg

under firefox

firefox http://run.xxmn.com/images/firefox.jpg

I made a style on the site like this:

* {
       font-family:Arial,Helvetica,sans-serif;
       font-size:14px;
       margin:0;padding:0;
}

How to make theme show the same style under IE and Firefox?


问:
VBA Date as integer
is there a way to get the underlying integer for Date function in VBA ? I'm referring to the integer stored by Excel to describe dates in memory in terms of number of days (when time is included it can be a float then I guess). I'm only interest in the integer part though. Is there just another function for that ?

For example, for today() I'd like to be able to get back 40877..

答:
You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging

```<code>Public Sub test(mdate As String)
    Dim toDay As String
    mdate = Round(CDbl(CDate(mdate)), 0)
    toDay = Round(CDbl(Now()), 0)
    Dim Aging as String
    Aging = toDay - mdate
    MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
    Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub
</code>```

NB: Used CDate for convert Date String to Valid Date

I am using this in Office 2007 :)

ContentLicense: CC BY-SA 4.0

Title: VBA Date as integer

Body:
You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging

Public Sub test(mdate As String)
    Dim toDay As String
    mdate = Round(CDbl(CDate(mdate)), 0)
    toDay = Round(CDbl(Now()), 0)
    Dim Aging as String
    Aging = toDay - mdate
    MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
    Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub

NB: Used CDate for convert Date String to Valid Date

I am using this in Office 2007 :)


问:
Customer Order Totals
How would I execute a sub that allows me to determine a customer as defined by their (customer ID) to determine how much they have spent in total for over ($3000). As well as find the total spent by each  customer on the list and reports those whose total is more than the amount provided by the user on a new worksheet (Ex $3000) into a sheet that produces how much each customer spent along with their total amount spent to the right in a different cell.

Example of data:

current:

```<code>Sub test()

Sheets.Add after:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = "Report"

Lastrow = Sheets("Data").UsedRange.Rows.Count

Sheets("Data").Range("B3:B" & Lastrow).Copy

With Sheets("Report")
    .Range("A1").PasteSpecial Paste:=xlPasteValues
    .Activate
    .Range("B1").Select
    .Range(Range("A1"), Range("A1").End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlYes
    .Cells(1, 2).Value = "Subtotal"
End With

For i = 2 To ActiveSheet.UsedRange.Rows.Count
    Cells(i, 2).Value = Application.WorksheetFunction.SumIf(Sheets("Data").Range("B:B"), "=" & Cells(i, 1).Value, Sheets("Data").Range("C:C"))

Next

For i = ActiveSheet.UsedRange.Rows.Count To 2 Step -1
    If Cells(i, 2).Value < 3000 Then
        Cells(i, 2).EntireRow.Delete
    End If
Next

Sheets("Report").Range("A1:B" & ActiveSheet.UsedRange.Rows.Count).Sort KEY1:=Range("B1:B" & ActiveSheet.UsedRange.Rows.Count), Order1:=xlAscending, Header:=xlYes

End Sub
</code>```

答:
This can be done without re-inventing the wheel with VBA. Select the data and insert a Pivot table. This is basic Excel functionality that has been around for at least 20 years.

If you want to use VBA, create the Pivot Table with VBA.

Tip: before creating the pivot table, turn the source data table into an Excel Table object with Insert > Table (or Ctrl-T). Then create a pivot table from the Excel Table. That way the pivot data source will be dynamic and when you add more data to the source, you only need to refresh the pivot table to include the new data.

Title: Customer Order Totals

Body:
How would I execute a sub that allows me to determine a customer as defined by their (customer ID) to determine how much they have spent in total for over ($3000). As well as find the total spent by each  customer on the list and reports those whose total is more than the amount provided by the user on a new worksheet (Ex $3000) into a sheet that produces how much each customer spent along with their total amount spent to the right in a different cell.

Example of data:

current:

Sub test()

Sheets.Add after:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = "Report"

Lastrow = Sheets("Data").UsedRange.Rows.Count

Sheets("Data").Range("B3:B" & Lastrow).Copy

With Sheets("Report")
    .Range("A1").PasteSpecial Paste:=xlPasteValues
    .Activate
    .Range("B1").Select
    .Range(Range("A1"), Range("A1").End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlYes
    .Cells(1, 2).Value = "Subtotal"
End With

For i = 2 To ActiveSheet.UsedRange.Rows.Count
    Cells(i, 2).Value = Application.WorksheetFunction.SumIf(Sheets("Data").Range("B:B"), "=" & Cells(i, 1).Value, Sheets("Data").Range("C:C"))

Next

For i = ActiveSheet.UsedRange.Rows.Count To 2 Step -1
    If Cells(i, 2).Value < 3000 Then
        Cells(i, 2).EntireRow.Delete
    End If
Next

Sheets("Report").Range("A1:B" & ActiveSheet.UsedRange.Rows.Count).Sort KEY1:=Range("B1:B" & ActiveSheet.UsedRange.Rows.Count), Order1:=xlAscending, Header:=xlYes

End Sub


问:
Android O in Android Emulater has not respond
I want to run some google android samples，but compileSdkVersion need "android-O"，I do not have a real phone, so I decided to use Android Emulator ,when I run it, it has no respond.

Android O

答:
compileSdkVersion need "android-O"

This doesn't require you to run the application just on Android O devices. minSdkVersion is the field that defines the minimum supported API version. You can run those applications on any phone which has a newer or same version of Android as declared in the minSdkVersion.

Read more here: Configure Your Build | Android Developers

compileSdkVersion specifies the Android API level Gradle should use to compile your app. This means your app can use the API features included in this API level and lower.

If you still really want to run it on an Emulator, make sure you have:

CPU ABI set to x86 or x86_64

Resolution set to something like 480 x 800

RAM set to minimum required by the API version you are trying to emulate

This will ensure that it takes up minimum resources and works even on older/lo-fi machines.


问:
Where should I cp oc binary to on MacOS?
In this documentation it says

unpack the archive and move the oc binary to a directory on your PATH

I tried echo $PATH and it returns:

bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin

Clearly there are multiple path here, which one should I move cp oc binary to?

答:
/usr/local/bin would be the usual choice for user or third-party executables. That way it won't get wiped out when you update the OS.

See also: Where do you keep your own scripts on OSX? - the question is about scripts rather than binaries, but the same logic applies.


问:
How to extract date time from sql and bind it to datetimePicker
I have saved dates from datetimepicker to sql in my windows form app with the format (dd-MM-yyyy). To edit date, I want to first fetch saved date and show in the datetimepicker control. Like if 28-03-2000 is saved in db then datetimepicker should show this same date and should understand the format dd-MM-yyyy. The code with which I am trying to do is as follows

```<code>birthday_search.Text = Convert.ToDateTime(reader["Birthday"]).ToString("dd-MM-yyyy");
</code>```

birthday_search is the name of datetimepicker. This gives error "String was not recognized as a valid datetime" because its itself picking the format MM-dd-yyyy which is turning out to be wrong.

答:
Try this:

change the property format of your datetimepicker to Custom
then add the following code:

birthday_search.CustomFormat = "dd-MM-yyyy";

```<code>birthday_search.Value = Convert.ToDateTime(reader["Birthday"]).ToString());
</code>```

Body:
I have saved dates from datetimepicker to sql in my windows form app with the format (dd-MM-yyyy). To edit date, I want to first fetch saved date and show in the datetimepicker control. Like if 28-03-2000 is saved in db then datetimepicker should show this same date and should understand the format dd-MM-yyyy. The code with which I am trying to do is as follows

birthday_search.Text = Convert.ToDateTime(reader["Birthday"]).ToString("dd-MM-yyyy");

birthday_search is the name of datetimepicker. This gives error "String was not recognized as a valid datetime" because its itself picking the format MM-dd-yyyy which is turning out to be wrong.

Body:
Try this:

change the property format of your datetimepicker to Custom
then add the following code:

birthday_search.CustomFormat = "dd-MM-yyyy";

birthday_search.Value = Convert.ToDateTime(reader["Birthday"]).ToString());


问:
How to exclude (ignore) certain folders in vagrant rsync?
I wish to run npm install in my vagrant virtual box.

But whenever I ran the npm install command, my rsync will execute. Since my host computer does not have node_modules installed, it simply remove the folder completely for me.

What do I need to do so that my vagrant rsync will ignore the node_modules folder?

I cannot have node_modules being rsynced into the guest machine because my host and guest are two different systems. So far my vagrantfile looks like this.

```<code>Vagrant.configure("2") do |config|
  config.vm.box = "laravel/homestead"

  config.vm.hostname = "localhost"

  config.vm.network "forwarded_port", guest: 8000, host: 8000

  config.vm.synced_folder "./", "/home/vagrant/app"

  config.vm.provider "virtualbox" do |v|
    v.name = "web2"
    v.memory = "4096"
    v.cpus = 2
    v.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/SHARE_NAME", "1"]
  end

  config.vm.synced_folder "./", "/home/vagrant/app", type: "rsync", rsync_auto: true, rsync_exclude: ['node_modules*']
  config.vm.provision :shell, path: "provision/setup.sh"

end
</code>```

And I execute vagrant rsync via

```<code>vagrant rsync-auto
</code>```

答:
rsync__exclude as well as rsync__auto takes 2 _

You need to rewrite your line as

```<code>config.vm.synced_folder "./", "/home/vagrant/app", type: "rsync", rsync__auto: true, rsync__exclude: ['./node_modules*']
</code>```

Body:
I wish to run npm install in my vagrant virtual box.

But whenever I ran the npm install command, my rsync will execute. Since my host computer does not have node_modules installed, it simply remove the folder completely for me.

What do I need to do so that my vagrant rsync will ignore the node_modules folder?

I cannot have node_modules being rsynced into the guest machine because my host and guest are two different systems. So far my vagrantfile looks like this.

Vagrant.configure("2") do |config|
  config.vm.box = "laravel/homestead"

  config.vm.hostname = "localhost"

  config.vm.network "forwarded_port", guest: 8000, host: 8000

  config.vm.synced_folder "./", "/home/vagrant/app"

  config.vm.provider "virtualbox" do |v|
    v.name = "web2"
    v.memory = "4096"
    v.cpus = 2
    v.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/SHARE_NAME", "1"]
  end

  config.vm.synced_folder "./", "/home/vagrant/app", type: "rsync", rsync_auto: true, rsync_exclude: ['node_modules*']
  config.vm.provision :shell, path: "provision/setup.sh"

end

And I execute vagrant rsync via

vagrant rsync-auto

Body:
rsync__exclude as well as rsync__auto takes 2 _

You need to rewrite your line as

config.vm.synced_folder "./", "/home/vagrant/app", type: "rsync", rsync__auto: true, rsync__exclude: ['./node_modules*']


问:
how to avoid karaf load the default resolve bundle
I use the karaf to run an OSGI bundle which use a built-in commons-lang3.5.jar.

The problem is when I run this bundle, the karaf will auto load another commons-lang3.1.jar. I am not sure when it be load. But it take my bundle crash.

Are there any ways to uninstall the karaf default built-in bundle?

答:
Nope, don't "uninstall" the default built-in bundle cause it is used by others.
Make sure your own bundle does a clean import for the commons lang bundle.

a bnd instruction would look like:

```<code>import-package:
   org.apache.commons.lang;version="[3.5,4.0)", \
   *
</code>```

this way you make sure you import only commons lang if there is a better version available then the one you already have included yourself.

Hint, don't embed dependencies, but make sure you depend on re-usable dependencies. With such import packages you can make sure you depend on a specific version.

Body:
Nope, don't "uninstall" the default built-in bundle cause it is used by others.
Make sure your own bundle does a clean import for the commons lang bundle.

a bnd instruction would look like:

import-package:
   org.apache.commons.lang;version="[3.5,4.0)", \
   *

this way you make sure you import only commons lang if there is a better version available then the one you already have included yourself.

Hint, don't embed dependencies, but make sure you depend on re-usable dependencies. With such import packages you can make sure you depend on a specific version.


问:
ajax - incremental load of elements from one file
I've got an index.html with a container in which I want to load content via ajax on click. It looks like this:

```<code><div id="loadcontent"></div>
<div id="more">Load More</div>
</code>```

And there's only one content file with a lot of divs:

```<code><div id="1" class="content">One</div>
<div id="2" class="content">Two</div>
<div id="3" class="content">Three</div>
<div id="4" class="content">Four</div>
<div id="5" class="content">Five</div>
<div id="6" class="content">Six</div>
<div id="7" class="content">Seven</div>
<div id="8" class="content">Eight</div>
<div id="9" class="content">Nine</div>
<div id="10" class="content">Ten</div>
<div id="11" class="content">Eleven</div>
<div id="12" class="content">Twelve</div>
</code>```

Here's the jQuery code:

```<code>$(document).ready(function () {
    var countItem = 0;

    $('#more').click(function(){
        countItem ++;
        $('<div/>').appendTo('#loadcontent').load('content.html #' + countItem)
            .hide()
            .fadeIn(1000);
    });
});
</code>```

For now it loads just one div when the load more button is clicked, cause it counts the ids.

Is it possible to load the next three ore more divs using ajax and append them to divs which already have been loaded? If yes, how can I get this working?
For example: first click: 1-3, second click: 1-6, third click: 1-9, etc...

Any help will be greatly appreciated.

UPDATE:

I don't want to load the content at once and then showing it up using .show() or something similar. It should be an ajax request for each click.

答:
I suggest you only make one request and store the request promise in a variable. Use slice() to filter new items to add each time

```<code>$(function() {
  var contentPromise = null,
    itemsPerClick = 3,
    startIndex = 0,
    $moreButton = $('#more');

 $moreButton.click(function() {
    getContent()
      .then(insertContent)
      .fail(function() {
        console.error("Failed request!")
      });
  });

  function getContent() {
    if (!contentPromise) {
      // store request promise
      contentPromise = $.get('content.html').then(function(resp) {
        // return jQuery object that can easily be sliced
        return $(resp).filter('div');
      })
    }
    return contentPromise;
  }

  function insertContent($content) {
    var endIndex = startIndex + itemsPerClick,
      $newItems = $content.slice(startIndex, endIndex);

    $('<div>').append($newItems)
      .appendTo('#loadcontent')
      .hide()
      .fadeIn(1000);

    // increment start
    startIndex = endIndex;
    // hide button when none left
    if (startIndex >= $content.length) {
      $moreButton.hide()
    }
  }
});
</code>```

Demo

Body:
I've got an index.html with a container in which I want to load content via ajax on click. It looks like this:

Load More

And there's only one content file with a lot of divs:

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

Twelve

Here's the jQuery code:

$(document).ready(function () {
    var countItem = 0;

    $('#more').click(function(){
        countItem ++;
        $('
').appendTo('#loadcontent').load('content.html #' + countItem)
            .hide()
            .fadeIn(1000);
    });
});

For now it loads just one div when the load more button is clicked, cause it counts the ids.

Is it possible to load the next three ore more divs using ajax and append them to divs which already have been loaded? If yes, how can I get this working?
For example: first click: 1-3, second click: 1-6, third click: 1-9, etc...

Any help will be greatly appreciated.

UPDATE:

I don't want to load the content at once and then showing it up using .show() or something similar. It should be an ajax request for each click.

Body:
I suggest you only make one request and store the request promise in a variable. Use slice() to filter new items to add each time

$(function() {
  var contentPromise = null,
    itemsPerClick = 3,
    startIndex = 0,
    $moreButton = $('#more');

 $moreButton.click(function() {
    getContent()
      .then(insertContent)
      .fail(function() {
        console.error("Failed request!")
      });
  });

  function getContent() {
    if (!contentPromise) {
      // store request promise
      contentPromise = $.get('content.html').then(function(resp) {
        // return jQuery object that can easily be sliced
        return $(resp).filter('div');
      })
    }
    return contentPromise;
  }

  function insertContent($content) {
    var endIndex = startIndex + itemsPerClick,
      $newItems = $content.slice(startIndex, endIndex);

    $('<div>').append($newItems)
      .appendTo('#loadcontent')
      .hide()
      .fadeIn(1000);

    // increment start
    startIndex = endIndex;
    // hide button when none left
    if (startIndex >= $content.length) {
      $moreButton.hide()
    }
  }
});

Demo


答:
I would think that the compiler is changing that to a constant.

Try b = a + 1 and then cout << b << b - a << endl;

Title: How to understand the output?

Body:
int a[2][3];
cout << a+1 << " " << a << " " << (a+1) - a << endl;

Output:

0029FAC0 0029FAB4 1

Shouldn't (a+1)-a be 0029FAC0-0029FAB4=12 ?


问:
How to get an enum constructor from a string?
Following up from my previous question I found the generic-deriving package which seems to have a lot of the building blocks that I need. Implementing a gEnumToString function was reduced to a one-liner. However, I'm running into problems with the gEnumFromString function:

```<code>{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}

import Text.Read
import GHC.Generics
import Generics.Deriving
import Control.Lens
import Data.Default as DD
import           Data.Aeson.Casing
import Data.Aeson.Types (camelTo2)

data Options = Options
  {
    optConstructorTagModifier :: String -> String
  } deriving (Generic)

instance DD.Default Options where
  def = Options
    {
      optConstructorTagModifier = (camelTo2 '_')
    }

makeLensesWith abbreviatedFields ''Options

gEnumToString :: (ConNames (Rep a), Generic a) => Options -> a -> String
gEnumToString opt x = (opt ^. constructorTagModifier) $ conNameOf x

gEnumFromString :: forall a . (Generic a, Enum' (Rep a), ConNames (Rep a))
                => Options -> String -> Maybe a
gEnumFromString opt s = lookup s lookupTable
  where
    lookupTable :: [(String, a)]
    lookupTable = (zipWith (,) (conNames undefined)  genumDefault)
</code>```

This code doesn't compile with the following errors. Even though I've tried constraining the type of conNames undefined by using ScopedTypeVariables and explicitly providing a forall a (as mentioned by one of the suggestions given in the answers). What am I doing wrong?

```<code>   168  33 error           error:
     • Could not deduce (Generic a0) arising from a use of ‘conNames’
       from the context: (Generic a, Enum' (Rep a), ConNames (Rep a))
         bound by the type signature for:
                    gEnumFromString :: (Generic a, Enum' (Rep a), ConNames (Rep a)) =>
                                       Options -> String -> Maybe a
         at /Users/saurabhnanda/projects/vl-haskell/.stack-work/intero/intero784UVH.hs:(163,1)-(164,47)
       The type variable ‘a0’ is ambiguous
       These potential instances exist:
         instance Generic (Either a b) -- Defined in ‘GHC.Generics’
         instance forall a k (b :: k). Generic (Const a b)
           -- Defined in ‘Data.Functor.Const’
         instance Generic (Identity a) -- Defined in ‘Data.Functor.Identity’
         ...plus 31 others
         ...plus 201 instances involving out-of-scope types
         (use -fprint-potential-instances to see them all)
     • In the second argument of ‘zipWith’, namely
         ‘(conNames undefined)’
       In the expression: (zipWith (,) (conNames undefined) genumDefault)
       In an equation for ‘lookupTable’:
           lookupTable = (zipWith (,) (conNames undefined) genumDefault) (intero)
</code>```

答:
To make type variables in scope, leveraging the extension ScopedTypeVariables, you need an explicit forall a..

E.g.

```<code>gEnumFromString :: forall a. (Generic a, Enum' (Rep a), ConNames (Rep a))
                => Options -> String -> Maybe a
gEnumFromString opt s = lookup s lookupTable
  where
    lookupTable :: [(String, a)]
    lookupTable = zipWith (,) (conNames (undefined :: a))  genumDefault
</code>```

There is no need to repeat the type constraints, since these are "carried" by a anyway.

Body:
Following up from my previous question I found the generic-deriving package which seems to have a lot of the building blocks that I need. Implementing a gEnumToString function was reduced to a one-liner. However, I'm running into problems with the gEnumFromString function:

{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}

import Text.Read
import GHC.Generics
import Generics.Deriving
import Control.Lens
import Data.Default as DD
import           Data.Aeson.Casing
import Data.Aeson.Types (camelTo2)

data Options = Options
  {
    optConstructorTagModifier :: String -> String
  } deriving (Generic)

instance DD.Default Options where
  def = Options
    {
      optConstructorTagModifier = (camelTo2 '_')
    }

makeLensesWith abbreviatedFields ''Options

gEnumToString :: (ConNames (Rep a), Generic a) => Options -> a -> String
gEnumToString opt x = (opt ^. constructorTagModifier) $ conNameOf x

gEnumFromString :: forall a . (Generic a, Enum' (Rep a), ConNames (Rep a))
                => Options -> String -> Maybe a
gEnumFromString opt s = lookup s lookupTable
  where
    lookupTable :: [(String, a)]
    lookupTable = (zipWith (,) (conNames undefined)  genumDefault)

This code doesn't compile with the following errors. Even though I've tried constraining the type of conNames undefined by using ScopedTypeVariables and explicitly providing a forall a (as mentioned by one of the suggestions given in the answers). What am I doing wrong?

   168  33 error           error:
     • Could not deduce (Generic a0) arising from a use of ‘conNames’
       from the context: (Generic a, Enum' (Rep a), ConNames (Rep a))
         bound by the type signature for:
                    gEnumFromString :: (Generic a, Enum' (Rep a), ConNames (Rep a)) =>
                                       Options -> String -> Maybe a
         at /Users/saurabhnanda/projects/vl-haskell/.stack-work/intero/intero784UVH.hs:(163,1)-(164,47)
       The type variable ‘a0’ is ambiguous
       These potential instances exist:
         instance Generic (Either a b) -- Defined in ‘GHC.Generics’
         instance forall a k (b :: k). Generic (Const a b)
           -- Defined in ‘Data.Functor.Const’
         instance Generic (Identity a) -- Defined in ‘Data.Functor.Identity’
         ...plus 31 others
         ...plus 201 instances involving out-of-scope types
         (use -fprint-potential-instances to see them all)
     • In the second argument of ‘zipWith’, namely
         ‘(conNames undefined)’
       In the expression: (zipWith (,) (conNames undefined) genumDefault)
       In an equation for ‘lookupTable’:
           lookupTable = (zipWith (,) (conNames undefined) genumDefault) (intero)

Body:
To make type variables in scope, leveraging the extension ScopedTypeVariables, you need an explicit forall a..

E.g.

gEnumFromString :: forall a. (Generic a, Enum' (Rep a), ConNames (Rep a))
                => Options -> String -> Maybe a
gEnumFromString opt s = lookup s lookupTable
  where
    lookupTable :: [(String, a)]
    lookupTable = zipWith (,) (conNames (undefined :: a))  genumDefault

There is no need to repeat the type constraints, since these are "carried" by a anyway.


问:
Python traceback broken: code out of sync with what is executed?
I'm running into a strange situation simply running a script from the command-line: when I run into errors, often the traceback given contains code that makes no sense. Every line in the traceback should be a method call, but sometimes they aren't. Also, the lines referenced in the traceback don't correspond to the given error. What's happening? As an example, here is a simple error where numpy wasn't imported, but the traceback makes little sense and refers to unrelated code lines:

```<code>Traceback (most recent call last):
  File "bin/train_global_model.py", line 549, in <module>
    if __name__ == '__main__':
  File "bin/train_global_model.py", line 236, in main
    def main():
  File "bin/train_global_model.py", line 407, in do_training
    tb_writer=train_writer,
  File "bin/train_global_model.py", line 200, in run_iteration
    print(accuracy)
NameError: global name 'np' is not defined
</code>```

Pay special attention to the code lines referenced.

Is python caching code that is executed somewhere but then referring to the actual file when it's tracing an exception? Running Python 2.7.13.

答: Python saves line numbers not the actual source code, when running programs. For tracebacks it loads the source code and shows the corresponding lines to the numbers. When the source changes, while the program is running, you get lines out of sync.</p>

Body:
I'm running into a strange situation simply running a script from the command-line: when I run into errors, often the traceback given contains code that makes no sense. Every line in the traceback should be a method call, but sometimes they aren't. Also, the lines referenced in the traceback don't correspond to the given error. What's happening? As an example, here is a simple error where numpy wasn't imported, but the traceback makes little sense and refers to unrelated code lines:

Traceback (most recent call last):
  File "bin/train_global_model.py", line 549, in <module>
    if __name__ == '__main__':
  File "bin/train_global_model.py", line 236, in main
    def main():
  File "bin/train_global_model.py", line 407, in do_training
    tb_writer=train_writer,
  File "bin/train_global_model.py", line 200, in run_iteration
    print(accuracy)
NameError: global name 'np' is not defined

Pay special attention to the code lines referenced.

Is python caching code that is executed somewhere but then referring to the actual file when it's tracing an exception? Running Python 2.7.13.


问:
Counting numbers of even numbers and odd numbers in java array
I have a program that reads a list of integers, and then display the number of even numbers and odd numbers. We assume that the input ends with 0. Here is the sample run of the program.

Input numbers: 1 2 3 4 5 6 7 8 9 0

Odd: 5    Even: 4

However, my result is
Odd: 5 and Even: 5.

The problem is that 0 is counted as an even number. This is my code

```<code>public class Q75 {
    public static void main(String[] args){
        java.util.Scanner input = new java.util.Scanner (System.in);
        double [] numbers = new double[10];
        System.out.print("Enter numbers: ");
        for(int i = 0;i<numbers.length;i++){
            numbers[i] = input.nextDouble();
        }

        int Evens = 0;
        int Odd = 0;

        for(int i = 0;i<numbers.length;i++){
            if(numbers[i]%2 == 0){
                Evens++;
            }else{
                Odd++;
            }
        }
        System.out.println("The number of odd numbers: " + Odd);
        System.out.println("The number of even numbers: " + Evens);
    }

}
</code>```

答:
There are two options

A) Adding another branch in your if statements i.e.

```<code>if(number[i] > 0) {
   if(number[i] % 2 >0)
      Odd++;
   else
      Evens++;
}
</code>```

NB: changing the else branch to else if(number[i] >0), you can do without the outer if condition.

B) Since the list of number ends with 0 you can put this as a condition in your for loop i.e.

```<code>for(int i =0; i < numbers.length && numbers[i] > 0 ; i++)
</code>```

Also as a rule of thumb variable names in java start with a small letter

Body:
I have a program that reads a list of integers, and then display the number of even numbers and odd numbers. We assume that the input ends with 0. Here is the sample run of the program.

Input numbers: 1 2 3 4 5 6 7 8 9 0

Odd: 5    Even: 4

However, my result is
Odd: 5 and Even: 5.

The problem is that 0 is counted as an even number. This is my code

public class Q75 {
    public static void main(String[] args){
        java.util.Scanner input = new java.util.Scanner (System.in);
        double [] numbers = new double[10];
        System.out.print("Enter numbers: ");
        for(int i = 0;i<numbers.length;i++){
            numbers[i] = input.nextDouble();
        }

        int Evens = 0;
        int Odd = 0;

        for(int i = 0;i<numbers.length;i++){
            if(numbers[i]%2 == 0){
                Evens++;
            }else{
                Odd++;
            }
        }
        System.out.println("The number of odd numbers: " + Odd);
        System.out.println("The number of even numbers: " + Evens);
    }

}

Body:
There are two options

A) Adding another branch in your if statements i.e.

if(number[i] > 0) {
   if(number[i] % 2 >0)
      Odd++;
   else
      Evens++;
}

NB: changing the else branch to else if(number[i] >0), you can do without the outer if condition.

B) Since the list of number ends with 0 you can put this as a condition in your for loop i.e.

for(int i =0; i < numbers.length && numbers[i] > 0 ; i++)

Also as a rule of thumb variable names in java start with a small letter


答:
try setting the format of the datetimepicker like this:

```<code>birthday_search.Format = DateTimePickerFormat.Custom;
</code>```

and now your desired format:

```<code>birthday_search.CustomFormat = "dd-MM-yyyy";
</code>```

Title: How to extract date time from sql and bind it to datetimePicker

Body:
try setting the format of the datetimepicker like this:

birthday_search.Format = DateTimePickerFormat.Custom;

and now your desired format:

birthday_search.CustomFormat = "dd-MM-yyyy";


问:
Packaging JRuby binaries into executable jar
Have downloaded the Jruby binaries on windows, installed the necessary gems i needed. How then do I re-package the whole Jruby binaries into an executable jar ?
thanks.</p>

答:
If you have a JRuby project, simply run

```<code>rake jar
</code>```

to see all available tasks:

```<code>rake -T
</code>```

Body:
If you have a JRuby project, simply run

rake jar

to see all available tasks:

rake -T


问:
Laravel 5 check if current url matches action
I am currently generating my application urls using {{action('Namespace\Class@method')}}. How would I check if the current page request maps to that current action Namespace\Class@method?

I would like to do something like:

```<code><a href="{{action('Namespace\Class@method')}}
  @if (currentAction('Namespace\Class@method'))
    class="active"
  @endif
>Some link</a>
</code>```

How would I achieve this in Laravel 5?

答:
This is how I do it without any named routes

```<code><a class="{{ str_contains(request()->url(), '/some-page') ? 'active' : '' }}" href="/some-page">Some Page</a>
</code>```

This is not a perfect solution but it works for most cases

Body:
I am currently generating my application urls using {{action('Namespace\Class@method')}}. How would I check if the current page request maps to that current action Namespace\Class@method?

I would like to do something like:

Some link

How would I achieve this in Laravel 5?

Body:
This is how I do it without any named routes

<a class="{{ str_contains(request()->url(), '/some-page') ? 'active' : '' }}" href="/some-page">Some Page</a>

This is not a perfect solution but it works for most cases


问:
Create Map in Java
I'd like to create a map that contains entries consisting of (int, Point2D)

How can I do this in Java?

I tried the following unsuccessfully.

```<code>HashMap hm = new HashMap();

hm.put(1, new Point2D.Double(50, 50));
</code>```

答:
There is even a better way to create a Map along with initialization:

```<code>Map<String, String> rightHereMap = new HashMap<String, String>()
{
    {
        put("key1", "value1");
        put("key2", "value2");
    }
};
</code>```

For more options take a look here How can I initialise a static Map?

Title: Create Map in Java

Body:
I'd like to create a map that contains entries consisting of (int, Point2D)

How can I do this in Java?

I tried the following unsuccessfully.

HashMap hm = new HashMap();

hm.put(1, new Point2D.Double(50, 50));

Body:
There is even a better way to create a Map along with initialization:

Map<String, String> rightHereMap = new HashMap<String, String>()
{
    {
        put("key1", "value1");
        put("key2", "value2");
    }
};

For more options take a look here How can I initialise a static Map?


问:
getline in C++ - Help needed
I am using getline to read up to end of newline but c++ getline gets me stuff till space,

I have txt file data as

address(tab char)1420 Happy Lane

When I do

getline(reader, ss, '\t') I get address in ss string.
when I do getline(reader, ss, '\n') I just get 1420.

I want full "1420 Happy Lane", How to get it ?

Thanks.

```<code>#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;
int main( int argc, char *argv[] )
{
        if( argc < 2 )
        {
                cout << "Missing filename as first argument" << "\n";
                exit(2);
        }

        vector<string> myvector;
        string ss;
        int i=0, j=0;

        ifstream reader(argv[1]);

        if (! reader )
        {
                cout << "Error opening input file : " << " " << argv[1] << '\n';
                return -1;
        }

        while( !reader.eof())
        {
                 if ((i+1) % 2 == 0 )
                        getline(reader, ss, '\n');
                 else
                         getline(reader, ss, '\t');
                if (ss[0] == '#')
                {
                        //Skip
                        getline(reader,ss, '\n');i=0;
                        continue;
                }

                i++;
                myvector.push_back(ss);
        }

        reader.close();

        vector<string>::iterator it;
        stringstream stream;
        int vecloc=1;
        string tag;
        string sData;

        cout << "myvector contains: \n";

        for ( it=myvector.begin() ; it < myvector.end(); it++ )
        {
                switch (vecloc)
                {
                case 1: stream << *it;  stream >> tag; vecloc++;break;
                case 2:
                                stream << *it;  stream >> sData;
                                // Do job
                                cout << tag << "   " << sData << "\n";
                                // Reset.
                                vecloc=1;       break;
                default :       break;
                }
                // Clear String stream
        stream.str(""); stream.clear();
        }

        return(0);
}
</code>```

output

/home/sr/utl

cat abc.txt

hey     c++ making me nuts.

/home/sr/utl

a.out abc.txt

myvector contains:

hey   c++

答:
I got a split() function you can use for that. Use \t as the delimeter:

```<code>void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}
</code>```

Title: getline in C++ - Help needed

Body:
I am using getline to read up to end of newline but c++ getline gets me stuff till space,

I have txt file data as

address(tab char)1420 Happy Lane

When I do

getline(reader, ss, '\t') I get address in ss string.
when I do getline(reader, ss, '\n') I just get 1420.

I want full "1420 Happy Lane", How to get it ?

Thanks.

#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;
int main( int argc, char *argv[] )
{
        if( argc < 2 )
        {
                cout << "Missing filename as first argument" << "\n";
                exit(2);
        }

        vector<string> myvector;
        string ss;
        int i=0, j=0;

        ifstream reader(argv[1]);

        if (! reader )
        {
                cout << "Error opening input file : " << " " << argv[1] << '\n';
                return -1;
        }

        while( !reader.eof())
        {
                 if ((i+1) % 2 == 0 )
                        getline(reader, ss, '\n');
                 else
                         getline(reader, ss, '\t');
                if (ss[0] == '#')
                {
                        //Skip
                        getline(reader,ss, '\n');i=0;
                        continue;
                }

                i++;
                myvector.push_back(ss);
        }

        reader.close();

        vector<string>::iterator it;
        stringstream stream;
        int vecloc=1;
        string tag;
        string sData;

        cout << "myvector contains: \n";

        for ( it=myvector.begin() ; it < myvector.end(); it++ )
        {
                switch (vecloc)
                {
                case 1: stream << *it;  stream >> tag; vecloc++;break;
                case 2:
                                stream << *it;  stream >> sData;
                                // Do job
                                cout << tag << "   " << sData << "\n";
                                // Reset.
                                vecloc=1;       break;
                default :       break;
                }
                // Clear String stream
        stream.str(""); stream.clear();
        }

        return(0);
}

output

/home/sr/utl

cat abc.txt

hey     c++ making me nuts.

/home/sr/utl

a.out abc.txt

myvector contains:

hey   c++

Body:
I got a split() function you can use for that. Use \t as the delimeter:

void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}


问:
Unable to uninstall certain applications and it throws an error "Could not open INSTALL.LOG file"
Whenever I try to uninstall certain applications I get an error Could not open INSTALL.LOG file and then just prevents the application from getting uninstalled. I had faced this issue several times.

答:
Thanks to The _khAttAm_ blog . Screenshot of the page placed at the bottom.

The solution is to go to the application's install location, find installer.log file in it and place it somewhere else. So that when the uninstaller runs, it will not find it and will ask you to select the file from a location. Now, select the file from where you have newly placed it. Now continue with uninstallation.

Done! Uninstallation completed!


问:
Why specify the namespace when using psr-4 autoloading with Composer?
I'm a little confused with how I should be using psr-4 autoloading in Composer. Let's say I've got a folder structure like this:

```<code>/
|- Core/
|   - Router.php
|- App/
|   - Models
|       User.php
|- composer.json
</code>```

Basically, in the project root: composer.json; a Core folder containing a Router php class; an App folder containing a Models folder that contains a User class.

The Router class looks like this:

```<code><?php
namespace Core;

class Router {
}
</code>```

and the Users class looks like this:

```<code><?php
namespace App\Models;

class User {
}
</code>```

So I can autoload these classes using the Composer psr-4 autoloader, I can do this in composer.json:

```<code>{
    "autoload": {
        "psr-4": {
            "Core\\": "Core",
            "App\\Models\\": "App/Models"
        }
    }
}
</code>```

So I can then use the classes without requiring them (after running composer dump-autoload) like this:

```<code>$router = new Core\Router();
$user = new App\Models\User();
</code>```

which works with no problems.

However, I can also do this in composer.json:

```<code>{
    "autoload": {
        "psr-4": {
            "": ""
        }
    }
}
</code>```

which, according to the documentation is a fallback directory where any namespace can be, relative to the root. So by having this "empty" entry in the composer autoloader, which I believe says "starting in the root, look in any directory for a class in any namespace", I can autoload any of my classes if I follow the correct folder naming / namespace structure.

So my question is, why would I do the former if the latter works and is much simpler? Is it a performance thing? Or is there another reason?

答:
Usually you only have one folder for your own project when using composer. Then you only need to specify one namespace.

Consider that you would rearrange your file structure to

```<code>/
|- lib/
|   - Core/
|      - Router.php
|   - App/
|      - Models
|          User.php
|- composer.json
</code>```

and change your composer.json to

```<code>{
    "autoload": {
        "psr-4": {
            "MyApp\\": "lib/"
        }
    }
}
</code>```

then you only have one specified namespace and you dont need to add any further namespaces. You can call your classes like this:

```<code>$router = new \MyApp\Core\Router;
$user   = new \MyApp\App\Models\User;
</code>```

or like this:

```<code>namespace MyApp;
$router = new Core\Router;
$user   = new App\Models\User;
</code>```

Body:
I'm a little confused with how I should be using psr-4 autoloading in Composer. Let's say I've got a folder structure like this:

/
|- Core/
|   - Router.php
|- App/
|   - Models
|       User.php
|- composer.json

Basically, in the project root: composer.json; a Core folder containing a Router php class; an App folder containing a Models folder that contains a User class.

The Router class looks like this:

<?php
namespace Core;

class Router {
}

and the Users class looks like this:

<?php
namespace App\Models;

class User {
}

So I can autoload these classes using the Composer psr-4 autoloader, I can do this in composer.json:

{
    "autoload": {
        "psr-4": {
            "Core\\": "Core",
            "App\\Models\\": "App/Models"
        }
    }
}

So I can then use the classes without requiring them (after running composer dump-autoload) like this:

$router = new Core\Router();
$user = new App\Models\User();

which works with no problems.

However, I can also do this in composer.json:

{
    "autoload": {
        "psr-4": {
            "": ""
        }
    }
}

which, according to the documentation is a fallback directory where any namespace can be, relative to the root. So by having this "empty" entry in the composer autoloader, which I believe says "starting in the root, look in any directory for a class in any namespace", I can autoload any of my classes if I follow the correct folder naming / namespace structure.

So my question is, why would I do the former if the latter works and is much simpler? Is it a performance thing? Or is there another reason?

Body:
Usually you only have one folder for your own project when using composer. Then you only need to specify one namespace.

Consider that you would rearrange your file structure to

/
|- lib/
|   - Core/
|      - Router.php
|   - App/
|      - Models
|          User.php
|- composer.json

and change your composer.json to

{
    "autoload": {
        "psr-4": {
            "MyApp\\": "lib/"
        }
    }
}

then you only have one specified namespace and you dont need to add any further namespaces. You can call your classes like this:

$router = new \MyApp\Core\Router;
$user   = new \MyApp\App\Models\User;

or like this:

namespace MyApp;
$router = new Core\Router;
$user   = new App\Models\User;


问:
How to make full screen mode, without covering the taskbar using :wpf c#
I need to change windows taskbar in my WPF application. For that I set WindowStyle="None", which means to disable the windows taskbar, and make custom taskbar with buttons for restoring, minimizing and closing the application. Now my problem is if the application is in maximize mode then I can't see the start menu on windows.

I found a similar question here, but when I tried this code it didn't compile. full screen mode, but don't cover the taskbar

How can I create my own taskbar and able to see the windows start menu when I maximized it? Is there a property window in xaml which can set it?

答:
```<code>WindowStyle="None"
AllowsTransparency="True"
</code>```

and

```<code>this.Top = 0;
this.Left = 0;
this.Width = SystemParameters.WorkArea.Width;
this.Height = SystemParameters.WorkArea.Height;
</code>```

Body:
WindowStyle="None"
AllowsTransparency="True"

and

this.Top = 0;
this.Left = 0;
this.Width = SystemParameters.WorkArea.Width;
this.Height = SystemParameters.WorkArea.Height;


答:
Just as (pointer + N) points to the Nth data element after the pointer argument, going the other way with (pointerA - pointerB) gives you the number of data elements betweeen the pointers.  In this case, the data element is int[3] (which you apparently already know since you are expecting 12...).

You shouldn't expect the difference in raw address value (which is machine-dependent in general anyway). C/C++ is converting for you.

Title: How to understand the output?

Body:
int a[2][3];
cout << a+1 << " " << a << " " << (a+1) - a << endl;

Output:

0029FAC0 0029FAB4 1

Shouldn't (a+1)-a be 0029FAC0-0029FAB4=12 ?


问:
unable to change width of image with bootstrap
I'm working on Carousel image slider with bootstrap. I'm unable to change the height of the image. If I try to change the height it's effecting for both height and width both. But I need to modify only width.

My code is like below :

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/
    bootstrap.min.css">

Carousel Example

        Previous

        Next

```

答:
You can try this:</p>

```<code>.carousel-inner .item img{
   max-width: none;
   width: your-width:
   height: your-height;
}
</code>```

Body:
You can try this:

.carousel-inner .item img{
   max-width: none;
   width: your-width:
   height: your-height;
}


问:
Delete associated model with ember-data
I have two models:

```<code>App.User = DS.Model.create({
  comments: DS.hasMany('App.Comment')
});

App.Comment = DS.Model.create({
  user: DS.belongsTo('App.User')
});
</code>```

When a user is deleted, it also will delete all its comments on the backend, so I should delete them from the client-side identity map.

I'm listing all the comments on the system from another place, so after deleting a user it would just crash.

Is there any way to specify this kind of dependency on the association? Thanks!

答:
I adapted the answer of @ahmacleod to work with ember-cli 2.13.1 and ember-data 2.13.0. I had an issue with nested relationships and the fact that after deleting an entity from the database its id was reused. This lead to conflicts with remnants in the ember-data model.

```<code>import Ember from 'ember';

export default Ember.Mixin.create({
    dependentRelationships: null,

    destroyRecord: function() {
        this.deleteDependentRelationships();

        return this._super()
        .then(function (model) {
            model.unloadRecord();

            return model;
        });
    },

    unloadRecord: function() {
        this.deleteDependentRelationships();

        this._super();
    },

    deleteDependentRelationships: function() {
        var self = this;
        var fields = Ember.get(this.constructor, 'fields');

        this.get('dependentRelationships').forEach(function(name) {
            self.deleteRelationship(name);
        });
    },

    deleteRelationship (name) {
        var self = this;
        self.get(name).then(function (records) {
            if (!records) {
                return;
            }

            var reset = [];
            if (!Ember.isArray(records)) {
                records = [records];
                reset = null;
            }

            records.forEach(function(record) {
                if (record) {
                    record.unloadRecord();
                }
            });

            self.set(name, reset);
        });
    },
});
</code>```

Eventually, I had to set the relationship to [] (hasMany) or null (belongsTo). Else I would have run into the following error message:

Assertion Failed: You cannot update the id index of an InternalModel once set. Attempted to update <id>.

Maybe this is helpful for somebody else.

Title: Delete associated model with ember-data

Body:
I have two models:

App.User = DS.Model.create({
  comments: DS.hasMany('App.Comment')
});

App.Comment = DS.Model.create({
  user: DS.belongsTo('App.User')
});

When a user is deleted, it also will delete all its comments on the backend, so I should delete them from the client-side identity map.

I'm listing all the comments on the system from another place, so after deleting a user it would just crash.

Is there any way to specify this kind of dependency on the association? Thanks!

Body:
I adapted the answer of @ahmacleod to work with ember-cli 2.13.1 and ember-data 2.13.0. I had an issue with nested relationships and the fact that after deleting an entity from the database its id was reused. This lead to conflicts with remnants in the ember-data model.

import Ember from 'ember';

export default Ember.Mixin.create({
    dependentRelationships: null,

    destroyRecord: function() {
        this.deleteDependentRelationships();

        return this._super()
        .then(function (model) {
            model.unloadRecord();

            return model;
        });
    },

    unloadRecord: function() {
        this.deleteDependentRelationships();

        this._super();
    },

    deleteDependentRelationships: function() {
        var self = this;
        var fields = Ember.get(this.constructor, 'fields');

        this.get('dependentRelationships').forEach(function(name) {
            self.deleteRelationship(name);
        });
    },

    deleteRelationship (name) {
        var self = this;
        self.get(name).then(function (records) {
            if (!records) {
                return;
            }

            var reset = [];
            if (!Ember.isArray(records)) {
                records = [records];
                reset = null;
            }

            records.forEach(function(record) {
                if (record) {
                    record.unloadRecord();
                }
            });

            self.set(name, reset);
        });
    },
});

Eventually, I had to set the relationship to [] (hasMany) or null (belongsTo). Else I would have run into the following error message:

Assertion Failed: You cannot update the id index of an InternalModel once set. Attempted to update <id>.

Maybe this is helpful for somebody else.


问:
Laravel 5.4 session is not being set if dd method is used
I am using laravel 5.4. In a method of a controller I have setting a value in session. If I call the dd() right after setting the session the dd() is showing all the session with the session I have just set. But if I fetch the session from another method the session is not available. If I remove the dd() from session setter method, I am getting the session properly.

My Code is as below:

```<code>public class TestController{
  public function setSession(){
    session(['test_key' => 'test_value']);//setting up the session
    dd(session()->all());//getting the session properly here
  }

  public function showSession(){
    dd(session()->all());//Here we are not getting the session
  }
}
</code>```

If we remove the dd() from setSession() session it works properly.  Is it a bug of Laravel or it's intentional. I am interested to know the root cause of this fact. Thanks

答:
Remove  this line dd(session()->all())

from setSession() and try it again.

Body:
I am using laravel 5.4. In a method of a controller I have setting a value in session. If I call the dd() right after setting the session the dd() is showing all the session with the session I have just set. But if I fetch the session from another method the session is not available. If I remove the dd() from session setter method, I am getting the session properly.

My Code is as below:

public class TestController{
  public function setSession(){
    session(['test_key' => 'test_value']);//setting up the session
    dd(session()->all());//getting the session properly here
  }

  public function showSession(){
    dd(session()->all());//Here we are not getting the session
  }
}

If we remove the dd() from setSession() session it works properly.  Is it a bug of Laravel or it's intentional. I am interested to know the root cause of this fact. Thanks


问:
XSLT: Merge child elements
Hi I am trying to merge child nodes into a single node containing all the data.

Here is my sample XML,

```<code><root>
<list>
<label>Label 1</label>
    <item>some text</item>
<label>Label 2</label>
    <item>some text</item>
    <item>some more text </item>
    <item>some more text</item>
<label>Label 3</label>
    <item>other text</item>
    <item>some text</item>
    <item>some more text</item>
</list>
</root>
</code>```

I need to merge item nodes following label element into one group  and contents into
 tag. Desired output is like below

```<code><root>
    <list>
    <label>Label 1</label>
        <item>some text</item>
    <label>Label 2</label>
        <item><p>some text</p>
        <p>some more text </p>
        <p>some more text</p></item>
    <label>Label 3</label>
        <item><p>other text</p>
        <p>some text</p>
        <p>some more text</p></item>
    </list>
</root>
</code>```

So far i tried following template but does not work as it should be, it merges all items in to one but i need to tag them into separate p tags. Thanks for help.

```<code><xsl:template match="list">
    <xsl:copy>
        <xsl:for-each-group select="*" group-adjacent="boolean(self::item)">
            <xsl:choose>
                <xsl:when test="current-grouping-key()">
                    <item>
                        <xsl:apply-templates select="current-group()/node()"/>
                    </item>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="current-group()"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>
</code>```

答:
I think you are close, you only need to make sure process the grouped item elements with a template creating p elements:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:output indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="list">
    <xsl:copy>
        <xsl:for-each-group select="*" group-adjacent="boolean(self::item)">
            <xsl:choose>
                <xsl:when test="current-grouping-key()">
                    <item>
                        <xsl:apply-templates select="current-group()"/>
                    </item>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="current-group()"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </xsl:copy>
    </xsl:template>

    <xsl:template match="item">
        <p>
            <xsl:apply-templates/>
        </p>
    </xsl:template>
</xsl:transform>
</code>```

That way (http://xsltransform.net/naZXpWX) I get

```<code><root>
   <list>
      <label>Label 1</label>
      <item>
         <p>some text</p>
      </item>
      <label>Label 2</label>
      <item>
         <p>some text</p>
         <p>some more text </p>
         <p>some more text</p>
      </item>
      <label>Label 3</label>
      <item>
         <p>other text</p>
         <p>some text</p>
         <p>some more text</p>
      </item>
   </list>
</root>
</code>```

That is slightly different from your posted desired result, I am not sure whether that is an error in your posted sample or whether you want to treat a group with only one item differently, you could do that with an additional check inside of the for-each-group:

```<code><xsl:template match="list">
<xsl:copy>
    <xsl:for-each-group select="*" group-adjacent="boolean(self::item)">
        <xsl:choose>
            <xsl:when test="current-grouping-key()">
                <item>
                    <xsl:choose>
                        <xsl:when test="current-group()[2]">
                            <xsl:apply-templates select="current-group()"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:apply-templates/>
                        </xsl:otherwise>
                    </xsl:choose>
                </item>
            </xsl:when>
            <xsl:otherwise>
                <xsl:apply-templates select="current-group()"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each-group>
</xsl:copy>
</xsl:template>
</code>```

as done in http://xsltransform.net/naZXpWX/1

Title: XSLT: Merge child elements

Body:
Hi I am trying to merge child nodes into a single node containing all the data.

Here is my sample XML,

<root>
<list>
Label 1
    <item>some text</item>
Label 2
    <item>some text</item>
    <item>some more text </item>
    <item>some more text</item>
Label 3
    <item>other text</item>
    <item>some text</item>
    <item>some more text</item>
</list>
</root>

I need to merge item nodes following label element into one group  and contents into
 tag. Desired output is like below

<root>
    <list>
    Label 1
        <item>some text</item>
    Label 2
        <item>
some text

some more text

some more text
</item>
    Label 3
        <item>
other text

some text

some more text
</item>
    </list>
</root>

So far i tried following template but does not work as it should be, it merges all items in to one but i need to tag them into separate p tags. Thanks for help.

<xsl:template match="list">
    <xsl:copy>
        <xsl:for-each-group select="*" group-adjacent="boolean(self::item)">
            <xsl:choose>
                <xsl:when test="current-grouping-key()">
                    <item>
                        <xsl:apply-templates select="current-group()/node()"/>
                    </item>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="current-group()"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

Body:
I think you are close, you only need to make sure process the grouped item elements with a template creating p elements:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:output indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="list">
    <xsl:copy>
        <xsl:for-each-group select="*" group-adjacent="boolean(self::item)">
            <xsl:choose>
                <xsl:when test="current-grouping-key()">
                    <item>
                        <xsl:apply-templates select="current-group()"/>
                    </item>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="current-group()"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </xsl:copy>
    </xsl:template>

    <xsl:template match="item">
        <p>
            <xsl:apply-templates/>
        </p>
    </xsl:template>
</xsl:transform>

That way (http://xsltransform.net/naZXpWX) I get

<root>
   <list>
      <label>Label 1</label>
      <item>
         <p>some text</p>
      </item>
      <label>Label 2</label>
      <item>
         <p>some text</p>
         <p>some more text </p>
         <p>some more text</p>
      </item>
      <label>Label 3</label>
      <item>
         <p>other text</p>
         <p>some text</p>
         <p>some more text</p>
      </item>
   </list>
</root>

That is slightly different from your posted desired result, I am not sure whether that is an error in your posted sample or whether you want to treat a group with only one item differently, you could do that with an additional check inside of the for-each-group:

<xsl:template match="list">
<xsl:copy>
    <xsl:for-each-group select="*" group-adjacent="boolean(self::item)">
        <xsl:choose>
            <xsl:when test="current-grouping-key()">
                <item>
                    <xsl:choose>
                        <xsl:when test="current-group()[2]">
                            <xsl:apply-templates select="current-group()"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:apply-templates/>
                        </xsl:otherwise>
                    </xsl:choose>
                </item>
            </xsl:when>
            <xsl:otherwise>
                <xsl:apply-templates select="current-group()"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each-group>
</xsl:copy>
</xsl:template>

as done in http://xsltransform.net/naZXpWX/1


问:
Strange Xcode behaviour
I am about to raise this as a bug with apple support but it takes a long time to get any response from them so ... I wanted to ask here.

Debugging an app where i use some dateTime conversions between timezones.
I get the following strange behavior and I wonder if anyone else has seen this and knows how to fix it.

Xcode 8.3.2

You can see that the GMTDate is displaying 2 completely different date/time values ( they aren't even related values) and it is difficult to know which one is correct.
I have restarted Xcode /computer, etc, but still the same!

Screenshot attached:

```<code>- (NSString*) convertToDeviceTime:(NSString*) GMTDate {

//create the formatter for parsing
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

//parsing the string and converting it to NSDate
NSDate *myGMTDate = [df dateFromString: GMTDate];

//create the formatter for the output
NSDateFormatter *out_df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[out_df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

//output the date
NSString *myDeviceDate =[out_df stringFromDate:myGMTDate];
NSLog(@"the date is %@",myDeviceDate);
return myDeviceDate;
}
</code>```

new screenshot below - this has to be something wrong with Xcode,
the real value of 'token' shows in the quick look, but the debugger window shows it as a date! Weird. I have restarted the Mac, still the same.

Update: It is happening with all NSString variables. As soon as I write a value to them, the debugger window shows them with the same date value. If I print them to the console or NSLog, then the values are shown correctly.

答:
Found the culprit.
In the debugger the "Edit Summary Format" popup I had somehow inadvertently pasted this date value, and it was showing this for all NSString values.

FYI:It is NOT project specific, so when I loaded another project, it kept that "Edit Summary Format" string and applied it to all NSStrings.

Kudos to an older SO post here: Strange values displayed in Xcode debugger

Screenshots attached!

Title: Strange Xcode behaviour

Body:
I am about to raise this as a bug with apple support but it takes a long time to get any response from them so ... I wanted to ask here.

Debugging an app where i use some dateTime conversions between timezones.
I get the following strange behavior and I wonder if anyone else has seen this and knows how to fix it.

Xcode 8.3.2

You can see that the GMTDate is displaying 2 completely different date/time values ( they aren't even related values) and it is difficult to know which one is correct.
I have restarted Xcode /computer, etc, but still the same!

Screenshot attached:

- (NSString*) convertToDeviceTime:(NSString*) GMTDate {

//create the formatter for parsing
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

//parsing the string and converting it to NSDate
NSDate *myGMTDate = [df dateFromString: GMTDate];

//create the formatter for the output
NSDateFormatter *out_df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[out_df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

//output the date
NSString *myDeviceDate =[out_df stringFromDate:myGMTDate];
NSLog(@"the date is %@",myDeviceDate);
return myDeviceDate;
}

new screenshot below - this has to be something wrong with Xcode,
the real value of 'token' shows in the quick look, but the debugger window shows it as a date! Weird. I have restarted the Mac, still the same.

Update: It is happening with all NSString variables. As soon as I write a value to them, the debugger window shows them with the same date value. If I print them to the console or NSLog, then the values are shown correctly.


问:
CURL error "couldn't connect to host" on http server only
i call a CURL code for calling a URL (the URL sends an email).
When i call the URL from the browser, it works, but when i execute it from the curl php code, it doesn't work.

also, the exact same curl code works on my https SSL production server, but not on my http development server.

The error i get on my development http server is "couldn't connect to host".

This is the code:

```<code>$ch = curl_init();

$requestedUrl = http://XXX.XXX.XX.XX/myproject/index.php?entryPoint=viewReport&record=.....etc..

curl_setopt($ch, CURLOPT_URL, $requestedUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);
if ($data === FALSE) {
    $GLOBALS['log']->fatal("error = " . print_r(curL_error($ch),true));
}

curl_close($ch);
</code>```

i read every post there is on this issue.
i don't know if i'm behind proxy or not and i dont know how to get the ip of the proxy if i'm behind one.

i have tried adding curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

tried adding :

```<code>curl_setopt($ch, CURLOPT_PROXYTYPE, 'HTTP');
curl_setopt($ch, CURLOPT_PROXY, "http://XXX.XXX.XX.XX"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number
</code>```

tried opeining port 1080 in the firewall (which is open for any http address).

i'm out of ideas, so please help me :)

答:
i just changed the IP of the url to "localhost" and it worked :)
$requestedUrl = http://localhost/myproject/index.php?entryPoint=viewReport&record=.....etc..</p>

Body:
i call a CURL code for calling a URL (the URL sends an email).
When i call the URL from the browser, it works, but when i execute it from the curl php code, it doesn't work.

also, the exact same curl code works on my https SSL production server, but not on my http development server.

The error i get on my development http server is "couldn't connect to host".

This is the code:

$ch = curl_init();

$requestedUrl = http://XXX.XXX.XX.XX/myproject/index.php?entryPoint=viewReport&record=.....etc..

curl_setopt($ch, CURLOPT_URL, $requestedUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);
if ($data === FALSE) {
    $GLOBALS['log']->fatal("error = " . print_r(curL_error($ch),true));
}

curl_close($ch);

i read every post there is on this issue.
i don't know if i'm behind proxy or not and i dont know how to get the ip of the proxy if i'm behind one.

i have tried adding curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

tried adding :

curl_setopt($ch, CURLOPT_PROXYTYPE, 'HTTP');
curl_setopt($ch, CURLOPT_PROXY, "http://XXX.XXX.XX.XX"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number

tried opeining port 1080 in the firewall (which is open for any http address).

i'm out of ideas, so please help me :)


问:
How do i select multiple rows which match the value of an item in an array?
I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:</p>

```<code>$id = array(1,4,7,3,11,120); // The array containing the ids

$query = mysql_query("SELECT *
                        FROM posts
                       WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`
</code>```

答:
I think you want the IN clause:

```<code>$idList = implode(",", $id);

SELECT *
FROM posts
WHERE id IN ( $idList );
</code>```

The implode() function will turn your array of numbers into a comma-separated string of those same values. When you use it as part of an IN clause, it tells the database to use those values as a lookup table to match id against.

Standard Disclaimer/Warning:

As with any SQL query, you really shouldn't be directly concatenating variables into the query string. You're just opening yourself up to SQL injection. Use prepared/parameterized statements instead.

Body:
I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:

$id = array(1,4,7,3,11,120); // The array containing the ids

$query = mysql_query("SELECT *
                        FROM posts
                       WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`

Body:
I think you want the IN clause:

$idList = implode(",", $id);

SELECT *
FROM posts
WHERE id IN ( $idList );

The implode() function will turn your array of numbers into a comma-separated string of those same values. When you use it as part of an IN clause, it tells the database to use those values as a lookup table to match id against.

Standard Disclaimer/Warning:

As with any SQL query, you really shouldn't be directly concatenating variables into the query string. You're just opening yourself up to SQL injection. Use prepared/parameterized statements instead.


问:
Is there a way to get a 32bit C++ compiler to follow 16bit integer promotion rules?
With the following code:

```<code>#include <stdint.h>

uint16_t test() {
    uint16_t a = 1000;
    uint16_t b = 1000;
    uint16_t c = 100;
    return (a * b) / c;
}
</code>```

A compiler targeting a 32bit machine will return 10000, but one targeting a 16 bit machine will return 169. The behavior is explained by C's integer promotion rules.

This is a problem when unit testing firmware for a 8 or 16 bit machine on a desktop PC.

Right now, either casting every multiplication or putting it inside a function returning the same type are the only options I can think of. Ideally some compiler switch would exist, but I haven't seen one.

Happy with a solution for either GCC, Clang or MSVC.

答:
No, there isn't any way to do what you're asking.

Right now, either casting every multiplication or putting it inside a function returning the same type are the only options I can think of.

Another option is avoiding using multiple operations in a single expression, implicitly forcing a conversion back to uint16_t:

```<code>uint16_t test() {
    uint16_t a = 1000;
    uint16_t b = 1000;
    uint16_t c = 100;
    a *= b;
    a /= c;
    return a;
}
</code>```

Or, using a function, that function could be an overloaded operator to keep the code readable:

```<code>#include <stdint.h>

template <typename T>
struct unpromoted
{
   T value;

   unpromoted() = default;
   unpromoted(T value) : value(value) { }
   explicit operator T() { return value; }

   friend unpromoted operator*(unpromoted a, unpromoted b)
   { return a.value * b.value; }

   friend unpromoted operator/(unpromoted a, unpromoted b)
   { return a.value / b.value; }

   // add other operators as well
};

using uuint16_t = unpromoted<uint16_t>;

uuint16_t test() {
    uuint16_t a = 1000;
    uuint16_t b = 1000;
    uuint16_t c = 100;
    return (a * b) / c; // returns 169
}
</code>```

Note that this does require a cast when e.g. adding an uuint16_t and an uuint8_t. It's possible to let that return an uuint16_t, but I probably wouldn't bother with it.

Body:
With the following code:

#include <stdint.h>

uint16_t test() {
    uint16_t a = 1000;
    uint16_t b = 1000;
    uint16_t c = 100;
    return (a * b) / c;
}

A compiler targeting a 32bit machine will return 10000, but one targeting a 16 bit machine will return 169. The behavior is explained by C's integer promotion rules.

This is a problem when unit testing firmware for a 8 or 16 bit machine on a desktop PC.

Right now, either casting every multiplication or putting it inside a function returning the same type are the only options I can think of. Ideally some compiler switch would exist, but I haven't seen one.

Happy with a solution for either GCC, Clang or MSVC.

Body:
No, there isn't any way to do what you're asking.

Right now, either casting every multiplication or putting it inside a function returning the same type are the only options I can think of.

Another option is avoiding using multiple operations in a single expression, implicitly forcing a conversion back to uint16_t:

uint16_t test() {
    uint16_t a = 1000;
    uint16_t b = 1000;
    uint16_t c = 100;
    a *= b;
    a /= c;
    return a;
}

Or, using a function, that function could be an overloaded operator to keep the code readable:

#include <stdint.h>

template <typename T>
struct unpromoted
{
   T value;

   unpromoted() = default;
   unpromoted(T value) : value(value) { }
   explicit operator T() { return value; }

   friend unpromoted operator*(unpromoted a, unpromoted b)
   { return a.value * b.value; }

   friend unpromoted operator/(unpromoted a, unpromoted b)
   { return a.value / b.value; }

   // add other operators as well
};

using uuint16_t = unpromoted<uint16_t>;

uuint16_t test() {
    uuint16_t a = 1000;
    uuint16_t b = 1000;
    uuint16_t c = 100;
    return (a * b) / c; // returns 169
}

Note that this does require a cast when e.g. adding an uuint16_t and an uuint8_t. It's possible to let that return an uuint16_t, but I probably wouldn't bother with it.


问:
How to delay a JQUERY onload function
I've found some solutions online for this but couldn't make them work for me. Or maybe I was doing it wrong. I am completely newbie in JS, can you please help me to delay this function?</p>

```<code>jQuery(window).on('load', function(){ var $ = jQuery;
var $container = $('.social_container');
$container.masonry({
      columnWidth:350,
      gutterWidth: 355,
      itemSelector: '.masonryImage'
});
});
</code>```

答:
The approach should be to wait for the plug-in to load and only then call your function.</p>

```<code>var finished_rendering = function() {
  console.log("finished rendering plugins");
}

// In your onload handler
FB.Event.subscribe('xfbml.render', finished_rendering);
</code>```

Title: How to delay a JQUERY onload function

Body:
I've found some solutions online for this but couldn't make them work for me. Or maybe I was doing it wrong. I am completely newbie in JS, can you please help me to delay this function?

jQuery(window).on('load', function(){ var $ = jQuery;
var $container = $('.social_container');
$container.masonry({
      columnWidth:350,
      gutterWidth: 355,
      itemSelector: '.masonryImage'
});
});

Body:
The approach should be to wait for the plug-in to load and only then call your function.

var finished_rendering = function() {
  console.log("finished rendering plugins");
}

// In your onload handler
FB.Event.subscribe('xfbml.render', finished_rendering);