问:
I'm trying to create 5 different div elements using this loop
I'm trying to create 5 different audio players from the following code to call them out individually wherever I need it in the HTML document: https://codepen.io/katzkode/pen/ZbxYYG

The issue is that this 2 loops use a single div element to call the function:

For audio:

```<code>/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}
</code>```

For div element:

```<code>/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
        $("#audio-players").append(playerString);
    }
}
</code>```

But what I'm trying to do is to create 5 different elements to tickle them all individually and call them wherever I need it in the website with div id="audio-players1", div id="audio-players2", etc.

I've tried to do this for both loops:

Instead of

```<code>$("#audio-players")
</code>```

Add this:

```<code>$("#audio-players" + f)
</code>```

But then the buttons won't work.

Here's the code to pull the files from:

```<code>var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];
</code>```

And I'm unsure how to proceed, I'm still learning. Thank you.

答:
Here's a CODEPEN of what you're looking for.

Changes compared to your code:

Re-ordered div and audio creation:

```<code>createAudioPlayers();
createAudioElements();
</code>```

As you need something like #audio-players2, just tweaked this code a bit:

```<code>for (f in files) {
    var playerString = "<div id=\"audio-players-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
    $("body").append(playerString);
}
</code>```

In the function createAudioElements(), append audio based on the audio-player (DIV) ID:

```<code>$("#audio-players-"+f).append(audioString);
</code>```

Edit:

New CODEPEN. I think I figured out the issue here. So when you try to add the players separately, the buttons wouldn't work BUT when they were added on the go while creation, all worked fine, right?

So here's the thing: bindAudioPlayer wasn't finding the correct element on adding a player separately to the DOM as well as the timeline and other elements.

In the new codepen, I've added a button with a select option, which when selected adds a particular player (based on the value) to the DOM. Check the onClick code:

```<code>  $('a.add_player').click(function() {
      var val = $(this).parent().find('select.player_num').val();
      if(!$('body div#audio-players'+val).length) {
         var playerString = "<div id=\"audio-players" + val + "\" class=\"audioplayer\"><button id=\"playbutton-" + val + "\" class=\"play playbutton\"></button><div id=\"timeline-" + val + "\" class=\"timeline\"><div id=\"playhead-" + val + "\" class=\"playhead\"></div></div><audio id=\"audio-" + val + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[val-1] + "\"></audio></div>";
         $("body").append(playerString);

        // Populate Audio List
         populateAudioList(val);
         populateComponentDictionary(val);
      }
  });
</code>```

If you can also check the populateAudioList function, in which the loop is gotten rid of and the passed value is used to select the DOM element and accordingly events are bound to the selector.

Let me know if this is the desired output. Hope this helps. :)

Edit 2

CODEPEN

I've added a function named createAudioPlayersSeparately() which, I think, fulfils the requirement.

If you notice, I've swapped files for player 3 and player 4 i.e. used file 4 for player 3 and file 3 for player 4. Now, that means, it should be easy enough to call any player with any audio "wherever" you'd like on the page. Just make sure you call populateAudioList() and populateComponentDictionary() accordingly.

Hope this helps. :)

Body:
I'm trying to create 5 different audio players from the following code to call them out individually wherever I need it in the HTML document: https://codepen.io/katzkode/pen/ZbxYYG

The issue is that this 2 loops use a single div element to call the function:

For audio:

/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}

For div element:

/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button>

";
        $("#audio-players").append(playerString);
    }
}

But what I'm trying to do is to create 5 different elements to tickle them all individually and call them wherever I need it in the website with div id="audio-players1", div id="audio-players2", etc.

I've tried to do this for both loops:

Instead of

$("#audio-players")

Add this:

$("#audio-players" + f)

But then the buttons won't work.

Here's the code to pull the files from:

var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];

And I'm unsure how to proceed, I'm still learning. Thank you.

Body:
Here's a CODEPEN of what you're looking for.

Changes compared to your code:

Re-ordered div and audio creation:

createAudioPlayers();
createAudioElements();

As you need something like #audio-players2, just tweaked this code a bit:

for (f in files) {
    var playerString = "<div id=\"audio-players-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
    $("body").append(playerString);
}

In the function createAudioElements(), append audio based on the audio-player (DIV) ID:

$("#audio-players-"+f).append(audioString);

Edit:

New CODEPEN. I think I figured out the issue here. So when you try to add the players separately, the buttons wouldn't work BUT when they were added on the go while creation, all worked fine, right?

So here's the thing: bindAudioPlayer wasn't finding the correct element on adding a player separately to the DOM as well as the timeline and other elements.

In the new codepen, I've added a button with a select option, which when selected adds a particular player (based on the value) to the DOM. Check the onClick code:

  $('a.add_player').click(function() {
      var val = $(this).parent().find('select.player_num').val();
      if(!$('body div#audio-players'+val).length) {
         var playerString = "<div id=\"audio-players" + val + "\" class=\"audioplayer\"><button id=\"playbutton-" + val + "\" class=\"play playbutton\"></button><div id=\"timeline-" + val + "\" class=\"timeline\"><div id=\"playhead-" + val + "\" class=\"playhead\"></div></div><audio id=\"audio-" + val + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[val-1] + "\"></audio></div>";
         $("body").append(playerString);

        // Populate Audio List
         populateAudioList(val);
         populateComponentDictionary(val);
      }
  });

If you can also check the populateAudioList function, in which the loop is gotten rid of and the passed value is used to select the DOM element and accordingly events are bound to the selector.

Let me know if this is the desired output. Hope this helps. :)

Edit 2

CODEPEN

I've added a function named createAudioPlayersSeparately() which, I think, fulfils the requirement.

If you notice, I've swapped files for player 3 and player 4 i.e. used file 4 for player 3 and file 3 for player 4. Now, that means, it should be easy enough to call any player with any audio "wherever" you'd like on the page. Just make sure you call populateAudioList() and populateComponentDictionary() accordingly.

Hope this helps. :)


来源: stackexchange

问:
How to create a filled arrow CustomLineCap?
The MSDN documentation has several open arrow examples but no examples for filled arrows.

I just want to create a bigger arrow than the default LineCapArrowAnchor. I tried several things and can't get it to work. It should be simple, right?

答: Found it. Looks like there's an AdjustableArrowCap class that derives from CustomLineCap and does just what I wanted.

OwnerDisplayName: djeidot

ContentLicense: CC BY-SA 2.5


问:
Passing a Variable to a system stored procedure
I am sure I am missing something simple. I am looking to map some of my data objects. I wanted to create a procedure would insert the results of sp_depends and insert data name.

Here is what I have created:

```<code>create table DatasetMapping
(
    Name nvarchar(257),
    Type nvarchar(16),
    updated nvarchar(7),
    Selected nvarchar(8),
    Column sysname
);

Insert into DatasetMapping
    exec sp_depends 'dbo.PositionReport_Quote_V3_2016'
</code>```

This works great manually.

I then created

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Repotingdatasets]
AS
    DECLARE @object NVARCHAR(257)

    INSERT INTO DatasetMapping
        EXEC sp_epends  @objname = @object

    EXEC [dbo].[Repotingdatasets] @object =' dbo.PositionReport_Quote_V3_2016';
</code>```

but I only get an error:

Msg 8146, Level 16, State 2, Procedure Repotingdatasets, Line 0 [Batch Start Line 48]

  Procedure Repotingdatasets has no parameters and arguments were supplied

答:
You don't declare the variable like that if you intend to pass it.  You're looking for this:

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Repotingdatasets] @object nvarchar(257)
AS
BEGIN

INSERT INTO DatasetMapping
EXEC sp_depends  @objname=@object

END
</code>```

Then..

```<code>EXEC [dbo].[Repotingdatasets]  @object =' dbo.PositionReport_Quote_V3_2016';
</code>```

If you want a default value add it to the same spot:

```<code>CREATE PROCEDURE [dbo].[Repotingdatasets] @object nvarchar(257) = 'default'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am sure I am missing something simple. I am looking to map some of my data objects. I wanted to create a procedure would insert the results of sp_depends and insert data name.

Here is what I have created:

create table DatasetMapping
(
    Name nvarchar(257),
    Type nvarchar(16),
    updated nvarchar(7),
    Selected nvarchar(8),
    Column sysname
);

Insert into DatasetMapping
    exec sp_depends 'dbo.PositionReport_Quote_V3_2016'

This works great manually.

I then created

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Repotingdatasets]
AS
    DECLARE @object NVARCHAR(257)

    INSERT INTO DatasetMapping
        EXEC sp_epends  @objname = @object

    EXEC [dbo].[Repotingdatasets] @object =' dbo.PositionReport_Quote_V3_2016';

but I only get an error:

Msg 8146, Level 16, State 2, Procedure Repotingdatasets, Line 0 [Batch Start Line 48]

  Procedure Repotingdatasets has no parameters and arguments were supplied

Body:
You don't declare the variable like that if you intend to pass it.  You're looking for this:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Repotingdatasets] @object nvarchar(257)
AS
BEGIN

INSERT INTO DatasetMapping
EXEC sp_depends  @objname=@object

END

Then..

EXEC [dbo].[Repotingdatasets]  @object =' dbo.PositionReport_Quote_V3_2016';

If you want a default value add it to the same spot:

CREATE PROCEDURE [dbo].[Repotingdatasets] @object nvarchar(257) = 'default'


问:
BufferedWriter write string line by line
Hello I am building a program that writes an output to a text file.
In my program my String looks like this:

```<code>MyName
Addres
Location
Paycheck
</code>```

But when I write it to a text file it looks like this:

```<code>MyName Addres Location Paycheck
</code>```

I am writing everything from a single toString method. How can I use bufferedwriter so that it formats the string while writing it?

Here's my code:

```<code>                               if (file != null) {
                                    FileWriter fileWriter = null;
                                    try {
                                        fileWriter = new FileWriter(file.getAbsolutePath());

                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    BufferedWriter out = new BufferedWriter(fileWriter);
                                    try {
                                        out.write(emp.toString());
                                        out.close();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
</code>```

EDIT:

Here is the toString method for the emp class:

```<code>@Override
public String toString() {
    return "Name: " + name + " \nDOB: " + dob + " \nAddress: " + address + " \n******Paycheck******\nSalary: "
            + myPaycheck.getSalary() + "\nFederal Income: " + myPaycheck.getTaxes() + "\nSocial Security: "+ myPaycheck.getSocialSecurity() + "\nMedicare: " + myPaycheck.getMedicare()
             + "\nNet Salary: " + myPaycheck.getNetPay() + "";
}
</code>```

答:
You either need to use System.lineSeparator() while writing text to file or change your toString() method to add a line separator between each line or object added

Edit
Your code writes your string as separate line only. Try reading the lines from output file and print each line, you will see that the reader treats each detail as separate line. Now if you wish to write it into the file with exact format so that it is shown in next line in file u have to give the inputs separately maybe by adding the objects to an ArrayList and iterating the same.

Body:
Hello I am building a program that writes an output to a text file.
In my program my String looks like this:

MyName
Addres
Location
Paycheck

But when I write it to a text file it looks like this:

MyName Addres Location Paycheck

I am writing everything from a single toString method. How can I use bufferedwriter so that it formats the string while writing it?

Here's my code:

                               if (file != null) {
                                    FileWriter fileWriter = null;
                                    try {
                                        fileWriter = new FileWriter(file.getAbsolutePath());

                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    BufferedWriter out = new BufferedWriter(fileWriter);
                                    try {
                                        out.write(emp.toString());
                                        out.close();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }

EDIT:

Here is the toString method for the emp class:

@Override
public String toString() {
    return "Name: " + name + " \nDOB: " + dob + " \nAddress: " + address + " \n******Paycheck******\nSalary: "
            + myPaycheck.getSalary() + "\nFederal Income: " + myPaycheck.getTaxes() + "\nSocial Security: "+ myPaycheck.getSocialSecurity() + "\nMedicare: " + myPaycheck.getMedicare()
             + "\nNet Salary: " + myPaycheck.getNetPay() + "";
}


问:
Calling javascript function inside jquery ajax response file code
I am trying to call date_cal() javascript function inside ajax response (wall_list.php).Every thing is fine am getting correct response. But its not calling date_cal() function.

main file:

$.ajax({

```<code>  url: 'wall_list.php',
  data:"dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
  type: 'POST',
success: function (resp) {

if(resp)
{
 //alert(resp);
  document.getElementById('wall_listdiv').innerHTML=resp;

}
</code>```

Wall_list.php

Some code...................

```<code>>   <td id="<?php print $key; ?>" class="tm_td" valign="top" colspan=2>
>

    <script language="JavaScript">
                                date_cal('<?php print $commentcreatetimearr[$key]; ?>','<?php print $key; ?>');
                                </script>

>       </td>
</code>```

Some code......................

it's not calling javascript there.

Can anyone explain how to all this function in response.

答:
here you go

```<code>$.ajax({
    url: 'wall_list.php',
    data: "dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
    type: 'POST',
    success: function (resp){
        if(resp){
            $("#wall_listdiv").html(resp);
        }
    },
    dataType: 'html'
});
</code>```

What you want to do is, specify the return dataType as html.
From jQuery API

```<code>If html is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string. Similarly, script will execute the JavaScript that is pulled back from the server, then return the script itself as textual data.
</code>```

More information here: jQuery.ajax() - jQuery API

Body:
I am trying to call date_cal() javascript function inside ajax response (wall_list.php).Every thing is fine am getting correct response. But its not calling date_cal() function.

main file:

$.ajax({

  url: 'wall_list.php',
  data:"dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
  type: 'POST',
success: function (resp) {

if(resp)
{
 //alert(resp);
  document.getElementById('wall_listdiv').innerHTML=resp;

}

Wall_list.php

Some code...................

>   <td id="<?php print $key; ?>" class="tm_td" valign="top" colspan=2>
>

>

Some code......................

it's not calling javascript there.

Can anyone explain how to all this function in response.

Body:
here you go

$.ajax({
    url: 'wall_list.php',
    data: "dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
    type: 'POST',
    success: function (resp){
        if(resp){
            $("#wall_listdiv").html(resp);
        }
    },
    dataType: 'html'
});

What you want to do is, specify the return dataType as html.
From jQuery API

If html is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string. Similarly, script will execute the JavaScript that is pulled back from the server, then return the script itself as textual data.

More information here: jQuery.ajax() - jQuery API


Title: Combine dictionary according to index

Body:
Let us Assume, I have a key value pair in python, such as the following.

a = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'test1', 'test', '', '', '', '', '', '', '', '', '', '']

now I want to combine these values with:

b = {"18", "17", "16", "15", "14", "13", "12", "11", "21", "22", "23", "24", "25", "26", "27", "28","48", "47", "46", "45", "44", "43", "42", "41", "31", "32", "33", "34", "35", "36", "37", "38"}

Is there any way where I can combine the values from variable a against the \ b like result shown below:

c = {'44': ['test1'], '43': ['test2']}

thank you.

Body:
You may use zip to solve your problem:

a = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'test1', 'test', '', '', '', '',
     '', '', '', '', '', '']
b = ["18", "17", "16", "15", "14", "13", "12", "11", "21", "22", "23", "24", "25", "26", "27", "28", "48", "47", "46",
     "45", "44", "43", "42", "41", "31", "32", "33", "34", "35", "36", "37", "38"]

print dict((x, y) for x, y in zip(b, a) if y != '')

And you will get the output:

{'44': 'test1', '43': 'test'}

If you want to learn more about such python built-in function, you may refer to this official document.


问:
ChartJS only show me data when I zoom-in or zoom-out
actually I'm using ASP.NET with SQL Server. And I'm using ChartJS to do the Charts for my Website. The problem is that ChartJS only show me the results when I do zoom in or zoom out in the browser.

Anyone knows why?, I'm using AJAX to get information from the Database and do a dynamic Chart.

This is my JavaScript:

```<code>        $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "Graficas.asmx/obtenerGrafica",
            data: '',
            contentType: "application/json; charset=utf-8",
            dataType: "json", // dataType is json format
            success: function OnSuccess(response) {
                items = response.d;
                $.each(items, function (index, val) {
                    myChart.data.labels.push(val.Nombre);
                    myChart.data.datasets[0].data.push(val.Gastado);
                    nmbre.push(val.Nombre);
                    precio.push(val.Gastado);
                });
            },
            error: function onError(error) {
                console.log(error.d);
            },
        });
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'horizontalBar',
            data: {
                labels: [],
                datasets: [{
                    label: ['Mensual'],
                    data: [],
                    backgroundColor: [
                        'rgba(137, 107, 255, 0.3)'
                    ],
                    borderColor: [
                        'rgba(137, 107, 255, 1)',

                    ],
                    borderWidth: 1
                }
                ]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    });
</code>```

Thank u.

答:
I had his same exact issue, and the only way I was able to fix it was by adding the following just before closing the document.ready block:

```<code>setTimeout(function() {
    myChart.update();
},1000);
</code>```

It's less than ideal but that was the only thing I could do to consistently get the chart to render -- call the "update" method after a 1 second delay.

Body:
actually I'm using ASP.NET with SQL Server. And I'm using ChartJS to do the Charts for my Website. The problem is that ChartJS only show me the results when I do zoom in or zoom out in the browser.

Anyone knows why?, I'm using AJAX to get information from the Database and do a dynamic Chart.

This is my JavaScript:

        $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "Graficas.asmx/obtenerGrafica",
            data: '',
            contentType: "application/json; charset=utf-8",
            dataType: "json", // dataType is json format
            success: function OnSuccess(response) {
                items = response.d;
                $.each(items, function (index, val) {
                    myChart.data.labels.push(val.Nombre);
                    myChart.data.datasets[0].data.push(val.Gastado);
                    nmbre.push(val.Nombre);
                    precio.push(val.Gastado);
                });
            },
            error: function onError(error) {
                console.log(error.d);
            },
        });
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'horizontalBar',
            data: {
                labels: [],
                datasets: [{
                    label: ['Mensual'],
                    data: [],
                    backgroundColor: [
                        'rgba(137, 107, 255, 0.3)'
                    ],
                    borderColor: [
                        'rgba(137, 107, 255, 1)',

                    ],
                    borderWidth: 1
                }
                ]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    });

Thank u.

Body:
I had his same exact issue, and the only way I was able to fix it was by adding the following just before closing the document.ready block:

setTimeout(function() {
    myChart.update();
},1000);

It's less than ideal but that was the only thing I could do to consistently get the chart to render -- call the "update" method after a 1 second delay.


问:
Can I make popup screen or file upload automatically with selenium?
Good morning. I have a web page control with selenium. However, when I click the button of the site, a pop-up screen appears and I want to test that the file attachment is saved by pressing the file attachment button in it. Can you control selenium with two windows (parent, child-popup) going up and down?</p>

答:
I guess you want to interact with file upload dialog which is native window via selenium. That is not possible. However you can select file to upload using sendKeys without the dialog being opened.

Something like that

```<code>fileInput.sendKeys("/path/to/local/file");
</code>```

Body:
I guess you want to interact with file upload dialog which is native window via selenium. That is not possible. However you can select file to upload using sendKeys without the dialog being opened.

Something like that

fileInput.sendKeys("/path/to/local/file");


问:
Install Ruby 2.4.1 in windows within corporate proxy. MSYS2 update fails
I am using ruby installer rubyinstaller-2.4.1-2-x64.exe to install ruby 2.4.1 on windows 10. It is successful and at the end of install MSYS2 installation is triggered. It is also successful. But MSYS2 system update fails with the following error.

```<code>mingw32.sig      96.0   B  93.8K/s 00:00 [#######################################] 100%
error: mingw32: signature from "Alexey Pavlov (Alexpux) <alexpux@gmail.com>" is invalid
error: failed to update mingw32 (invalid or corrupted database (PGP signature))
</code>```

Any workaround to fix this?

Note: The same installation package works perfectly in my home network. So I guess it is something to do with the corporate firewall.

答:
I somehow made it work, by going through various SO answers. Following are the set of actions that made it work.

Set proxy in env variables

setx http_proxy="http://proxy.server.address:port"
 setx https_proxy="http://proxy.server.address:port"
 setx ftp_proxy="http://proxy.server.address:port"
 setx rsync_proxy="http://proxy.server.address:port"

Delete all files from C:\msys64\var\lib\pacman\sync

Open C:\msys64\mingw64.exe and run the command pacman -Syy

Since pacman is working now, I returned to the original ruby installer 2 process. It worked!

ridk install

1 - MSYS2 base installation - Completed Already
2 - MSYS2 system update -Successful now after proxy update
3 - MSYS2 and MINGW development toolchain -Successful now after proxy update

Body:
I am using ruby installer rubyinstaller-2.4.1-2-x64.exe to install ruby 2.4.1 on windows 10. It is successful and at the end of install MSYS2 installation is triggered. It is also successful. But MSYS2 system update fails with the following error.

mingw32.sig      96.0   B  93.8K/s 00:00 [#######################################] 100%
error: mingw32: signature from "Alexey Pavlov (Alexpux) <alexpux@gmail.com>" is invalid
error: failed to update mingw32 (invalid or corrupted database (PGP signature))

Any workaround to fix this?

Note: The same installation package works perfectly in my home network. So I guess it is something to do with the corporate firewall.


问:
Pass html defined in parent to child
I am trying to define some html in my parent component that can be passed to the child component. Is this possible? I have tried a couple of things like this: How to pass an expression to a component as an input in Angular2?, but I did not have any luck. Maybe my syntax was wrong. I was a little confused with the let.  Appreciate all the help and any explanations to help me understand this better.

```<code>@Component({
    selector: 'app-my-parent',
    template: `
    <div>other parent html</div>
    <app-my-child [property]="value">
        <ng-template #someTemplate">value.first</ng-template>
    </app-my-child>
    <app-my-child [property]="value">
        <ng-template #someTemplate">value.second</ng-template>
    </app-my-child>
    `
})
export class MyParent {
}
</code>```

```<code>@Component({
    selector: 'app-my-child',
    template: `
    <div>other child html</div>
    how do I access the template from here? Is there a way to do binding with templates?

})
export class MyChild {
      @Input() property;
}
</code>```

答:
As @bryan60 pointed out, the child template needs an <ng-content>. In the parent, everything you put within the child selector will be displayed at the ng-content location immediately before the AfterContentInit() lifecycle hook executes:

Parent component template:

```<code><child-cmp>
  <p>This will appear within ng-content of ChildComponent</p>
</child-cmp>
</code>```

Child component template:

```<code>  <h2>I am ChildComponent</h2>
  <ng-content></ng-content>
</code>```

Live demo

ContentLicense: CC BY-SA 4.0

Title: Pass html defined in parent to child

Body:
I am trying to define some html in my parent component that can be passed to the child component. Is this possible? I have tried a couple of things like this: How to pass an expression to a component as an input in Angular2?, but I did not have any luck. Maybe my syntax was wrong. I was a little confused with the let.  Appreciate all the help and any explanations to help me understand this better.

@Component({
    selector: 'app-my-parent',
    template: `

other parent html

    <app-my-child [property]="value">
        <ng-template #someTemplate">value.first</ng-template>
    </app-my-child>
    <app-my-child [property]="value">
        <ng-template #someTemplate">value.second</ng-template>
    </app-my-child>
    `
})
export class MyParent {
}

@Component({
    selector: 'app-my-child',
    template: `

other child html

    how do I access the template from here? Is there a way to do binding with templates?

})
export class MyChild {
      @Input() property;
}

Body:
As @bryan60 pointed out, the child template needs an <ng-content>. In the parent, everything you put within the child selector will be displayed at the ng-content location immediately before the AfterContentInit() lifecycle hook executes:

Parent component template:

<child-cmp>
  <p>This will appear within ng-content of ChildComponent</p>
</child-cmp>

Child component template:

  <h2>I am ChildComponent</h2>
  <ng-content></ng-content>

Live demo


问:
Call hierarchy of async functions inside a loop?
There's a async call I'm making that queries a database on a service, but this service has a limit of how many it can output at once, so I need to check if it hit its limit through the result it sends and repeat the query until it doesn't.

Synchronous mockup :

```<code>var query_results = [];

var limit_hit = true; #While this is true means that the query hit the record limit
var start_from = 0; #Pagination parameter

while (limit_hit) {
    Server.Query(params={start_from : start_from}, callback=function(result){
        limit_hit = result.limit_hit;
        start_from = result.results.length;
        query_result.push(result.results);
    }
}
</code>```

Obviously the above does not work, I've seen some other questions here about the issue, but they don't mention what to do when you need each iteration to wait for the last one to finish and you don't know before hand the number of iterations.

How can I turn the above asynchronous? I'm open to answers using promise/deferred-like logic, but preferably something clean.

I can probably think of a monstruous and horrible way of doing this using waits/timeouts, but there has to be a clean, clever and modern way to solve it.

Another way is to make a "pre-query" to know the number of features before hand so you know the number of loops, I'm not sure if this is the correct way.

Here we use Dojo sometimes, but the examples I found does not explain what to do when you have an unknown amount of loops https://www.sitepen.com/blog/2015/06/10/dojo-faq-how-can-i-sequence-asynchronous-operations/

答:
If you want to use a loop then I think there is no (clean) way to do it without Promises.

A different approach would be the following:

var query_results = [];

var start_from = 0;

funciton myCallback(result) {
  if(!result) {
    //first call
    Server.Query({ start_from: start_from}, myCallback);
  } else {
    //repeated call
    start_from = result.results.length
    query_result.push(result.results);

    if(!result.limit_hit) {
      //limit has not been hit yet
      //repeat the query with new start value
      Server.Query({ start_from: start_from}, myCallback);
    } else {
        //call some callback function here
    }
  }
}

myCallback(null);```

You could call this recursive, but since the Query is asynchronous you shouldn't have problems with call stack limits etc.

Using promises in an ES6 environment you could make use of async/await. Im not sure if this is possible with dojo.

Body:
There's a async call I'm making that queries a database on a service, but this service has a limit of how many it can output at once, so I need to check if it hit its limit through the result it sends and repeat the query until it doesn't.

Synchronous mockup :

var query_results = [];

var limit_hit = true; #While this is true means that the query hit the record limit
var start_from = 0; #Pagination parameter

while (limit_hit) {
    Server.Query(params={start_from : start_from}, callback=function(result){
        limit_hit = result.limit_hit;
        start_from = result.results.length;
        query_result.push(result.results);
    }
}

Obviously the above does not work, I've seen some other questions here about the issue, but they don't mention what to do when you need each iteration to wait for the last one to finish and you don't know before hand the number of iterations.

How can I turn the above asynchronous? I'm open to answers using promise/deferred-like logic, but preferably something clean.

I can probably think of a monstruous and horrible way of doing this using waits/timeouts, but there has to be a clean, clever and modern way to solve it.

Another way is to make a "pre-query" to know the number of features before hand so you know the number of loops, I'm not sure if this is the correct way.

Here we use Dojo sometimes, but the examples I found does not explain what to do when you have an unknown amount of loops https://www.sitepen.com/blog/2015/06/10/dojo-faq-how-can-i-sequence-asynchronous-operations/

Body:
If you want to use a loop then I think there is no (clean) way to do it without Promises.

A different approach would be the following:

var query_results = [];

var start_from = 0;

funciton myCallback(result) {
  if(!result) {
    //first call
    Server.Query({ start_from: start_from}, myCallback);
  } else {
    //repeated call
    start_from = result.results.length
    query_result.push(result.results);

    if(!result.limit_hit) {
      //limit has not been hit yet
      //repeat the query with new start value
      Server.Query({ start_from: start_from}, myCallback);
    } else {
        //call some callback function here
    }
  }
}

myCallback(null);

You could call this recursive, but since the Query is asynchronous you shouldn't have problems with call stack limits etc.

Using promises in an ES6 environment you could make use of async/await. Im not sure if this is possible with dojo.


问:
python rename field json with specific structure
i have a json with structure:

```<code>{
" features": [
{
  "geometry": {
    "type": "Polygon",
    "coordinates": []
  },
  "type": "Feature",
  "properties": {
    "ADMIN_LEVE": "REGION",
    "POPULTION": 4363916,
    "GEO_CENTER": "7.923209152686669, 45.06052300898206",
    "ID": "01",
    "NAME": "PIEMONTE"
  }
}

]
}
</code>```

and i need to rename the field "ADMIN_LEVE".
I have write a code using pandas to rename but doesn't work

```<code>df = pd.DataFrame(data)
df.rename(columns={'ADMIN_LEVE':'ADMIN_LEVEL'}, inplace=True)
</code>```

I can i do it?

i have also tryied with replace but doesn't work

```<code>json_data=open(path + ".json").read()
data = json.loads(json_data)
for d in data:
      d.replace('"ADMIN_LEVE"', '"ADMIN_LEVEL"')
</code>```

Thanks

答:
Source JSON (as string):

```<code>In [325]: print(s)

{
" features": [
{
  "geometry": {
    "type": "Polygon",
    "coordinates": []
  },
  "type": "Feature",
  "properties": {
    "ADMIN_LEVE": "REGION",
    "POPULTION": 4363916,
    "GEO_CENTER": "7.923209152686669, 45.06052300898206",
    "ID": "01",
    "NAME": "PIEMONTE"
  }
}

]
}
</code>```

Replaced:

```<code>In [327]: s = s.replace('"ADMIN_LEVE":', '"ADMIN_LEVEL":')

In [328]: print(s)

{
" features": [
{
  "geometry": {
    "type": "Polygon",
    "coordinates": []
  },
  "type": "Feature",
  "properties": {
    "ADMIN_LEVEL": "REGION",
    "POPULTION": 4363916,
    "GEO_CENTER": "7.923209152686669, 45.06052300898206",
    "ID": "01",
    "NAME": "PIEMONTE"
  }
}

]
}
</code>```

UPDATE: helper function:

```<code>def replace_in_json_file(filename, from_str, to_str):
    with open(filename) as f:
        data = f.read()
    with open(filename, 'w') as f:
        f.write(data.replace(from_str, to_str))
</code>```

Body:
i have a json with structure:

{
" features": [
{
  "geometry": {
    "type": "Polygon",
    "coordinates": []
  },
  "type": "Feature",
  "properties": {
    "ADMIN_LEVE": "REGION",
    "POPULTION": 4363916,
    "GEO_CENTER": "7.923209152686669, 45.06052300898206",
    "ID": "01",
    "NAME": "PIEMONTE"
  }
}

]
}

and i need to rename the field "ADMIN_LEVE".
I have write a code using pandas to rename but doesn't work

df = pd.DataFrame(data)
df.rename(columns={'ADMIN_LEVE':'ADMIN_LEVEL'}, inplace=True)

I can i do it?

i have also tryied with replace but doesn't work

json_data=open(path + ".json").read()
data = json.loads(json_data)
for d in data:
      d.replace('"ADMIN_LEVE"', '"ADMIN_LEVEL"')

Thanks

Body:
Source JSON (as string):

In [325]: print(s)

{
" features": [
{
  "geometry": {
    "type": "Polygon",
    "coordinates": []
  },
  "type": "Feature",
  "properties": {
    "ADMIN_LEVE": "REGION",
    "POPULTION": 4363916,
    "GEO_CENTER": "7.923209152686669, 45.06052300898206",
    "ID": "01",
    "NAME": "PIEMONTE"
  }
}

]
}

Replaced:

In [327]: s = s.replace('"ADMIN_LEVE":', '"ADMIN_LEVEL":')

In [328]: print(s)

{
" features": [
{
  "geometry": {
    "type": "Polygon",
    "coordinates": []
  },
  "type": "Feature",
  "properties": {
    "ADMIN_LEVEL": "REGION",
    "POPULTION": 4363916,
    "GEO_CENTER": "7.923209152686669, 45.06052300898206",
    "ID": "01",
    "NAME": "PIEMONTE"
  }
}

]
}

UPDATE: helper function:

def replace_in_json_file(filename, from_str, to_str):
    with open(filename) as f:
        data = f.read()
    with open(filename, 'w') as f:
        f.write(data.replace(from_str, to_str))


问:
Client Server communication over https using xml in android
This is the first time i am trying this. Can somebody pls share some bit of code which would help me doing this.

Any help would be appreciated.

Initial Attempt

hi,

I am trying to write code that will do client-server comm over https.

The code snippet(Mostly from different forums) for what i did is as under:

_FakeX509TrustManager.allowAllSSL();

The code for allowAllSSL() is

public static void allowAllSSL() { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

```<code>            public boolean verify(String hostname, SSLSession session) {
                // TODO Auto-generated method stub
                return false;
            }

    });

    SSLContext context = null;
    if (trustManagers == null) {
            trustManagers = new TrustManager[] { new _FakeX509TrustManager() };
    }

    try {
            context = SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
    } catch (KeyManagementException e) {
            e.printStackTrace();
    }

    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
</code>```

}

Also in the main activity the code after the above is:

HttpPost post = new HttpPost(new URI(eText.getText().toString())); post.setEntity(new StringEntity("test"));

```<code>            KeyStore trustStore = KeyStore.getInstance("JKS");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            InputStream trustStoreStream = getBaseContext().getResources().openRawResource(R.raw.mytruststore);
            trustStore.load(trustStoreStream, "test1234".toCharArray());
            trustManagerFactory.init(trustStore);

            // Setup keystore
            KeyStore keyStore = KeyStore.getInstance("JKS");
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            InputStream keyStoreStream = getBaseContext().getResources().openRawResource(R.raw.mykeystore);
            keyStore.load(keyStoreStream, "test1234".toCharArray());
            keyManagerFactory.init(keyStore, "test1234".toCharArray());

            SSLSocketFactory sslf = new SSLSocketFactory(keyStore);
            sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme ("https", sslf, 443));
            SingleClientConnManager cm = new
            SingleClientConnManager(post.getParams(), schemeRegistry);

            HttpClient client = new DefaultHttpClient(cm, post.getParams());
            HttpResponse result = client.execute(post);
</code>```

I have generated the JKS Keystore and Truststore files and kept it under /res/raw folder in my app.

The error which i get here is :

W/System.err( 358): java.security.KeyStoreException: KeyStore JKS implementation not found W/System.err( 358): at java.security.KeyStore.getInstance(KeyStore.java:134) W/System.err( 358): at com.msi.getwebpage.GetWebPage$2.onClick(GetWebPage.java:93) W/System.err( 358): at android.view.View.performClick(View.java:2408) W/System.err( 358): at android.view.View$PerformClick.run(View.java:8816) W/System.err( 358): at android.os.Handler.handleCallback(Handler.java:587) W/System.err( 358): at android.os.Handler.dispatchMessage(Handler.java:92) W/System.err( 358): at android.os.Looper.loop(Looper.java:123) W/System.err( 358): at android.app.ActivityThread.main(ActivityThread.java:4627) W/System.err( 358): at java.lang.reflect.Method.invokeNative(Native Method) W/System.err( 358): at java.lang.reflect.Method.invoke(Method.java:521) W/System.err( 358): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) W/System.err( 358): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) W/System.err( 358): at dalvik.system.NativeStart.main(Native Method)

Any idea why am i getting this error?

Also if i am trying to change the KeyStore instance to BKS i am getting the error as:

W/System.err( 387): java.io.IOException: Wrong version of key store. W/System.err( 387): at org.bouncycastle.jce.provider.JDKKeyStore.engineLoad(JDKKeyStore.java:839) W/System.err( 387): at java.security.KeyStore.load(KeyStore.java:676) W/System.err( 387): at com.msi.getwebpage.GetWebPage$2.onClick(GetWebPage.java:96) W/System.err( 387): at android.view.View.performClick(View.java:2408) W/System.err( 387): at android.view.View$PerformClick.run(View.java:8816) W/System.err( 387): at android.os.Handler.handleCallback(Handler.java:587) W/System.err( 387): at android.os.Handler.dispatchMessage(Handler.java:92) W/System.err( 387): at android.os.Looper.loop(Looper.java:123) W/System.err( 387): at android.app.ActivityThread.main(ActivityThread.java:4627) W/System.err( 387): at java.lang.reflect.Method.invokeNative(Native Method) W/System.err( 387): at java.lang.reflect.Method.invoke(Method.java:521) W/System.err( 387): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) W/System.err( 387): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) W/System.err( 387): at dalvik.system.NativeStart.main(Native Method)

This is probably because i have kept the jks keystore and truststore files under /res/raw folder in my app.(just a guess).

Please let me know how can i generate a BKS keystore and truststore file.

Or is their any other way that i can try to make this code snippet working. Thanks!!

答: The short answer is: Use keytool (from Java SDK) to export the certs from your jks keystore then import them to a new BKS keystore using bouncycastle security provider.</p>

Body:
This is the first time i am trying this. Can somebody pls share some bit of code which would help me doing this.

Any help would be appreciated.

Initial Attempt

hi,

I am trying to write code that will do client-server comm over https.

The code snippet(Mostly from different forums) for what i did is as under:

_FakeX509TrustManager.allowAllSSL();

The code for allowAllSSL() is

public static void allowAllSSL() { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                // TODO Auto-generated method stub
                return false;
            }

    });

    SSLContext context = null;
    if (trustManagers == null) {
            trustManagers = new TrustManager[] { new _FakeX509TrustManager() };
    }

    try {
            context = SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
    } catch (KeyManagementException e) {
            e.printStackTrace();
    }

    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

}

Also in the main activity the code after the above is:

HttpPost post = new HttpPost(new URI(eText.getText().toString())); post.setEntity(new StringEntity("test"));

            KeyStore trustStore = KeyStore.getInstance("JKS");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            InputStream trustStoreStream = getBaseContext().getResources().openRawResource(R.raw.mytruststore);
            trustStore.load(trustStoreStream, "test1234".toCharArray());
            trustManagerFactory.init(trustStore);

            // Setup keystore
            KeyStore keyStore = KeyStore.getInstance("JKS");
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            InputStream keyStoreStream = getBaseContext().getResources().openRawResource(R.raw.mykeystore);
            keyStore.load(keyStoreStream, "test1234".toCharArray());
            keyManagerFactory.init(keyStore, "test1234".toCharArray());

            SSLSocketFactory sslf = new SSLSocketFactory(keyStore);
            sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme ("https", sslf, 443));
            SingleClientConnManager cm = new
            SingleClientConnManager(post.getParams(), schemeRegistry);

            HttpClient client = new DefaultHttpClient(cm, post.getParams());
            HttpResponse result = client.execute(post);

I have generated the JKS Keystore and Truststore files and kept it under /res/raw folder in my app.

The error which i get here is :

W/System.err( 358): java.security.KeyStoreException: KeyStore JKS implementation not found W/System.err( 358): at java.security.KeyStore.getInstance(KeyStore.java:134) W/System.err( 358): at com.msi.getwebpage.GetWebPage$2.onClick(GetWebPage.java:93) W/System.err( 358): at android.view.View.performClick(View.java:2408) W/System.err( 358): at android.view.View$PerformClick.run(View.java:8816) W/System.err( 358): at android.os.Handler.handleCallback(Handler.java:587) W/System.err( 358): at android.os.Handler.dispatchMessage(Handler.java:92) W/System.err( 358): at android.os.Looper.loop(Looper.java:123) W/System.err( 358): at android.app.ActivityThread.main(ActivityThread.java:4627) W/System.err( 358): at java.lang.reflect.Method.invokeNative(Native Method) W/System.err( 358): at java.lang.reflect.Method.invoke(Method.java:521) W/System.err( 358): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) W/System.err( 358): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) W/System.err( 358): at dalvik.system.NativeStart.main(Native Method)

Any idea why am i getting this error?

Also if i am trying to change the KeyStore instance to BKS i am getting the error as:

W/System.err( 387): java.io.IOException: Wrong version of key store. W/System.err( 387): at org.bouncycastle.jce.provider.JDKKeyStore.engineLoad(JDKKeyStore.java:839) W/System.err( 387): at java.security.KeyStore.load(KeyStore.java:676) W/System.err( 387): at com.msi.getwebpage.GetWebPage$2.onClick(GetWebPage.java:96) W/System.err( 387): at android.view.View.performClick(View.java:2408) W/System.err( 387): at android.view.View$PerformClick.run(View.java:8816) W/System.err( 387): at android.os.Handler.handleCallback(Handler.java:587) W/System.err( 387): at android.os.Handler.dispatchMessage(Handler.java:92) W/System.err( 387): at android.os.Looper.loop(Looper.java:123) W/System.err( 387): at android.app.ActivityThread.main(ActivityThread.java:4627) W/System.err( 387): at java.lang.reflect.Method.invokeNative(Native Method) W/System.err( 387): at java.lang.reflect.Method.invoke(Method.java:521) W/System.err( 387): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) W/System.err( 387): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) W/System.err( 387): at dalvik.system.NativeStart.main(Native Method)

This is probably because i have kept the jks keystore and truststore files under /res/raw folder in my app.(just a guess).

Please let me know how can i generate a BKS keystore and truststore file.

Or is their any other way that i can try to make this code snippet working. Thanks!!


问:
Swift 4 - How to enable / disable keyboard by using buttons
My tricky problem is :

I've 2 buttons with 2 UITextView.
Like you know, when I push an UITextView, keyboard appear. Well, this is not what I want.

I want to enable / disable the display's keyboard according a specific @IBAction taped.

The scenario is the following:
- First button (Keyboard icon) allow the user to display the keyboard to type something in one of the UITextView, with a FirstResponder init on the top one.

Second button (REC icon) allow the user to speak and display in pre-selected TextView but without displaying keyboard.

I already known that there is :

isUserInteractionEnabled

and

textViewDidBeginEditing

But it doesn't really fit well and/or fix my issue.

Here a screen to be more explicit (don't give a mind about the third green validate button, it's just for the .POST feature) :

Thanks for any help!

答:
function to dismiss KeyBoard when button is clicked:

```<code>@IBAction func hideKeyboard() {
     textView.resignFirstResponder()
 }
</code>```

function to get keyboard to show up:

```<code> @IBAction func showKeyboard() {
     textView.becomeFirstResponder()
 }
</code>```

Body:
function to dismiss KeyBoard when button is clicked:

@IBAction func hideKeyboard() {
     textView.resignFirstResponder()
 }

function to get keyboard to show up:

 @IBAction func showKeyboard() {
     textView.becomeFirstResponder()
 }


问:
Sequential list with pairs of the same prefix
I have the simplest possible code for creating string with integer:

```<code>x = []
for i in range(6):
    x.append('a' + str(i))
</code>```

,witch creating that output:

```<code>['a0', 'a1', 'a2', 'a3', 'a4', 'a5']
</code>```

But how could the condition to create a list in this form look like:

```<code> ['a0', 'a0', 'a1', 'a1', 'a2', 'a2']
</code>```

I tried this way:

```<code>x = []
for i in range(6):
   if i%2==0:
       x.append('a' + str(i))
   else:
       x.append('a' + str(i-1))
</code>```

But this ['a0', 'a0', 'a2', 'a2', 'a4', 'a4'] is far from what I need.

答:
Duplicating code as described in other answers works well.

Other interesting options include:

```<code>x = []
for i in range(6 * 2):
    x.append('a' + str(i // 2))

# list comprehension, expect better performance with this
x = ['a' + str(i//2) for i in range(6 * 2)]

# if you have numpy
import numpy as np
temp = ['a' + str(i) for i in range(6)]
x = np.array(temp).repeat(2)
</code>```

Body:
I have the simplest possible code for creating string with integer:

x = []
for i in range(6):
    x.append('a' + str(i))

,witch creating that output:

['a0', 'a1', 'a2', 'a3', 'a4', 'a5']

But how could the condition to create a list in this form look like:

 ['a0', 'a0', 'a1', 'a1', 'a2', 'a2']

I tried this way:

x = []
for i in range(6):
   if i%2==0:
       x.append('a' + str(i))
   else:
       x.append('a' + str(i-1))

But this ['a0', 'a0', 'a2', 'a2', 'a4', 'a4'] is far from what I need.

Body:
Duplicating code as described in other answers works well.

Other interesting options include:

x = []
for i in range(6 * 2):
    x.append('a' + str(i // 2))

# list comprehension, expect better performance with this
x = ['a' + str(i//2) for i in range(6 * 2)]

# if you have numpy
import numpy as np
temp = ['a' + str(i) for i in range(6)]
x = np.array(temp).repeat(2)


问:
How many levels of inheritance
Are there any best practices regarding the maximum depth of the inheritance hierarchy for a framework and guidelines when to use multiple levels of inheritance or join them in a single class?

Some references to established practices/examples that worked well in the Java world would be nice in the answers as this is from the perspective of the community and frameworks surrounding Java.

答:
General rule is the deeper the hierarchy the more difficult it might be to understand where particular methods and fields are defined or/and redefined.

But beside the inheritance there are other factors that you need to be careful to keep your code complexity manageable.

The best approach is to use a code metrics tool and try to balance between different factors(lines of code, class decoupling and ...)

Title: How many levels of inheritance


问:
WHERE clause date is greater than 24h - Carbon / Laravel
I Am making a query where I need to find all the results for reminder that are greater than 24h in that database.

My query looks like this but its wrong I believe

```<code>$reminder = Reminder::where('reminder_date','<', Carbon::now()->addHours(24))
                          ->get();
</code>```

Using Laravel / Carbon

答:
It looks like you might be using the wrong operator. < (Less than) should be swapped for > (Greater than):

```<code>$reminder = Reminder::where('reminder_date','>', Carbon::now()->addHours(24))
                      ->get();
</code>```

Body:
I Am making a query where I need to find all the results for reminder that are greater than 24h in that database.

My query looks like this but its wrong I believe

$reminder = Reminder::where('reminder_date','<', Carbon::now()->addHours(24))
                          ->get();

Using Laravel / Carbon

Body:
It looks like you might be using the wrong operator. < (Less than) should be swapped for > (Greater than):

$reminder = Reminder::where('reminder_date','>', Carbon::now()->addHours(24))
                      ->get();


问:
R plumber api deployment on digital ocean with swagger
I am using plumber to deploy an R api to digital ocean. It's hard to provide a reproducible example here but what I want is for the swagger endpoint to compile and be available. It works locally but not on the digital ocean server.

Locally I do this:

```<code>library(plumber)
r <- plumb("api/plumber.R")
r$run(port=8000)
</code>```

now the swagger docs are available at: http://127.0.0.1:8000/__swagger__/

When I deploy to the server as follows:

```<code>library(analogsea)
library(plumber)
my_droplet <- as.droplet("my_droplet")

do_deploy_api(
  droplet = my_droplet,
  path = "my_path",
  localPath = "my_local_path",
  port = 8000
)

do_forward(my_droplet, "my_path")
</code>```

Now I go to [my_remote_ip]/my_path/__swagger__/ I get a 404.

Anyone know how to do this?
Much appreciated.

答:
I found a work around thanks to the conversation here. After do_deploy_api() and do_forward() i then do this:

```<code>droplet_execute([my_droplet], {
  system("sed -i 's/pr$run(port=8000)/pr$run(port=8000, swagger = TRUE)/g' /etc/systemd/system/plumber-[my_api].service", intern = TRUE)
  system("systemctl daemon-reload", intern = TRUE)
  system("service plumber-[my_api] restart", intern = TRUE)
})
</code>```

Body:
I am using plumber to deploy an R api to digital ocean. It's hard to provide a reproducible example here but what I want is for the swagger endpoint to compile and be available. It works locally but not on the digital ocean server.

Locally I do this:

library(plumber)
r <- plumb("api/plumber.R")
r$run(port=8000)

now the swagger docs are available at: http://127.0.0.1:8000/__swagger__/

When I deploy to the server as follows:

library(analogsea)
library(plumber)
my_droplet <- as.droplet("my_droplet")

do_deploy_api(
  droplet = my_droplet,
  path = "my_path",
  localPath = "my_local_path",
  port = 8000
)

do_forward(my_droplet, "my_path")

Now I go to [my_remote_ip]/my_path/__swagger__/ I get a 404.

Anyone know how to do this?
Much appreciated.

Body:
I found a work around thanks to the conversation here. After do_deploy_api() and do_forward() i then do this:

droplet_execute([my_droplet], {
  system("sed -i 's/pr$run(port=8000)/pr$run(port=8000, swagger = TRUE)/g' /etc/systemd/system/plumber-[my_api].service", intern = TRUE)
  system("systemctl daemon-reload", intern = TRUE)
  system("service plumber-[my_api] restart", intern = TRUE)
})


问:
Are there platforms where the size of shorts is actually larger than 16bits
As far as I know the standard says that the size of the short type must be at least 16 bits.

Now I'm wondering if there are actually platforms where shorts are 32 bit or even larger.

I'm aware of stddef.h and that the types defined there should be used if a certain size is required.

答: Yes. You can find an example here (well, not 32 bit, but "larger than 16"). The example given there is the UNICOS operating system for "Cray" supercomputers, which has 64bit short.


问:
why dataTable is not acting if a new row with header is added
I am able to create dataTable  successfully

Here is Demo:https://jsfiddle.net/w2nevcca/3/

The problem occurs when i add

```<code>        <tr>
            <th class="widthind">14/11/2017</th>
        </tr>
                 <!-- added as date divider -->
</code>```

When i add above code as divider to show my date

Here is 2nd Demo(Not Working):https://jsfiddle.net/pkxmnh2a/12/

below is my code

HTML:

```<code><div class="table-content table-responsive">
    <table id="examples" class="display tvalues" cellspacing="0" width="100%" name="tabel">
        <thead>
            <tr>
                <!--th>ID</th-->
                <th>User Id</th>
                <th>User Name</th>
                <th>Project Name</th>
                <th>Work Description</th>
                <!--<th>Reported On</th>-->
            </tr>
        </thead>
        <tfoot>
            <tr>
                <!--th>ID</th-->
                <th>User Id</th>
                <th>User Name</th>
                <th>Project Name</th>
                <th>Work Description</th>
                <!-- <th>Reported On</th>-->
            </tr>
        </tfoot>
        <tbody>
            <tr>
                <th class="widthind">14/11/2017</th>
            </tr>
            <tr>
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>today's day report</td>
                <td>
                    <p>this my first day report employeee 2222</p>
                </td>
            </tr>
            <tr>
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>today's day report</td>
                <td>
                    <p>this my first day report employeee 33333</p>
                </td>
            </tr>
            <tr>
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>today's day report</td>
                <td>
                    <p>this my first day report employeee 44444</p>
                </td>
            </tr>
            <tr>
                <th class="widthind">13/11/2017</th>
            </tr>
            <tr>
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>yesterday report</td>
                <td>
                    <p>this my yesterday day report employeee 2222</p>
                </td>
            </tr>
            <tr>
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>yesterday report</td>
                <td>
                    <p>this my yesterday day report employeee 33333</p>
                </td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

below is my javascript code

JS:

```<code>$(document).ready(function () {
        var table = $('#examples').DataTable();
        $('a.toggle-vis').on('click', function (e) {
            e.preventDefault();

            var column = table.column($(this).attr('data-column'));
            column.visible(!column.visible());
        });

        $('#examples tfoot th').each(function () {
            var title = $('#examples thead th').eq($(this).index()).text();
            $(this).html('<input tyepe="text" placeholder="Search ' + title + '"/>');
        });
        table.columns().eq(0).each(function (colIdx) {
            $('input', table.column(colIdx).footer()).on('keyup change', function () {
                table
                        .column(colIdx)
                        .search(this.value)
                        .draw();
            });
        });
    });
</code>```

The above code works perfectly when i don't add divider to dive the date

when i add the divider the above code doesn't  work.

Please help me thanks in advance !!!!

答:
If you look into the console of your browser's developer tools (open up by hitting F12 on your keyboard), you can see that there's a JavaScript error. This is in fact what's preventing DataTables from rendering.

The reason for this error is that DataTables isn't prepared to encounter such a row - it expects all rows to hold data in the same format (and the same amount of columns).

While you can get rid of the error by inserting three empty  cells to the header row (colspan won't work here) and thus get DataTable to render (see https://jsfiddle.net/n34vbnmd/1) - how is DataTables supposed to know how to handle those rows when sorting?

A better solution would be to insert those rows dynamically after each rendering. You'll need to group the rows that should have a common header line, for example with a custom data-attribute. Then you can use the fnDrawCallback callback via DataTable's options in order to generate those header rows whenever the DataTable has been redrawn.

You might also want to look into the official docs for "row grouping":
https://datatables.net/examples/advanced_init/row_grouping.html - I just found this, but it's essentially doing the same as my example. Mind that I haven't tested my example thoroughly with multiple pages etc., where the code provided in the docs seems to handle this better!

$(document).ready(function () {
    var table = $('#examples').DataTable({
        "fnDrawCallback": function() {
          var currentGroup = null;
          $(this).find('tbody tr').each(function() {
            var thisRow = $(this),
                rowGroup = thisRow.attr('data-group');
            if (rowGroup != currentGroup) {
                currentGroup = rowGroup;
                thisRow.before('
' + rowGroup + '
');
            }
          });
        }
    });

    $('a.toggle-vis').on('click', function (e) {
        e.preventDefault();

        var column = table.column($(this).attr('data-column'));
        column.visible(!column.visible());
    });

    $('#examples tfoot th').each(function () {
        var title = $('#examples thead th').eq($(this).index()).text();
        $(this).html('<input tyepe="text" placeholder="Search ' + title + '"/>');
    });

    table.columns().eq(0).each(function (colIdx) {
        $('input', table.column(colIdx).footer()).on('keyup change', function () {
            table
                .column(colIdx)
                .search(this.value)
                .draw();
        });
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.widthind th {
  background-color: black;
  color: white;
  text-align: left;
}</code>```

<link href="https://cdn.datatables.net/1.10.0/css/jquery.dataTables.css" rel="stylesheet"/>

                User Id
                User Name
                Project Name
                Work Description

                User Id
                User Name
                Project Name
                Work Description

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                today's day report

this my first day report employeee 2222

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                today's day report

this my first day report employeee 33333

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                today's day report

this my first day report employeee 44444

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                yesterday report

this my yesterday day report employeee 2222

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                yesterday report

this my yesterday day report employeee 33333

```

Body:
I am able to create dataTable  successfully

Here is Demo:https://jsfiddle.net/w2nevcca/3/

The problem occurs when i add

            14/11/2017

When i add above code as divider to show my date

Here is 2nd Demo(Not Working):https://jsfiddle.net/pkxmnh2a/12/

below is my code

HTML:

                User Id
                User Name
                Project Name
                Work Description

                User Id
                User Name
                Project Name
                Work Description

                14/11/2017

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                today's day report

this my first day report employeee 2222

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                today's day report

this my first day report employeee 33333

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                today's day report

this my first day report employeee 44444

                13/11/2017

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                yesterday report

this my yesterday day report employeee 2222

                9cbc6e5a99bf96a61e5fa0445315286f
                arjun
                yesterday report

this my yesterday day report employeee 33333

below is my javascript code

JS:

$(document).ready(function () {
        var table = $('#examples').DataTable();
        $('a.toggle-vis').on('click', function (e) {
            e.preventDefault();

            var column = table.column($(this).attr('data-column'));
            column.visible(!column.visible());
        });

        $('#examples tfoot th').each(function () {
            var title = $('#examples thead th').eq($(this).index()).text();
            $(this).html('<input tyepe="text" placeholder="Search ' + title + '"/>');
        });
        table.columns().eq(0).each(function (colIdx) {
            $('input', table.column(colIdx).footer()).on('keyup change', function () {
                table
                        .column(colIdx)
                        .search(this.value)
                        .draw();
            });
        });
    });

The above code works perfectly when i don't add divider to dive the date

when i add the divider the above code doesn't  work.

Please help me thanks in advance !!!!

Body:
If you look into the console of your browser's developer tools (open up by hitting F12 on your keyboard), you can see that there's a JavaScript error. This is in fact what's preventing DataTables from rendering.

The reason for this error is that DataTables isn't prepared to encounter such a row - it expects all rows to hold data in the same format (and the same amount of columns).

While you can get rid of the error by inserting three empty <th> cells to the header row (colspan won't work here) and thus get DataTable to render (see https://jsfiddle.net/n34vbnmd/1) - how is DataTables supposed to know how to handle those rows when sorting?

A better solution would be to insert those rows dynamically after each rendering. You'll need to group the rows that should have a common header line, for example with a custom data-attribute. Then you can use the fnDrawCallback callback via DataTable's options in order to generate those header rows whenever the DataTable has been redrawn.

You might also want to look into the official docs for "row grouping":
https://datatables.net/examples/advanced_init/row_grouping.html - I just found this, but it's essentially doing the same as my example. Mind that I haven't tested my example thoroughly with multiple pages etc., where the code provided in the docs seems to handle this better!

$(document).ready(function () {
    var table = $('#examples').DataTable({
        "fnDrawCallback": function() {
          var currentGroup = null;
          $(this).find('tbody tr').each(function() {
            var thisRow = $(this),
                rowGroup = thisRow.attr('data-group');
            if (rowGroup != currentGroup) {
                currentGroup = rowGroup;
                thisRow.before('<tr class="widthind"><th colspan="4">' + rowGroup + '</th></tr>');
            }
          });
        }
    });

    $('a.toggle-vis').on('click', function (e) {
        e.preventDefault();

        var column = table.column($(this).attr('data-column'));
        column.visible(!column.visible());
    });

    $('#examples tfoot th').each(function () {
        var title = $('#examples thead th').eq($(this).index()).text();
        $(this).html('<input tyepe="text" placeholder="Search ' + title + '"/>');
    });

    table.columns().eq(0).each(function (colIdx) {
        $('input', table.column(colIdx).footer()).on('keyup change', function () {
            table
                .column(colIdx)
                .search(this.value)
                .draw();
        });
    });
});

.widthind th {
  background-color: black;
  color: white;
  text-align: left;
}

<link href="https://cdn.datatables.net/1.10.0/css/jquery.dataTables.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.js"></script>
<div class="table-content table-responsive">
    <table id="examples" class="display tvalues" cellspacing="0" width="100%" name="tabel">
        <thead>
            <tr>
                <!--th>ID</th-->
                <th>User Id</th>
                <th>User Name</th>
                <th>Project Name</th>
                <th>Work Description</th>
                <!--<th>Reported On</th>-->
            </tr>
        </thead>
        <tfoot>
            <tr>
                <!--th>ID</th-->
                <th>User Id</th>
                <th>User Name</th>
                <th>Project Name</th>
                <th>Work Description</th>
                <!-- <th>Reported On</th>-->
            </tr>
        </tfoot>
        <tbody>
            <tr data-group="14/11/2017">
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>today's day report</td>
                <td>
                    <p>this my first day report employeee 2222</p>
                </td>
            </tr>
            <tr data-group="14/11/2017">
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>today's day report</td>
                <td>
                    <p>this my first day report employeee 33333</p>
                </td>
            </tr>
            <tr data-group="14/11/2017">
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>today's day report</td>
                <td>
                    <p>this my first day report employeee 44444</p>
                </td>
            </tr>

            <tr data-group="13/11/2017">
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>yesterday report</td>
                <td>
                    <p>this my yesterday day report employeee 2222</p>
                </td>
            </tr>
            <tr data-group="13/11/2017">
                <td>9cbc6e5a99bf96a61e5fa0445315286f</td>
                <td>arjun</td>
                <td>yesterday report</td>
                <td>
                    <p>this my yesterday day report employeee 33333</p>
                </td>
            </tr>
        </tbody>
    </table>
</div>


问:
How to remove the default charset in HttpClient Request Header C#
I am trying to hit an API from C# code. I am unable to get the response and receiving the status code "500 - Internal Server error".

Found the reason that the "Charset-UTF8" is getting appended in the request header

When i tried to hit the API in Fiddler without "Charset-UTF8", I am able to get the response in Fiddler and postman. With the "Charset-UTF8" i get the same 500 internal server error. The content type is application/json.

I even tried each and every charaset encoding methods  UTF-8,16,32, unicode and default format from C# code, gives the same error.

Please let me know how to remove the CharSet(appending) from the API request Header.

please go through code i have attached

```<code>HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("i have third party url");
client1.DefaultRequestHeaders
    .Accept
    .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
        client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Basic",
            Convert.ToBase64String(
                System.Text.ASCIIEncoding.ASCII.GetBytes(
                    string.Format("{0}:{1}", userName, password))));

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, client1.BaseAddress);

StringContent content = new StringContent(JsonConvert.SerializeObject("working request"));

request.Content = content;

client1.SendAsync(request)
    .ContinueWith(responseTask =>
    {
        Console.WriteLine("Response: {0}", responseTask.Result);
    });
</code>```

答:
Try the solution below

```<code>content.Headers.Remove("Content-Type"); // "{application/json; charset=utf-8}"
content.Headers.Add("Content-Type", "application/json");
</code>```

or

```<code>content.Headers.ContentType.CharSet = string.Empty;
</code>```

I have submitted an issue on dotnet/corefx repo.

Check it out https://github.com/dotnet/corefx/issues/25290

Tested on .NET Core 2.0, .NET Standard 2.0

Body:
I am trying to hit an API from C# code. I am unable to get the response and receiving the status code "500 - Internal Server error".

Found the reason that the "Charset-UTF8" is getting appended in the request header

When i tried to hit the API in Fiddler without "Charset-UTF8", I am able to get the response in Fiddler and postman. With the "Charset-UTF8" i get the same 500 internal server error. The content type is application/json.

I even tried each and every charaset encoding methods  UTF-8,16,32, unicode and default format from C# code, gives the same error.

Please let me know how to remove the CharSet(appending) from the API request Header.

please go through code i have attached

HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("i have third party url");
client1.DefaultRequestHeaders
    .Accept
    .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
        client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Basic",
            Convert.ToBase64String(
                System.Text.ASCIIEncoding.ASCII.GetBytes(
                    string.Format("{0}:{1}", userName, password))));

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, client1.BaseAddress);

StringContent content = new StringContent(JsonConvert.SerializeObject("working request"));

request.Content = content;

client1.SendAsync(request)
    .ContinueWith(responseTask =>
    {
        Console.WriteLine("Response: {0}", responseTask.Result);
    });

Body:
Try the solution below

content.Headers.Remove("Content-Type"); // "{application/json; charset=utf-8}"
content.Headers.Add("Content-Type", "application/json");

or

content.Headers.ContentType.CharSet = string.Empty;

I have submitted an issue on dotnet/corefx repo.

Check it out https://github.com/dotnet/corefx/issues/25290

Tested on .NET Core 2.0, .NET Standard 2.0


答:
From what I've seen (note: this isn't an official opinion, just my observations), 3-4 is a reasonable maximum.

Also, remember one important part from Effective Java:

Favor composition over inheritance

Title: How many levels of inheritance

Body:
Are there any best practices regarding the maximum depth of the inheritance hierarchy for a framework and guidelines when to use multiple levels of inheritance or join them in a single class?

Some references to established practices/examples that worked well in the Java world would be nice in the answers as this is from the perspective of the community and frameworks surrounding Java.


问:
Count the selected Item in CheckboxTreeViewer
I have an issue when using CheckBoxTreeViewer.
When I checked the child items, I want to show the count number of them in a label.
Please help me!</p>

答:
Assuming this is the Eclipse JFace CheckboxTreeViewer.

Add a check state listener to the viewer using the addCheckStateListener method.

In the checkStateChanged  method of the listener you can get the number of checked items and update your label.

Use the viewer getCheckedElements method of the viewer to get the number of checked elements:

```<code>Object [] elements = viewer.getCheckedElement();

int cout = elements.length;
</code>```

Body:
Assuming this is the Eclipse JFace CheckboxTreeViewer.

Add a check state listener to the viewer using the addCheckStateListener method.

In the checkStateChanged  method of the listener you can get the number of checked items and update your label.

Use the viewer getCheckedElements method of the viewer to get the number of checked elements:

Object [] elements = viewer.getCheckedElement();

int cout = elements.length;


问:
Sharing Files in SVN
I am in the process of moving from VSS to SVN and I'm not sure how to share files in SVN.

Basically we have the following structure in VSS

```<code>$MOSS
  - Components
    - ComponentA
      - bin
    - ComponentB
      - bin
  - GAC Mirror
</code>```

GAC Mirror holds a shared copy of all the Dlls from the bin folders of the components to allow for easy copying to the GAC.

In VSS all you do is drag the Dll from the bin folder to the GAC Mirror folder and it works it's life out.

How would I do this in SVN?

Thanks in advance.

答:
Use SVN 1.6+, it supports files also, see:
http://svnbook.red-bean.com/nightly/en/svn-book.html#svn.advanced.externals</p>

OwnerDisplayName: Arry

Title: Sharing Files in SVN

Body:
I am in the process of moving from VSS to SVN and I'm not sure how to share files in SVN.

Basically we have the following structure in VSS

$MOSS
  - Components
    - ComponentA
      - bin
    - ComponentB
      - bin
  - GAC Mirror

GAC Mirror holds a shared copy of all the Dlls from the bin folders of the components to allow for easy copying to the GAC.

In VSS all you do is drag the Dll from the bin folder to the GAC Mirror folder and it works it's life out.

How would I do this in SVN?

Thanks in advance.


问:
Knitr preamble error results in "pandoc document conversion failed with error 43"
Rstudio Version 0.99.441; Windows 7 enterprise; knitr 1.10.5; MiKTex 0.4.5 r.1280 (2.9 64-bit)

I have a an error on my office computer when trying to knit PDF's in Rstudio, there are no problems knitting to HTML or word. The problem may be related to updates because knitting used to work fine and my home computer can knit to pdf without issue, however I took my computer home to update and the problem is still there.

My error message was as follows
"pandoc.exe: Error producing PDF from TeX source
Error: pandoc document conversion failed with error 43"

I created a new file using the template example in Rstudio attempted to knit, then inspected the TEX output. I traced the error to the last paragraph of the preamble.

```<code>\setlength{\droptitle}{-2em}
 \title{Untitled}
 \pretitle{\vspace{\droptitle}\centering\huge}
 \posttitle{\par}
 \author{user name}
 \preauthor{\centering\large\emph}
 \postauthor{\par}
 \predate{\centering\large\emph}
 \postdate{\par}
 \date{\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{14}
\itemsep1pt\parskip0pt\parsep0pt
\item
  juni 2015
\end{enumerate}}
</code>```

by removing the last 7 lines to do with enumerate and the date then running the TEX code the document prints as a PDF. Why is this happening and what can I do about it so the document knits at first click from Rstudio?

答:
My screw-up that resulted in this error was forgetting to put dollar signs around some inline latex code. I did

```<code>\theta
</code>```

Instead of

```<code>$\theta$
</code>```

Body:
Rstudio Version 0.99.441; Windows 7 enterprise; knitr 1.10.5; MiKTex 0.4.5 r.1280 (2.9 64-bit)

I have a an error on my office computer when trying to knit PDF's in Rstudio, there are no problems knitting to HTML or word. The problem may be related to updates because knitting used to work fine and my home computer can knit to pdf without issue, however I took my computer home to update and the problem is still there.

My error message was as follows
"pandoc.exe: Error producing PDF from TeX source
Error: pandoc document conversion failed with error 43"

I created a new file using the template example in Rstudio attempted to knit, then inspected the TEX output. I traced the error to the last paragraph of the preamble.

\setlength{\droptitle}{-2em}
 \title{Untitled}
 \pretitle{\vspace{\droptitle}\centering\huge}
 \posttitle{\par}
 \author{user name}
 \preauthor{\centering\large\emph}
 \postauthor{\par}
 \predate{\centering\large\emph}
 \postdate{\par}
 \date{\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{14}
\itemsep1pt\parskip0pt\parsep0pt
\item
  juni 2015
\end{enumerate}}

by removing the last 7 lines to do with enumerate and the date then running the TEX code the document prints as a PDF. Why is this happening and what can I do about it so the document knits at first click from Rstudio?

Body:
My screw-up that resulted in this error was forgetting to put dollar signs around some inline latex code. I did

\theta

Instead of

$\theta$


问:
how to merge a collection of Maps using streams
I have a collection of maps:

```<code>Collection<Map<String,Double>> myCol = table.values();
</code>```

I would like to transform this into a Map

```<code>Map<String, Double>
</code>```

such that, for a matching key, values are summed up. Using a for loop, it is rather simple:

```<code>Map<String, Double> outMap = new HashMap<>();
for (Map<String, Double> map : myCol) {
    outMap =  mergeMaps(outMap, map);
}
</code>```

and mergeMaps() is defined as

```<code>mergeMaps(Map<String, Double> m1, Map<String, Double> m2){
    Map<String, Double> outMap = new TreeMap<>(m1);
    m2.forEach((k,v) -> outMap.merge(k,v,Double::sum)); /*sum values if key exists*/
    return outMap;
}
</code>```

However, I would like to use streams to get a map from collection. I have tried as follows:

```<code>Map<String, Double> outMap = new HashMap<>();
myCol.stream().forEach(e-> outMap.putAll(mergeMaps(outMap,e)));
return outMap;
</code>```

This works without a problem. However, can I still improve it? I mean, how can I use collectors in it?

答:
With streams:

```<code>Map<String, Double> outMap = myCol.stream()
    .flatMap(map -> map.entrySet().stream())
    .collect(Collectors.toMap(
        Map.Entry::getKey,   // key of the result map
        Map.Entry::getValue, // value of the result map
        Double::sum,         // how to merge values for equal keys
        TreeMap::new));      // the type of map to be created
</code>```

This uses Collectors.toMap to create the result TreeMap.

You can do it without streams, though. I think your version is a little bit complicated, you could refactor it as follows:

```<code>Map<String, Double> outMap = TreeMap<>();
myCol.forEach(map -> map.forEach((k, v) -> outMap.merge(k, v, Double::sum)));
</code>```

Which is shorter, easy and most readable.

Body:
I have a collection of maps:

Collection<Map<String,Double>> myCol = table.values();

I would like to transform this into a Map

Map<String, Double>

such that, for a matching key, values are summed up. Using a for loop, it is rather simple:

Map<String, Double> outMap = new HashMap<>();
for (Map<String, Double> map : myCol) {
    outMap =  mergeMaps(outMap, map);
}

and mergeMaps() is defined as

mergeMaps(Map<String, Double> m1, Map<String, Double> m2){
    Map<String, Double> outMap = new TreeMap<>(m1);
    m2.forEach((k,v) -> outMap.merge(k,v,Double::sum)); /*sum values if key exists*/
    return outMap;
}

However, I would like to use streams to get a map from collection. I have tried as follows:

Map<String, Double> outMap = new HashMap<>();
myCol.stream().forEach(e-> outMap.putAll(mergeMaps(outMap,e)));
return outMap;

This works without a problem. However, can I still improve it? I mean, how can I use collectors in it?

Body:
With streams:

Map<String, Double> outMap = myCol.stream()
    .flatMap(map -> map.entrySet().stream())
    .collect(Collectors.toMap(
        Map.Entry::getKey,   // key of the result map
        Map.Entry::getValue, // value of the result map
        Double::sum,         // how to merge values for equal keys
        TreeMap::new));      // the type of map to be created

This uses Collectors.toMap to create the result TreeMap.

You can do it without streams, though. I think your version is a little bit complicated, you could refactor it as follows:

Map<String, Double> outMap = TreeMap<>();
myCol.forEach(map -> map.forEach((k, v) -> outMap.merge(k, v, Double::sum)));

Which is shorter, easy and most readable.


问:
Any simple php lib to auth with Google, FB, Twitter
Is there something like Hybridauth3, Loginza, or uLogin (but not those as I understand they are not supported by the teams anymore)? Hybridauth is too complex for me for simple auth.</p>

答:
As long as you know how to use code libraries (packages) here is one that is rather popular: https://github.com/laravel/socialite

This one deals with just about any OAuth2 services: https://packagist.org/packages/league/oauth2-client

And here we have a list of SSO packages provided via the composer package manager:  https://packagist.org/?q=sso&p=0

Hope this helps you out.


问:
Eigen matrix ros/cols not working out right
I can't get this to compile:

```<code>Eigen::Map<Eigen::Matrix<const T, EA::ColsAtCompileTime, 1>> x(vec);
auto result = a_ * x - b_; // a(60r,1200c) * x(1200r,1c) - b(60r,1c)
</code>```

The two errors (about 1000 lines each) eventually conclude that the * and - operators can't be "overloaded" (their term, not mine).

a_ is of this type: typedef Eigen::Map<Eigen::Matrix<double, ROWS, COLS>> EA;

b_ is of this type: typedef Eigen::Map<Eigen::Matrix<double, ROWS, 1>> EB;

T is the Ceres Solver Jet type. The errors seem to bespeak a column/row mismatch rather than a type problem. I could be wrong, though; the output is entirely too verbose. Did I misunderstand how the rows and columns work with Eigen matrix operators?

Update: I followed the "fatal-errors" suggestion:

```<code>In file included from /usr/include/eigen3/Eigen/Core:437:0,
                 from /usr/local/include/ceres/jet.h:165,
                 from /usr/local/include/ceres/internal/autodiff.h:145,
                 from /usr/local/include/ceres/autodiff_cost_function.h:132,
                 from /usr/local/include/ceres/ceres.h:37,
                 from /home/brannon/Workspace/Solver/music_solver.cpp:3:
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h: In instantiation of ‘class Eigen::PlainObjectBase<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1> >’:
/usr/include/eigen3/Eigen/src/Core/Matrix.h:178:7:   required from ‘class Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>’
/usr/include/eigen3/Eigen/src/Core/Map.h:24:32:   required from ‘struct Eigen::internal::traits<Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> > >’
/usr/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h:32:54:   required from ‘struct Eigen::internal::accessors_level<Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> > >’
/usr/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h:113:75:   required from ‘class Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> >’
/home/brannon/Workspace/Solver/music_solver.cpp:18:72:   required from ‘bool MusicCostFunctor<MATRIX_A, MATRIX_B>::operator()(const T*, T*) const [with T = double; MATRIX_A = Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >; MATRIX_B = Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> >]’
/usr/local/include/ceres/internal/variadic_evaluate.h:175:19:   required from ‘static bool ceres::internal::VariadicEvaluate<Functor, T, N0, 0, 0, 0, 0, 0, 0, 0, 0, 0>::Call(const Functor&, const T* const*, T*) [with Functor = MusicCostFunctor<Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >, Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> > >; T = double; int N0 = 1200]’
/usr/local/include/ceres/autodiff_cost_function.h:208:17:   required from ‘bool ceres::AutoDiffCostFunction<CostFunctor, kNumResiduals, N0, N1, N2, N3, N4, N5, N6, N7, N8, N9>::Evaluate(const double* const*, double*, double**) const [with CostFunctor = MusicCostFunctor<Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >, Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> > >; int kNumResiduals = 1; int N0 = 1200; int N1 = 0; int N2 = 0; int N3 = 0; int N4 = 0; int N5 = 0; int N6 = 0; int N7 = 0; int N8 = 0; int N9 = 0]’
/home/brannon/Workspace/Solver/music_solver.cpp:115:1:   required from here
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:585:27: error: ‘static Eigen::PlainObjectBase<Derived>::MapType Eigen::PlainObjectBase<Derived>::Map(Eigen::PlainObjectBase<Derived>::Scalar*) [with Derived = Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>; Eigen::PlainObjectBase<Derived>::MapType = Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> >; Eigen::PlainObjectBase<Derived>::Scalar = const double]’ cannot be overloaded
     static inline MapType Map(Scalar* data)
                           ^~~
</code>```

答:
You need to tell Eigen how to mix your scalar types through Eigen:: ScalarBinaryOpTraits. See similar questions with solutions there:

https://forum.kde.org/viewtopic.php?f=74&t=141467

Transform matrix of 3D positions with corresponding transformation matrix

Body:
I can't get this to compile:

Eigen::Map<Eigen::Matrix<const T, EA::ColsAtCompileTime, 1>> x(vec);
auto result = a_ * x - b_; // a(60r,1200c) * x(1200r,1c) - b(60r,1c)

The two errors (about 1000 lines each) eventually conclude that the * and - operators can't be "overloaded" (their term, not mine).

a_ is of this type: typedef Eigen::Map<Eigen::Matrix<double, ROWS, COLS>> EA;

b_ is of this type: typedef Eigen::Map<Eigen::Matrix<double, ROWS, 1>> EB;

T is the Ceres Solver Jet type. The errors seem to bespeak a column/row mismatch rather than a type problem. I could be wrong, though; the output is entirely too verbose. Did I misunderstand how the rows and columns work with Eigen matrix operators?

Update: I followed the "fatal-errors" suggestion:

In file included from /usr/include/eigen3/Eigen/Core:437:0,
                 from /usr/local/include/ceres/jet.h:165,
                 from /usr/local/include/ceres/internal/autodiff.h:145,
                 from /usr/local/include/ceres/autodiff_cost_function.h:132,
                 from /usr/local/include/ceres/ceres.h:37,
                 from /home/brannon/Workspace/Solver/music_solver.cpp:3:
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h: In instantiation of ‘class Eigen::PlainObjectBase<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1> >’:
/usr/include/eigen3/Eigen/src/Core/Matrix.h:178:7:   required from ‘class Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>’
/usr/include/eigen3/Eigen/src/Core/Map.h:24:32:   required from ‘struct Eigen::internal::traits<Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> > >’
/usr/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h:32:54:   required from ‘struct Eigen::internal::accessors_level<Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> > >’
/usr/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h:113:75:   required from ‘class Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> >’
/home/brannon/Workspace/Solver/music_solver.cpp:18:72:   required from ‘bool MusicCostFunctor<MATRIX_A, MATRIX_B>::operator()(const T*, T*) const [with T = double; MATRIX_A = Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >; MATRIX_B = Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> >]’
/usr/local/include/ceres/internal/variadic_evaluate.h:175:19:   required from ‘static bool ceres::internal::VariadicEvaluate<Functor, T, N0, 0, 0, 0, 0, 0, 0, 0, 0, 0>::Call(const Functor&, const T* const*, T*) [with Functor = MusicCostFunctor<Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >, Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> > >; T = double; int N0 = 1200]’
/usr/local/include/ceres/autodiff_cost_function.h:208:17:   required from ‘bool ceres::AutoDiffCostFunction<CostFunctor, kNumResiduals, N0, N1, N2, N3, N4, N5, N6, N7, N8, N9>::Evaluate(const double* const*, double*, double**) const [with CostFunctor = MusicCostFunctor<Eigen::Map<Eigen::Matrix<double, 60, 1200, 0, 60, 1200>, 0, Eigen::Stride<0, 0> >, Eigen::Map<Eigen::Matrix<double, 60, 1, 0, 60, 1>, 0, Eigen::Stride<0, 0> > >; int kNumResiduals = 1; int N0 = 1200; int N1 = 0; int N2 = 0; int N3 = 0; int N4 = 0; int N5 = 0; int N6 = 0; int N7 = 0; int N8 = 0; int N9 = 0]’
/home/brannon/Workspace/Solver/music_solver.cpp:115:1:   required from here
/usr/include/eigen3/Eigen/src/Core/PlainObjectBase.h:585:27: error: ‘static Eigen::PlainObjectBase<Derived>::MapType Eigen::PlainObjectBase<Derived>::Map(Eigen::PlainObjectBase<Derived>::Scalar*) [with Derived = Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>; Eigen::PlainObjectBase<Derived>::MapType = Eigen::Map<Eigen::Matrix<const double, 1200, 1, 0, 1200, 1>, 0, Eigen::Stride<0, 0> >; Eigen::PlainObjectBase<Derived>::Scalar = const double]’ cannot be overloaded
     static inline MapType Map(Scalar* data)
                           ^~~


问:
How to filter files shown in Visual Studio Code?
How would you filter the files shown in the folder view in Visual Studio Code?

Reference: Filter files shown in folder

答:
If you only want to change the setting for this project, then do the following:

File > Save Workspace As > ... enter your {project name}

Then open file: {project name}.code-workspace
And update section settings.

Sample:

```<code>{
    "folders": [
        {
            "path": "."
        }
    ],
    "settings": {
        "files.exclude": {
            "**/*.log": true
        }
    }
}
</code>```

Body:
If you only want to change the setting for this project, then do the following:

File > Save Workspace As > ... enter your {project name}

Then open file: {project name}.code-workspace
And update section settings.

Sample:

{
    "folders": [
        {
            "path": "."
        }
    ],
    "settings": {
        "files.exclude": {
            "**/*.log": true
        }
    }
}