问:
On dropdown search not able to generate pop
```<code>@{
    ViewBag.Title = "iifl_conference";
    Layout = "/Views/Shared/_ConferenceLayout.cshtml";
}
@model IIFLWeb.Models.Parents.EventsParent
@section Conference
{
    <div class="search-ac-list">
        @Html.DropDownList("ddlSpeaker", Model.lstSpeakerData, "Select Speaker", new { @onchange = "GetSearchedSpeakerData(this)", @class = "select2" })
    </div>
}
</code>```

The Main issue is that I am not able to generate pop up in search

```<code>function GetSearchedSpeakerData(val) {
    var selectedSpeaker = val.value;
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/NewConference/getSearchedSpeaker",
        data: {"name": selectedSpeaker },
        success: function (result) {
            var SpeakData = '';
            $.each(result, function (i, val) {
                var SpeakerName = '';
                SpeakData += ' <li>';
                SpeakData += '<a href="#SpeakerPopup"  onclick="GetSelectedSpeakerData(\'' + val.Name + '\');" data-effect="mfp-zoom-in" id="SpeakerDetails" class="open-popup-link popup-block">';
                SpeakData += '<div class="height240">';
                SpeakData += '<div class="circle-img">';
                if(val.Name=="Panel Discussions")
                {
                    SpeakData += ' <img src="../../Upload/SpecialistSpeaker/' + val.ImageUrl + ' " alt="Panel Discussions "/>';

                }
                else
                {
                    SpeakData += ' <img src="../../Upload/SpecialistSpeaker/' + val.ImageUrl + ' " alt="'+val.Name+'"/>';
                }
                SpeakData += '</div>';
                SpeakData += '<h4>'+val.Title +'</h4>';
                SpeakData += '<label class="speaker-date">';
                SpeakData += +val.TimeSlot + ", " + val.Venue  + " at "+val.SpeakerDate ;
                SpeakData += ' </label>';
                SpeakData += '</div>';
                SpeakData += '<div class="speaker-bx">';
                SpeakData += '<h3 id="SpeakerName">' + val.Name + '</h3>';
                SpeakData += '<h4>' + val.Designation + '</h4>';
                SpeakData += '</div>';
                SpeakData += '</a>';
                SpeakData += '</li>';
            });
            $("#UlProfileList ").empty();
            $("#UlProfileList").append(SpeakData);
        }
    });
}
</code>```

I am getting name from dropdownlist and from  Ajax function name called GetSearchedSpeakerData(val) and I get that particular div

Now OnClick of that particular Div Need to generate Popup, for that I am using another Ajax function name called GetSelectedSpeakerData(val) , This function is create so that on select of the particular div I get  "name" value on that name value is and popup is  created form ajax function GetSelectedSpeakerData(val)..

```<code>function GetSelectedSpeakerData(val) {
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/NewConference/getSearchedSpeaker",
        data: { "name": val },
        success: function (result) {
            var SpeakData = '';
            var Speaktopic='';
            var Speaktab='';
            $.each(result, function (i, val) {
                var SpeakerName = '' ;
                SpeakData += ' <div class="col-sm-3">';
                SpeakData += ' <div class="circle-img">';
                SpeakData += ' <img src="../../Upload/SpecialistSpeaker/'+ val.ImageUrl+ ' " alt=" '+val.Name+ '"/>';
                SpeakData += '</div>';
                SpeakData += '</div>';
                SpeakData += '<div class="col-sm-9">';
                if(val.Name=="Panel Discussions")
                {
                    SpeakData += '<h3>Panel Discussion</h3>';
                }
                else
                {
                    SpeakData += '<h3>'+val.Name+'</h3>';
                }
                SpeakData += '<h5>'+val.Designation+'</h5>';
                SpeakData += '<h4>' + val.Title + '</h4>';
                if(@Html.Raw(Json.Encode(ViewBag.IsVenue)) == true)
                {
                    SpeakData += '<label class="speaker-date"> ( ' + val.SpeakerDate + ", " + val.TimeSlot + " at " + val.Venue + ')</label>';
                }
                SpeakData +='</div>';
                Speaktopic += '<div role="tabpanel" class="tab-pane active" id="Tab1-1">' + val.Description + '</div>';
                Speaktopic += '<div role="tabpanel" class="tab-pane" id="Tab1-2">' + val.CompanyDesc + '</div>';
                Speaktopic += '<div role="tabpanel" class="tab-pane" id="Tab1-3">';
                Speaktopic += '<h4>' + val.Title + '</h4>';
                Speaktopic += val.Topic +'</div>';
                Speaktopic += '<div role="tabpanel" class="tab-pane" id="Tab1-4">';
                Speaktopic += '<video controls class="VideoPlayer">';
                Speaktopic +='<source src="http://www.iiflcap.com/IPad/Conference/Videos/2017/'+val.VideoUrl+'"  type="video/mp4"></video></div>';
                if (val.Description != "")
                {
                    Speaktab += '<li role="presentation" class="active">';
                    Speaktab +=' <a href="#Tab1-1" aria-controls="Tab1-1" role="tab" data-toggle="tab">Profile</a>';
                    Speaktab +=' </li>';
                }
                if (val.CompanyDesc != "")
                {
                    Speaktab +='<li role="presentation" >';
                    Speaktab +=' <a href="#Tab1-2" aria-controls="Tab1-2" role="tab" data-toggle="tab">Company</a>';
                    Speaktab +='  </li>';
                }
                if(val.Topic != "")
                {
                    Speaktab +='  <li role="presentation">';
                    Speaktab +='<a href="#Tab1-3" aria-controls="Tab1-3" role="tab" data-toggle="tab">Topic</a></li>';
                    Speaktab +='</li>';
                }
                if(val.VideoUrl != "")
                {
                    Speaktab +='  <li role="presentation">';
                    Speaktab +=  '<a href="#Tab1-4" aria-controls="Tab1-4" role="tab" data-toggle="tab">Video</a></li>';
                    Speaktab += '</li>';
                }
            });
            $("#Details").empty();
            $("#Details").append(SpeakData);
            $("#Tabcontent").empty();
            $("#Tabcontent").append(Speaktopic);
            $("#Menutabs").empty();
            $("#Menutabs").append(Speaktab);
         }
    });
}
</code>```

I can see on the brower the popup div called div is named as #SpeakerPopup
But I cannot  see the Popup up

```<code><div id="SpeakerPopup" class="white-popup mfp-with-anim mfp-hide">
    <div id = "Details" class="row">
        <div class="col-sm-3">
            <div class="circle-img">
                <img src="resources/images/speakers/1.jpg"/>
            </div>
        </div>
        <div class="col-sm-9">
            <h3>Dr. Jim Walker</h3>
            <h5>Renowned economist, Founder and Managing Director, Asianomic</h5>
            <h4>"World War Three"</h4>
            <label class="speaker-date">(Tuesday, 21 February, 8:30am at Golconda)</label>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12">
            <ul id="Menutabs" class="nav nav-tabs Border-0 popuptabs" role="tablist">
                <li role="presentation"><a href="#Tab1-1" aria-controls="Tab1-1" role="tab" data-toggle="tab">Profile</a></li>
                <li role="presentation" class="active"><a href="#Tab1-2" aria-controls="Tab1-2" role="tab" data-toggle="tab">Company</a></li>
                <li role="presentation"><a href="#Tab1-3" aria-controls="Tab1-3" role="tab" data-toggle="tab">Topic</a></li>
                <li role="presentation"><a href="#Tab1-4" aria-controls="Tab1-4" role="tab" data-toggle="tab">Video</a></li>
            </ul>
            <div id="Tabcontent" class="tab-content">
                <div role="tabpanel" class="tab-pane active" id="Tab1-1">
                    <p>hello </p>
                </div>
                <div role="tabpanel" class="tab-pane" id="Tab1-2">
                    <p>HEllo</p>
                </div>
                <div role="tabpanel" class="tab-pane" id="Tab1-3">
                    <h4>"World War Three"</h4>
                    <p>hi </p>
                </div>
                <div role="tabpanel" class="tab-pane" id="Tab1-4">tttddd
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答:
This is purely css issue. I see mfp-hide class on popup - div#SpeakerPopup which basically might be having some property display:none in CSS. So what I would suggest is, Just add $("#SpeakerPopup").show() at the end of GetSelectedSpeakerData(val) ajax-success. Also you can just replace below lines

```<code>$("#Details").empty();
$("#Details").append(SpeakData);
$("#Tabcontent").empty();
$("#Tabcontent").append(Speaktopic);
$("#Menutabs").empty();
$("#Menutabs").append(Speaktab);
</code>```

with just

```<code>$("#Details").html(SpeakData);
$("#Tabcontent").html(Speaktopic);
$("#Menutabs").html(Speaktab);
</code>```

and at the end of these you can add $("#SpeakerPopup").show().

PS - Seems like you've been using twitter-bootstrap framework for responsive design. If so, you can try using bootstrap-modals to achieve this elegantly.

Hope this helps.

Body:
@{
    ViewBag.Title = "iifl_conference";
    Layout = "/Views/Shared/_ConferenceLayout.cshtml";
}
@model IIFLWeb.Models.Parents.EventsParent
@section Conference
{

        @Html.DropDownList("ddlSpeaker", Model.lstSpeakerData, "Select Speaker", new { @onchange = "GetSearchedSpeakerData(this)", @class = "select2" })

}

The Main issue is that I am not able to generate pop up in search

function GetSearchedSpeakerData(val) {
    var selectedSpeaker = val.value;
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/NewConference/getSearchedSpeaker",
        data: {"name": selectedSpeaker },
        success: function (result) {
            var SpeakData = '';
            $.each(result, function (i, val) {
                var SpeakerName = '';
                SpeakData += '
';
                SpeakData += '';
                SpeakData += '
';
                SpeakData += '
';
                if(val.Name=="Panel Discussions")
                {
                    SpeakData += ' ';

                }
                else
                {
                    SpeakData += ' ';
                }
                SpeakData += '
';
                SpeakData += '
'+val.Title +'
';
                SpeakData += '';
                SpeakData += +val.TimeSlot + ", " + val.Venue  + " at "+val.SpeakerDate ;
                SpeakData += ' ';
                SpeakData += '
';
                SpeakData += '
';
                SpeakData += '
' + val.Name + '
';
                SpeakData += '
' + val.Designation + '
';
                SpeakData += '
';
                SpeakData += '';
                SpeakData += '
';
            });
            $("#UlProfileList ").empty();
            $("#UlProfileList").append(SpeakData);
        }
    });
}

I am getting name from dropdownlist and from  Ajax function name called GetSearchedSpeakerData(val) and I get that particular div

Now OnClick of that particular Div Need to generate Popup, for that I am using another Ajax function name called GetSelectedSpeakerData(val) , This function is create so that on select of the particular div I get  "name" value on that name value is and popup is  created form ajax function GetSelectedSpeakerData(val)..

function GetSelectedSpeakerData(val) {
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/NewConference/getSearchedSpeaker",
        data: { "name": val },
        success: function (result) {
            var SpeakData = '';
            var Speaktopic='';
            var Speaktab='';
            $.each(result, function (i, val) {
                var SpeakerName = '' ;
                SpeakData += '
';
                SpeakData += '
';
                SpeakData += ' ';
                SpeakData += '
';
                SpeakData += '
';
                SpeakData += '
';
                if(val.Name=="Panel Discussions")
                {
                    SpeakData += '
Panel Discussion
';
                }
                else
                {
                    SpeakData += '
'+val.Name+'
';
                }
                SpeakData += '
'+val.Designation+'
';
                SpeakData += '
' + val.Title + '
';
                if(@Html.Raw(Json.Encode(ViewBag.IsVenue)) == true)
                {
                    SpeakData += ' ( ' + val.SpeakerDate + ", " + val.TimeSlot + " at " + val.Venue + ')';
                }
                SpeakData +='
';
                Speaktopic += '
' + val.Description + '
';
                Speaktopic += '
' + val.CompanyDesc + '
';
                Speaktopic += '
';
                Speaktopic += '
' + val.Title + '
';
                Speaktopic += val.Topic +'
';
                Speaktopic += '
';
                Speaktopic += '<video controls class="VideoPlayer">';
                Speaktopic +='<source src="http://www.iiflcap.com/IPad/Conference/Videos/2017/'+val.VideoUrl+'"  type="video/mp4"></video>
';
                if (val.Description != "")
                {
                    Speaktab += '
';
                    Speaktab +=' Profile';
                    Speaktab +='
';
                }
                if (val.CompanyDesc != "")
                {
                    Speaktab +='
';
                    Speaktab +=' Company';
                    Speaktab +='
';
                }
                if(val.Topic != "")
                {
                    Speaktab +='
';
                    Speaktab +='Topic
';
                    Speaktab +='
';
                }
                if(val.VideoUrl != "")
                {
                    Speaktab +='
';
                    Speaktab +=  'Video
';
                    Speaktab += '
';
                }
            });
            $("#Details").empty();
            $("#Details").append(SpeakData);
            $("#Tabcontent").empty();
            $("#Tabcontent").append(Speaktopic);
            $("#Menutabs").empty();
            $("#Menutabs").append(Speaktab);
         }
    });
}

I can see on the brower the popup div called div is named as #SpeakerPopup
But I cannot  see the Popup up

Dr. Jim Walker

Renowned economist, Founder and Managing Director, Asianomic

"World War Three"

            (Tuesday, 21 February, 8:30am at Golconda)

Profile

Company

Topic

Video

hello

HEllo

"World War Three"

hi

tttddd

Body:
This is purely css issue. I see mfp-hide class on popup - div#SpeakerPopup which basically might be having some property display:none in CSS. So what I would suggest is, Just add $("#SpeakerPopup").show() at the end of GetSelectedSpeakerData(val) ajax-success. Also you can just replace below lines

$("#Details").empty();
$("#Details").append(SpeakData);
$("#Tabcontent").empty();
$("#Tabcontent").append(Speaktopic);
$("#Menutabs").empty();
$("#Menutabs").append(Speaktab);

with just

$("#Details").html(SpeakData);
$("#Tabcontent").html(Speaktopic);
$("#Menutabs").html(Speaktab);

and at the end of these you can add $("#SpeakerPopup").show().

PS - Seems like you've been using twitter-bootstrap framework for responsive design. If so, you can try using bootstrap-modals to achieve this elegantly.

Hope this helps.


来源: stackexchange

问:
Importing HTML into another HTML import
I've got a small website I'm working on, and have chosen to seperate the navbar (I use Bootstrap) into an external file, so I don't have to re-write it for every file that uses it, every time I make a change to it. This works really well, as I have imported it with the following code:

```<code><!-- Loads external files -->
<script>
$(function(){
$("#navbarContent").load("/navbar.html");
});
</script>
</code>```

In my , I have the following code where I need the navbar:

```<code><div id="navbarContent"></div>
</code>```

The issue is, is that on my index, I have a link in the navbar that smoothly moves to the anchor position on the index page when clicked. What I want, is to be able to instantly move to the anchor when loading from another page other than the index (that works), except smoothly anchor from index itself.

My proposed solution is to simply add in a second import, which will be different based upon each page. In other words, the link to the anchor will have different href contents, so I'll store them in seperate files, but it won't work for some reason:

i.e.:

On index.html, use the following code:

```<code><script>
$(function(){
$("#navbarContent").load("/navbar.html").load("/indexcontact.html");
});
</script>
</code>```

Except what happens is, the entire thing is replaced by indexcontact.html instead of adding to navbar.html. I've tested with stupid things and this seems to happen no matter what I have in those two files.

So, is there a way to merge two jQuery loads so I can import both of the imports simply merged together into one huge string?

答:
One way is to use $.when with two AJAX calls and concatenate the output before setting it into the #navbarContent.

```<code>var d1 = $.ajax('/navbar.html');
var d2 = $.ajax('/indexcontact.html');

$.when( d1, d2 ).done(function ( v1, v2 ) {
    $("#navbarContent").html([v1[0], v2[0]].join());
});
</code>```

To know more about $.when, you can refer to the jQuery documentation here.

ContentLicense: CC BY-SA 3.0

Title: Importing HTML into another HTML import

Body:
I've got a small website I'm working on, and have chosen to seperate the navbar (I use Bootstrap) into an external file, so I don't have to re-write it for every file that uses it, every time I make a change to it. This works really well, as I have imported it with the following code:

In my , I have the following code where I need the navbar:

The issue is, is that on my index, I have a link in the navbar that smoothly moves to the anchor position on the index page when clicked. What I want, is to be able to instantly move to the anchor when loading from another page other than the index (that works), except smoothly anchor from index itself.

My proposed solution is to simply add in a second import, which will be different based upon each page. In other words, the link to the anchor will have different href contents, so I'll store them in seperate files, but it won't work for some reason:

i.e.:

On index.html, use the following code:

Except what happens is, the entire thing is replaced by indexcontact.html instead of adding to navbar.html. I've tested with stupid things and this seems to happen no matter what I have in those two files.

So, is there a way to merge two jQuery loads so I can import both of the imports simply merged together into one huge string?

Body:
One way is to use $.when with two AJAX calls and concatenate the output before setting it into the #navbarContent.

var d1 = $.ajax('/navbar.html');
var d2 = $.ajax('/indexcontact.html');

$.when( d1, d2 ).done(function ( v1, v2 ) {
    $("#navbarContent").html([v1[0], v2[0]].join());
});

To know more about $.when, you can refer to the jQuery documentation here.


问:
Prgrammably making excel spreadsheets (97 - 2003 format)
I was wondering how difficult it would be to make an application like this. Basically, I have some old html files that use tables. I want to put these tables into excel for easier reading and manipulation. I only have text, I have no numbers of formulas or anything.

Are there any tutorials on how to do this sort of thing?

The application would produce .xls

Thanks

答:
You have three options:

Output a CSV file. While not an XLS file, Excel is more than capable of opening such a file, and it's extremely easy to create. You need nothing more than standard C++ to implement this solution. This is by far the easiest and quickest way to output to Excel (or any spreadsheet program, for that matter).

Use OLE automation. Microsoft even has a Knowledge Base article that provides an example of how to invoke Excel from your native C++ application and fill in some values. If you absolutely need to output XLS files, this is the easiest way to go. Note that users must have Excel installed on their computers for this to work.

Create your own XLS writer. Don't even bother with this option unless you really want to generate XLS files without requiring Excel to be installed on end-user computers. Options 1 and 2 are more than good enough for just about any application.

ContentLicense: CC BY-SA 2.5


问:
multiple alarm clock in javascript using dynamic generated input elements in javascript
I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far</p>

```<code><div id="TextBoxContainer">
     <!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />

<script type="text/javascript">
        var room = 0;
        var i = 0;
        function GetDynamicTextBox(){
            return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
        }
        function AddTextBox() {
            var div = document.createElement('DIV');
            div.innerHTML = GetDynamicTextBox("");
            document.getElementById("TextBoxContainer").appendChild(div);
        }

        function RemoveTextBox(div) {
            document.getElementById("TextBoxContainer").removeChild(div.parentNode);
        }

        function RecreateDynamicTextboxes() {
                var html = "";
                html += "<div>" + GetDynamicTextBox() + "</div>";
                document.getElementById("TextBoxContainer").innerHTML = html;
                room++;
        }
        window.onload = RecreateDynamicTextboxes;

        function AddAlarm(values){
            var hour = document.getElementById('');
            var minute = document.getElementById('');
            var date = document.getElementById('');
        }
</script>
</code>```

答:
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).

This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.

For an alarm project, I would recommend an interval of one second.

Example (not tested):

JavaScript

```<code>var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.

var ONE_SECOND = 1000; // miliseconds

var alarmClock = setInterval(function() {
    var currentDate = new Date();

    if (currentDate.getHours() == alarmDate.getHours() &&
             currentDate.getMinutes() == alarmDate.getMinutes()
      /* compare other fields at your convenience */ ) {
        alert('Alarm triggered at ' + currentDate);
        // better use something better than alert for that?

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

To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.

In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.

Hope this helps and good luck!

Body:
I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far

<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />

Body:
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).

This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.

For an alarm project, I would recommend an interval of one second.

Example (not tested):

JavaScript

var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.

var ONE_SECOND = 1000; // miliseconds

var alarmClock = setInterval(function() {
    var currentDate = new Date();

    if (currentDate.getHours() == alarmDate.getHours() &&
             currentDate.getMinutes() == alarmDate.getMinutes()
      /* compare other fields at your convenience */ ) {
        alert('Alarm triggered at ' + currentDate);
        // better use something better than alert for that?

}, ONE_SECOND);

To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.

In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.

Hope this helps and good luck!


问:
Python: Trying to execute command to clear screen if user inputs certain number
I'm trying to remake a terminal from the Fallout series, if any of you know what that is.

Basically, the program shows a bunch of options they can choose from, then they have to input a number (1-5) to select which thing they want to view. The program will use an if statement to determine which thing they want to view. For example, if the user inputted one, then it will clear the screen and print a bunch of information, then the user has to input enter, then the screen clears and the options from the beginning are displayed again. This whole thing is inside a while statement, and while the user input is not "C", it will still display all of that other stuff, and when it does become "C", the program will clear everything and the program ends.

I know all of that sounded confusing, but basically the problem is that if the person inputs a number, it doesn't do the clearing thing, it just displays the choices again.

I'll just display the code, so if anyone could tell me what the problem is, that would greatly be appreciated.

```<code>def confusingFunction():
    from os import system
    userChoice = ""

    while userChoice.upper() != "C":
        print("Choice 1")
        print("Choice 2")
        print("Choice 3")
        print("Choice 4")
        print("Choice 5")
        userChoice = input(">>>")

        if userChoice == 1:
            system('cls')
            print("Stuff")
            print("Stuff")
            print("Stuff")
            input(">>>")
            system('cls')

    system('cls')
    return
</code>```

答:
Python 2.x

input evaluates whatever you entered and returns the result of evaluation.
So, userChoice is int when the user input is a number and it's a string when the user input is a string.

You can use raw_input to avoid the evaluation.

Python 3.x

input doesn't evaluate the entered value.

Body:
I'm trying to remake a terminal from the Fallout series, if any of you know what that is.

Basically, the program shows a bunch of options they can choose from, then they have to input a number (1-5) to select which thing they want to view. The program will use an if statement to determine which thing they want to view. For example, if the user inputted one, then it will clear the screen and print a bunch of information, then the user has to input enter, then the screen clears and the options from the beginning are displayed again. This whole thing is inside a while statement, and while the user input is not "C", it will still display all of that other stuff, and when it does become "C", the program will clear everything and the program ends.

I know all of that sounded confusing, but basically the problem is that if the person inputs a number, it doesn't do the clearing thing, it just displays the choices again.

I'll just display the code, so if anyone could tell me what the problem is, that would greatly be appreciated.

def confusingFunction():
    from os import system
    userChoice = ""

    while userChoice.upper() != "C":
        print("Choice 1")
        print("Choice 2")
        print("Choice 3")
        print("Choice 4")
        print("Choice 5")
        userChoice = input(">>>")

        if userChoice == 1:
            system('cls')
            print("Stuff")
            print("Stuff")
            print("Stuff")
            input(">>>")
            system('cls')

    system('cls')
    return


问:
why onclick is not working with innerHtml
Here I am trying to add html to an element using innerHtml

```<code>  <body>
 <h3>Dynamically Retrieve the chapter name</h3>
<div>
<div>
    <button id="addChapter">Add Chapter</button>
    <div id="courseStructure">

    </div>
 </div>
 </div>
<script src="index.js"></script>
</body>
</code>```

JS:

```<code>var addChapter = document.getElementById("addChapter");

  addChapter.onclick = function(){
document.getElementById("courseStructure").innerHtml += '<div><input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button><br><br></div>';
 }
</code>```

everything seems good the onclick event is firing when button is clicked but the html is not getting added to the element.

答:
you can selecting on js:

```<code>$("#courseStructure").click(function(){
document.getElementById("courseStructure").innerHtml += '<div><input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button><br><br></div>';
});
</code>```

or:

```<code><button id="addChapter" onclick="myFunction()">Add Chapter</button>
</code>```

Body:
Here I am trying to add html to an element using innerHtml

Dynamically Retrieve the chapter name

    <button id="addChapter">Add Chapter</button>

JS:

var addChapter = document.getElementById("addChapter");

  addChapter.onclick = function(){
document.getElementById("courseStructure").innerHtml += '
<input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button>

';
 }

everything seems good the onclick event is firing when button is clicked but the html is not getting added to the element.

Body:
you can selecting on js:

$("#courseStructure").click(function(){
document.getElementById("courseStructure").innerHtml += '<div><input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button><br><br></div>';
});

or:

<button id="addChapter" onclick="myFunction()">Add Chapter</button>


问:
how can I know whether a user has watched my full rewarded video ad or skip ad in android?
I am using Rewarded interstitial ads in my app.
Is there any method to know whether any user has watched a complete rewarded video or not in my rewarded video ad?

I need to place a rewarded video in my app, and I want to know whether any user has watched the full video or not? How can I know that?

答:
Yes you can check if an user has completely watched a rewarded video or not. All you need to do it to implement the rewarded ad video listener.

```<code>yourAdObject.setRewardedVideoAdListener(this);
</code>```

and implement RewardedVideoAdListener's methods in your activity.
It will override these methods :

```<code>@Override
public void onRewarded(RewardItem reward) {

}

// The following listener methods are optional.
@Override
public void onRewardedVideoAdLeftApplication() {

}

@Override
public void onRewardedVideoAdClosed() {

}

@Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {

}

@Override
public void onRewardedVideoAdLoaded() {

}

@Override
public void onRewardedVideoAdOpened() {

}

@Override
public void onRewardedVideoStarted() {
}
</code>```

The onRewarded(RewardItem reward) is called on watching the video completely.

For more information about Video Ads read the official docs

Body:
Yes you can check if an user has completely watched a rewarded video or not. All you need to do it to implement the rewarded ad video listener.

yourAdObject.setRewardedVideoAdListener(this);

and implement RewardedVideoAdListener's methods in your activity.
It will override these methods :

@Override
public void onRewarded(RewardItem reward) {

}

// The following listener methods are optional.
@Override
public void onRewardedVideoAdLeftApplication() {

}

@Override
public void onRewardedVideoAdClosed() {

}

@Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {

}

@Override
public void onRewardedVideoAdLoaded() {

}

@Override
public void onRewardedVideoAdOpened() {

}

@Override
public void onRewardedVideoStarted() {
}

The onRewarded(RewardItem reward) is called on watching the video completely.

For more information about Video Ads read the official docs


问:
Initializing a dynamic memory array in a class
I am new to c++ programming, and this is probably a trivial problem, but I need to construct a variable sized array in a class and transfer text file data into it, see below. Here HISTORYFile >> ClusterCoord[i]; seems to take in the information fine, however when I try to get access to the info in the main program via,

```<code>cout << CoordClassExample.ClusterCoord[1] << "\n";
</code>```

I get a bus error. Please help if you can!

```<code>class CoordClass{
public:
    int Entries;
    double * ClusterCoord;
    void set_valuesCoord(ifstream &HISTORYFile,int MolAtomNum, int MolNum);
};

void CoordClass::set_valuesCoord(ifstream& HISTORYFile,int MolAtomNum, int MolNum) {
    Entries=MolAtomNum*MolNum;
    double *ClusterCoord = new double [Entries];

    for (int i=0;i<Entries;i++) {
        HISTORYFile.ignore(1000,'\n');
            HISTORYFile >> ClusterCoord[i];
        cout << ClusterCoord[i] << "\n";
            HISTORYFile.ignore(1000,'\n');
    }
}
</code>```

答:
You have a leak in the set_valuesCoord() function if you call the function twice, unless you somewhere release the resources. That's not the problem but it's a problem. Use a std::vector<>.

```<code>class CoordClass {
    // ...
    std::vector<double> ClusterCoord;  // instead of double *ClusterCoord
    // ...
};
</code>```

What might be the problem is that you don't check whether the double parsed properly. If it didn't then you're accessing uninitialized memory, and that leads to undefined behaviour.

```<code>void CoordClass::set_valuesCoord(...)
{
    // ...
    double cluster_coord = 0;
    if( HISTORYFile >> cluster_coord )
        ClusterCoord.push_back(cluster_coord);
    else
        std::cerr << "Error parsing cluster coord.\n";
    // ...
}
</code>```

Body:
I am new to c++ programming, and this is probably a trivial problem, but I need to construct a variable sized array in a class and transfer text file data into it, see below. Here HISTORYFile >> ClusterCoord[i]; seems to take in the information fine, however when I try to get access to the info in the main program via,

cout << CoordClassExample.ClusterCoord[1] << "\n";

I get a bus error. Please help if you can!

class CoordClass{
public:
    int Entries;
    double * ClusterCoord;
    void set_valuesCoord(ifstream &HISTORYFile,int MolAtomNum, int MolNum);
};

void CoordClass::set_valuesCoord(ifstream& HISTORYFile,int MolAtomNum, int MolNum) {
    Entries=MolAtomNum*MolNum;
    double *ClusterCoord = new double [Entries];

    for (int i=0;i<Entries;i++) {
        HISTORYFile.ignore(1000,'\n');
            HISTORYFile >> ClusterCoord[i];
        cout << ClusterCoord[i] << "\n";
            HISTORYFile.ignore(1000,'\n');
    }
}

Body:
You have a leak in the set_valuesCoord() function if you call the function twice, unless you somewhere release the resources. That's not the problem but it's a problem. Use a std::vector<>.

class CoordClass {
    // ...
    std::vector<double> ClusterCoord;  // instead of double *ClusterCoord
    // ...
};

What might be the problem is that you don't check whether the double parsed properly. If it didn't then you're accessing uninitialized memory, and that leads to undefined behaviour.

void CoordClass::set_valuesCoord(...)
{
    // ...
    double cluster_coord = 0;
    if( HISTORYFile >> cluster_coord )
        ClusterCoord.push_back(cluster_coord);
    else
        std::cerr << "Error parsing cluster coord.\n";
    // ...
}


问:
Yii2 | requires bower-asset/jquery
I'm trying to install Yii2 via composer:

```<code>composer global require "fxp/composer-asset-plugin:~1.1.1"
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
</code>```

~/.composer/composer.json

```<code>{
    "require": {
    "fxp/composer-asset-plugin": "~1.1.1"
    }
}
</code>```

result:

```<code>Problem 1
- yiisoft/yii2 2.0.x-dev requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
- yiisoft/yii2 dev-master requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
- yiisoft/yii2 2.0.6 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
- yiisoft/yii2 2.0.5 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
- Installation request for yiisoft/yii2 >=2.0.5 -> satisfiable by yiisoft/yii2[2.0.5, 2.0.6, dev-master, 2.0.x-dev].
</code>```

What do I do wrong?

答:
You can try the newer version:

```<code>composer global require "fxp/composer-asset-plugin:^1.2.0"
</code>```

then:

```<code>composer create-project --prefer-dist yiisoft/yii2-app-basic basic
</code>```

Non-install Bower-Asset way:

You can download Yii2 by Install from an Archive File. By this way you won't need to handle Bower issue.

Further, if you need to update composer without handling Bower, you can require yidas/yii2-composer-bower-skip before yiisoft/yii2 in composer.json file:

```<code>"require": {
    "php": ">=5.4.0",
    "yidas/yii2-composer-bower-skip": "~2.0.0",
    "yiisoft/yii2": "~2.0.5",
    "yiisoft/yii2-bootstrap": "~2.0.0"
}
</code>```

Instead, if you want to create yii2 project without bower-asset issue:

yidas/yii2-app-basic:

composer create-project yidas/yii2-app-basic

yidas/yii2-app-advanced:

composer create-project yidas/yii2-app-advanced

From Yii 2.0.13, it used Asset-Packagist solution instead of fxp/composer-asset-plugin

Title: Yii2 | requires bower-asset/jquery

Body:
I'm trying to install Yii2 via composer:

composer global require "fxp/composer-asset-plugin:~1.1.1"
composer create-project --prefer-dist yiisoft/yii2-app-basic basic

~/.composer/composer.json

{
    "require": {
    "fxp/composer-asset-plugin": "~1.1.1"
    }
}

result:

Problem 1
- yiisoft/yii2 2.0.x-dev requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
- yiisoft/yii2 dev-master requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
- yiisoft/yii2 2.0.6 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
- yiisoft/yii2 2.0.5 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
- Installation request for yiisoft/yii2 >=2.0.5 -> satisfiable by yiisoft/yii2[2.0.5, 2.0.6, dev-master, 2.0.x-dev].

What do I do wrong?

Body:
You can try the newer version:

composer global require "fxp/composer-asset-plugin:^1.2.0"

then:

composer create-project --prefer-dist yiisoft/yii2-app-basic basic

Non-install Bower-Asset way:

You can download Yii2 by Install from an Archive File. By this way you won't need to handle Bower issue.

Further, if you need to update composer without handling Bower, you can require yidas/yii2-composer-bower-skip before yiisoft/yii2 in composer.json file:

"require": {
    "php": ">=5.4.0",
    "yidas/yii2-composer-bower-skip": "~2.0.0",
    "yiisoft/yii2": "~2.0.5",
    "yiisoft/yii2-bootstrap": "~2.0.0"
}

Instead, if you want to create yii2 project without bower-asset issue:

yidas/yii2-app-basic:

composer create-project yidas/yii2-app-basic

yidas/yii2-app-advanced:

composer create-project yidas/yii2-app-advanced

From Yii 2.0.13, it used Asset-Packagist solution instead of fxp/composer-asset-plugin


问:
How to extract n rows based on similar column values in a dataframe
I have a large dataframe that has imported data from multiple csv files. The dataframe has a column that lists the filename each data point came from. From this large dataframe, I'd like to extract every 50 rows of data from the same filename. So from filename 1, extract rows 1,50,100, 150,etc and from filename 2 extract rows 1,50,100,150, and then combine all of the extracted rows into 1 dataframe with their filenames.

The problem is that all of the data is already imported into 1 dataframe. So using this 1 dataframe, how do I make a new one as explained above?

Another way to ask this question is:

I have a list of dataframes and I'd like to extract every 50 rows from each dataframe in the list and combine them into a new dataframe.

I know for a single dataframe I can do this:
new.df <- df1[seq(1,nrow(df1),50),]

How do I do this for each dataframe in a list and then combine those results into 1 large dataframe?

Thanks!

答:
```<code>split_df <- split(df, df$filename)
subset_df <- do.call(rbind, lapply(split_df, function(x) {x[c("your_rows_here"),]}))
</code>```

Hope this solves it!

Body:
split_df <- split(df, df$filename)
subset_df <- do.call(rbind, lapply(split_df, function(x) {x[c("your_rows_here"),]}))

Hope this solves it!


问:
Dynamic style - Angular
Basivally i have a div ,which i'm putting a dynamic style

```<code><div style="position:relative; left: {{et.getNumPadStyle()}}px">
</code>```

My function getNumPadStyle will have

```<code>function getNumPadStyle {
    var num = "25";
    return num;
}
</code>```

This is giving me an error

```<code>Referencing DOM nodes in Angular expressions is disallowed! Expression: et.getNumPadStyle()
</code>```

And when i inspect the element, the exact number is not reflecting

```<code>element {
    position:relative;
    left:{{et.getNumPadStyle()}}px
}
</code>```

How to resolve this?

答:
There are few errors in your code . Find the code example below

Html :

```<code><div ng-app>
  <div ng-controller="TodoCtrl">
  <div style="position:relative; left: {{getNumPadStyle()}}px">test</div>
</div>
</code>```

JS :

```<code>function TodoCtrl($scope) {
    $scope.getNumPadStyle= function() {
    var num = "455";
    return num;
}
  };
</code>```

Title: Dynamic style - Angular

Body:
Basivally i have a div ,which i'm putting a dynamic style

My function getNumPadStyle will have

function getNumPadStyle {
    var num = "25";
    return num;
}

This is giving me an error

Referencing DOM nodes in Angular expressions is disallowed! Expression: et.getNumPadStyle()

And when i inspect the element, the exact number is not reflecting

element {
    position:relative;
    left:{{et.getNumPadStyle()}}px
}

How to resolve this?

Body:
There are few errors in your code . Find the code example below

Html :

<div ng-app>
  <div ng-controller="TodoCtrl">
  <div style="position:relative; left: {{getNumPadStyle()}}px">test</div>
</div>

JS :

function TodoCtrl($scope) {
    $scope.getNumPadStyle= function() {
    var num = "455";
    return num;
}
  };


问:
Get UITableViewRowAction to bounce on tap
I want to add feedback for a table cell with a row action. When the user clicks the cell the row action will bounce open a bit. I've seen this somewhere before, it shows the user theres a menu. </p>

<p>I don't see anything in the docs that would give me that control. </p>

答:
```<code>            UIView.animate(withDuration: 0.2, animations: {

                cell?.frame = CGRect(x: (cell?.frame.origin.x)!-15, y: (cell?.frame.origin.y)!, width: cell!.bounds.size.width, height: cell!.bounds.size.height)

            }) { (finished) in
                UIView.animate(withDuration: 0.3, animations: {

                    cell?.frame = CGRect(x: (cell?.frame.origin.x)!+15, y: (cell?.frame.origin.y)!, width: cell!.bounds.size.width, height: cell!.bounds.size.height)

                })
                tableView.deselectRow(at: indexPath, animated: true)
            }
</code>```

Body:
I want to add feedback for a table cell with a row action. When the user clicks the cell the row action will bounce open a bit. I've seen this somewhere before, it shows the user theres a menu.

I don't see anything in the docs that would give me that control.


问:
banner refresh code
I have banner code, which is not like images and hyperlinks. All I need is the javascript code that will refresh this code every 30 seconds without refreshing the rest of the page.

This banner code will be appear in chatroom. I would really appreciate any help.
The banner code:

```<code><script language='JavaScript'
        type='text/javascript'
        src='xxxxxx/banner.php?uname=yyyy&type=2&rows=1' >
</script>
</code>```

答:
First thing you should do is wrap your code in a function. Trying to re-invoke an entire scripting file import is much more difficult than just invoking a function.

Once everything is wrapped in a function, you can use setTimeout to invoke the method. I would do something like this:

```<code>function drawBanner() {
    // Do stuff to draw the banner.
    // Make sure you handle the case that the
    // banner is already present in the DOM!
}

function onDrawBannerTimer() {
    // Set this function to fire again after 30 seconds.
    // Note that this will fire it roughly every 30 seconds real-time.
    // You can move this statement to after the drawBanner() call
    // in order to make it 30 seconds between the end of one
    // invocation and the start of the next.
    setTimeout(onDrawBannerTimer, 30 * 1000);
    drawBanner();
}

// Trigger the first invocation when the script is loaded.
onDrawBannerTimer();
</code>```

Title: banner refresh code

Body:
First thing you should do is wrap your code in a function. Trying to re-invoke an entire scripting file import is much more difficult than just invoking a function.

Once everything is wrapped in a function, you can use setTimeout to invoke the method. I would do something like this:

function drawBanner() {
    // Do stuff to draw the banner.
    // Make sure you handle the case that the
    // banner is already present in the DOM!
}

function onDrawBannerTimer() {
    // Set this function to fire again after 30 seconds.
    // Note that this will fire it roughly every 30 seconds real-time.
    // You can move this statement to after the drawBanner() call
    // in order to make it 30 seconds between the end of one
    // invocation and the start of the next.
    setTimeout(onDrawBannerTimer, 30 * 1000);
    drawBanner();
}

// Trigger the first invocation when the script is loaded.
onDrawBannerTimer();


问:
SSMS - stop execution with sql command
Is there a command in SSMS to pause execution at selected point, like putting break point?

Example:

```<code>declare @i int
declare @b int

debugger // stop execution here

select * from myTable
</code>```

Something like debugger command in javascript?

答: usually debugging an sp is tricky i use print statement in every loop so i can know that it entered that loop and the best way is to put them in a transaction and instead of commeting the transaction just rollback the transaction by this way your database will be intact too and also print the variables so you can know the values </p>

Title: SSMS - stop execution with sql command

Body:
Is there a command in SSMS to pause execution at selected point, like putting break point?

Example:

declare @i int
declare @b int

debugger // stop execution here

select * from myTable

Something like debugger command in javascript?


问:
Allow tab completion in rbash
I have restricted user, whose default shell is rbash. Now, I would like to allow the TAB completion feature for this user for his/her home directory, instead of getting this error:

```<code>-rbash: /dev/null: restricted: cannot redirect output
-rbash: /dev/null: restricted: cannot redirect output
bash: _upvars: `-a2': invalid number specifier
-rbash: /dev/null: restricted: cannot redirect output
bash: _upvars: `-a0': invalid number specifier
</code>```

How can I do this for restricted user?

答: Sorry for the late reply, but this is one of the first results in Google for this issue, so you ought to know: Tab completion works ordinarily, even in rbash. I recently encountered this same issue and it turned out to be caused by using su restricteduser instead of su -l restricteduser. The latter command sets the environment and shell variables to be like they would be if you had logged in as restricteduser with an actual login shell. You never mentioned su in the OP, but I suspect this was the issue.

Title: Allow tab completion in rbash

Body:
I have restricted user, whose default shell is rbash. Now, I would like to allow the TAB completion feature for this user for his/her home directory, instead of getting this error:

-rbash: /dev/null: restricted: cannot redirect output
-rbash: /dev/null: restricted: cannot redirect output
bash: _upvars: `-a2': invalid number specifier
-rbash: /dev/null: restricted: cannot redirect output
bash: _upvars: `-a0': invalid number specifier

How can I do this for restricted user?


问:
Revision control locking: Is the jury still out?
When I'm online it seems that everyone has agreed that using the exclusive locking workflow in source control is a Bad Thing. All the new revision control systems I see appear to be built for edit and merge workflows, and many don't even support exclusive locks at all.

However, everyone I work with is of the opinion that exclusive locks are a "must have" for any source control system, and working any other way would be a nightmare. Even recent hires from other companies seem to come in with this idea.

My question isn't who is right. I'm pretty sure what answer I'd get to that. My question is, is there really still any debate over this matter? Is there an honest "pro locking" camp out there that makes a serious case? Is any work being done to advance the art of revision control based around the locking model? Or are locking fans flogging a dead horse?

EDIT:
The answers so far have done a good job of explaining why exclusive locks are a good feature to use occasionally. However, I'm talking about promoting a workflow where exclusive locks are used for everything.

答:
Here's my $0.02.

Locking is an old school of thought for textual Code. Once programmers use merging a couple of times they learn and usually like the power of it.

Valid cases for locks still exist.

Graphics alterations. 99% of the time you cannot merge 2 peoples work on the same graphic.

Binary updates.

Sometimes code can be complex/simple enough to justify only 1 person working on it at a time. In this case it's a project management choice to use a feature.


问:
nodejs get mac address of client
I created a Tcp server using net module in NodeJS and tried to get the mac address info from each client to generate uuid. However, in the Socket object, there is no information about it. Also I tried to get read mac address from arp table, but it's not working either. Any other ways to figure it out?

答:
I did something similar before for class rooms in production environment. In my case, I have access to all client machines. Either you have admin access to all clients or you can pre-register the client into your database somehow, you can do the following. If not, please ignore this answer.

Create another NodeJs program hosted a web service in Clients (Don't forget to implement some kind of security). This program could be just a simple ExpressJs with getmac node module.

Register all IPs or domain name of the clients to Server database. Could be manual or, in my case, when Client turned-on it's auto send a request to server to register itself. (Implement client-server validation if needed)

When Server needed the mac from client, Server app sends a request to each pre-registered client to get its mac address or any other information Server needs from clients.

Title: nodejs get mac address of client


问:
How to retrieve object that I stored in azure service bus from message queue
I stored object in azure service bus now I want to retrieve that object and its values. Here is my code that I used to store object in azure service bus.</p>

```<code>class Program
    {
      static void Main(string[] args)
       {
foreach(string file in Directory.EnumerateFiles(@"C:\Users\shubham.mittal\Desktop\xml", "*.xml"))
            {
                string contents = File.ReadAllText(file);
                XDocument doc = XDocument.Parse(contents);
                string locationcode = doc.Root.Element("Customer").Element("Location_Code").Value;
                string Phone_Number = doc.Root.Element("Customer").Element("Phone_Number").Value;
                var connectionString = "Endpoint=sb://namespacename.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=sharedaccesskey";
                var queueName = "shubhamqueue";

                var client = QueueClient.CreateFromConnectionString(connectionString, queueName);
                data d=new data();
                d.location_code=locationcode;
                d.Phone_Number = Phone_Number;
                var message1 = new BrokeredMessage(d);
                client.Send(message1);
            }
        }
    }
</code>```

答:
We could get BrokerMessage info with BrokeredMessage.GetBody<T>. So in your case I create a demo and it works on my side.

1.Create a C# console project.

2.Reference the Microsoft Azure Service Bus SDK

3.Add a public Class

```<code>public class Data

{
    public string LocationCode { get; set; }
    public string PhoneNumber { get; set; }
}
</code>```

4. Add the following code to the main function in the Program.cs

```<code>  var client =
  QueueClient.CreateFromConnectionString("servicebus connection string", queueName);
  Data data = new Data
  {
      LocationCode =  "test location code",
      PhoneNumber = "test phone number"
  };
  var sendMessage = new BrokeredMessage(data);

  client.Send(sendMessage);

  client.OnMessage(message =>
  {
     var dataInfo = message.GetBody<Data>();
     Console.WriteLine($"location: {dataInfo.LocationCode}, phone number: {dataInfo.PhoneNumber}");
  });
</code>```

5.Test the code.

Body:
I stored object in azure service bus now I want to retrieve that object and its values. Here is my code that I used to store object in azure service bus.

class Program
    {
      static void Main(string[] args)
       {
foreach(string file in Directory.EnumerateFiles(@"C:\Users\shubham.mittal\Desktop\xml", "*.xml"))
            {
                string contents = File.ReadAllText(file);
                XDocument doc = XDocument.Parse(contents);
                string locationcode = doc.Root.Element("Customer").Element("Location_Code").Value;
                string Phone_Number = doc.Root.Element("Customer").Element("Phone_Number").Value;
                var connectionString = "Endpoint=sb://namespacename.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=sharedaccesskey";
                var queueName = "shubhamqueue";

                var client = QueueClient.CreateFromConnectionString(connectionString, queueName);
                data d=new data();
                d.location_code=locationcode;
                d.Phone_Number = Phone_Number;
                var message1 = new BrokeredMessage(d);
                client.Send(message1);
            }
        }
    }

Body:
We could get BrokerMessage info with BrokeredMessage.GetBody<T>. So in your case I create a demo and it works on my side.

1.Create a C# console project.

2.Reference the Microsoft Azure Service Bus SDK

3.Add a public Class

public class Data

{
    public string LocationCode { get; set; }
    public string PhoneNumber { get; set; }
}

4. Add the following code to the main function in the Program.cs

  var client =
  QueueClient.CreateFromConnectionString("servicebus connection string", queueName);
  Data data = new Data
  {
      LocationCode =  "test location code",
      PhoneNumber = "test phone number"
  };
  var sendMessage = new BrokeredMessage(data);

  client.Send(sendMessage);

  client.OnMessage(message =>
  {
     var dataInfo = message.GetBody<Data>();
     Console.WriteLine($"location: {dataInfo.LocationCode}, phone number: {dataInfo.PhoneNumber}");
  });

5.Test the code.


问:
How to extract a float from a string
I have a string: string = "2017.5 is halfway through the year". Is there a way to extract this "2017.5" from the string? I tried using string.isdigit(), but that only worked for non-floats.

答:
here is an example using re.match:

```<code>>>> import re
>>> ok = '2017.5 and some stuff'
>>> hmm = re.match(r'[0-9\.]+', ok)
>>> hmm.group()
'2017.5'
</code>```

r'[0-9\.]+' is a regex to extract the group that matches numbers and periods

Title: How to extract a float from a string

Body:
here is an example using re.match:

>>> import re
>>> ok = '2017.5 and some stuff'
>>> hmm = re.match(r'[0-9\.]+', ok)
>>> hmm.group()
'2017.5'

r'[0-9\.]+' is a regex to extract the group that matches numbers and periods


问:
Download 3000+ Images Using C#?
I have a list of around 3000 image URLs, where I need to download them to my desktop.

I'm a web dev, so naturally wrote a little asp.net c# download method to do this but the obvious problem happened and the page timed out before I got hardly any of them.

Was wondering if anyone else knew of a good, quick and robust way of me looping through all the image URL's and downloading them to a folder?  Open to any suggestions, WinForms, batch file although I'm a novice at both.

Any help greatly appreciated

答:
Working on the assumption that this is a one off run once project and as you are a novice with other technologies I would suggest the following:

Rather than try and download all 3000 images in one web request do one image per request.  When the image download is complete redirect to the same page passing the URL of the next image to get as a query string parameter.  Download that one and then repeat until all images are downloaded.

Not what I would call a "production" solution, but if my assumption is correct it is a solution that will have you up an running in no time.

Another fairly simple solution would be to create a simple C# console application that uses WebClient to download each of the images.  The following psuedo code should give you enough to get going:

```<code>List<string> imageUrls = new List<string>();
imageUrls.Add(..... your urls from wherever .....)

foreach(string imageUrl in imagesUrls)
{
    using (WebClient client = new WebClient())
    {
        byte[] raw = client.DownloadData(imageUrl);

        .. write raw .. to file
    }
}
</code>```

Title: Download 3000+ Images Using C#?

Body:
Working on the assumption that this is a one off run once project and as you are a novice with other technologies I would suggest the following:

Rather than try and download all 3000 images in one web request do one image per request.  When the image download is complete redirect to the same page passing the URL of the next image to get as a query string parameter.  Download that one and then repeat until all images are downloaded.

Not what I would call a "production" solution, but if my assumption is correct it is a solution that will have you up an running in no time.

Another fairly simple solution would be to create a simple C# console application that uses WebClient to download each of the images.  The following psuedo code should give you enough to get going:

List<string> imageUrls = new List<string>();
imageUrls.Add(..... your urls from wherever .....)

foreach(string imageUrl in imagesUrls)
{
    using (WebClient client = new WebClient())
    {
        byte[] raw = client.DownloadData(imageUrl);

        .. write raw .. to file
    }
}


答:
If your float is always expressed in decimal notation something like

```<code>>>> import re
>>> re.findall("\d+\.\d+", "2017.5 is halfway through the year")
['2017.5']
</code>```

may suffice.

For parse int and float (point separator) values:

```<code>re.findall( r'\d+\.*\d*', '2017.5 is halfway through the year' )
</code>```

result:

```<code>['2017.5']
</code>```

Title: How to extract a float from a string

Body: I have a string: string = "2017.5 is halfway through the year". Is there a way to extract this "2017.5" from the string? I tried using string.isdigit(), but that only worked for non-floats.

Body:
If your float is always expressed in decimal notation something like

>>> import re
>>> re.findall("\d+\.\d+", "2017.5 is halfway through the year")
['2017.5']

may suffice.

For parse int and float (point separator) values:

re.findall( r'\d+\.*\d*', '2017.5 is halfway through the year' )

result:

['2017.5']


问:
Can an html button launch a different A HREF when held down?
Is it possible to make one html button launch different a href?

For example: if you press the button it launches w3schools.com but if you hold it down it launches google.com instead.

I'm looking for it to work in a web app on a mobile phone, and am thinking it might be doable with the jQuery taphold Event.

Or in other words:

```<code><button><a href="sms:?&body=https://www.google.com">Try Me</a></button>
</code>```

if pressed and

```<code><button><a href="https://www.google.com">Try Me</a></button>
</code>```

if held.

Any help would be much appreciated :)

答:
Using tap and taphold event you can achieve your desired result.

pagecreate event is fired when HTML is created in DOM

$(document).on("pagecreate", function () {
    $.event.special.tap.emitTapOnTaphold = false;
    $("button").on('tap',function(){
        console.log('tap!');
    }).on('taphold',function(){
        console.log('taphold!');
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

<button>Hit me</button></code>```

Just replace the console.log line with window.open('URL') and you are done.

$.event.special.tap.emitTapOnTaphold = false; is used to disable the default click event when you tap and hold the button.

Body:
Is it possible to make one html button launch different a href?

For example: if you press the button it launches w3schools.com but if you hold it down it launches google.com instead.

I'm looking for it to work in a web app on a mobile phone, and am thinking it might be doable with the jQuery taphold Event.

Or in other words:

<button>Try Me</button>

if pressed and

<button>Try Me</button>

if held.

Any help would be much appreciated :)

Body:
Using tap and taphold event you can achieve your desired result.

pagecreate event is fired when HTML is created in DOM

$(document).on("pagecreate", function () {
    $.event.special.tap.emitTapOnTaphold = false;
    $("button").on('tap',function(){
        console.log('tap!');
    }).on('taphold',function(){
        console.log('taphold!');
    });
});

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

<button>Hit me</button>

Just replace the console.log line with window.open('URL') and you are done.

$.event.special.tap.emitTapOnTaphold = false; is used to disable the default click event when you tap and hold the button.


问:
Procedure call with date attribute gives error
I have a stored procedure with attributes like this:

```<code>CREATE PROCEDURE [sp_INUSAV_BASE](
, @dUSAV_DAT DATETIME = NULL
, @dUSAV_DFR DATETIME = NULL
, @dUSAV_DTO DATETIME = NULL
</code>```

I am trying to call this procedure from SSMS with:

```<code>exec sp_inusav_base @dUSAV_DAT = getdate()
</code>```

Which is giving me error:

Why is that error? I've also tried to call like this:

```<code>exec sp_inusav_base  @dUSAV_DAT = (SELECT getdate())
</code>```

But this is also giving me error:

Why is that?

答:
You can't use a function call as a parameter for a stored procedure. You need to assign getdate() to a variable first..

Duplicate of: Incorrect syntax near ')' calling storedproc with GETDATE

Body:
I have a stored procedure with attributes like this:

CREATE PROCEDURE [sp_INUSAV_BASE](
, @dUSAV_DAT DATETIME = NULL
, @dUSAV_DFR DATETIME = NULL
, @dUSAV_DTO DATETIME = NULL

I am trying to call this procedure from SSMS with:

exec sp_inusav_base @dUSAV_DAT = getdate()

Which is giving me error:

Why is that error? I've also tried to call like this:

exec sp_inusav_base  @dUSAV_DAT = (SELECT getdate())

But this is also giving me error:

Why is that?


问:
Pandas Delete Part of String
```<code>>>> df
                       Time
    5/10/2017 (135) 01:05:03
    5/11/2017 (136) 04:05:06
</code>```

Given an input date such as this in a DataFrame, how would I delete the Julian Date, (135) and (136), and remove the whitespace in the middle, so that the output looks like:

```<code>>>> df
                       Time
    5/10/2017 01:05:03
    5/11/2017 04:05:06
</code>```

I've tried:

```<code>df['Time'].replace('(135)','', regex=True, inplace=True)
</code>```

which outputs:

```<code>>>> df
                    Time
0  5/10/2017 () 01:05:03
</code>```

I was wondering what I'm doing wrong here.

答:
You can use replace by regex:

First need escape () by \ because special chars in regex, then match all ints by \d+ and last match zero or more whitespaces after ) by \s*.

```<code>df['Time'] = df['Time'].str.replace("\(\d+\)\s*", '')
print (df)
                 Time
0  5/10/2017 01:05:03
1  5/11/2017 04:05:06
</code>```

And if need convert to datetime:

```<code>df['Time'] = pd.to_datetime(df['Time'].str.replace("\(\d+\)\s*", ''))
print (df)
                 Time
0 2017-05-10 01:05:03
1 2017-05-11 04:05:06
</code>```

EDIT:

In your sample are mising escaping chars \ and is possible use instead \d+ [0-9]+:

```<code>df['Time'].replace('\([0-9]+\)\s*','', regex=True, inplace=True)
print (df)
                 Time
0  5/10/2017 01:05:03
1  5/11/2017 04:05:06
</code>```

Title: Pandas Delete Part of String

Body:
>>> df
                       Time
    5/10/2017 (135) 01:05:03
    5/11/2017 (136) 04:05:06

Given an input date such as this in a DataFrame, how would I delete the Julian Date, (135) and (136), and remove the whitespace in the middle, so that the output looks like:

>>> df
                       Time
    5/10/2017 01:05:03
    5/11/2017 04:05:06

I've tried:

df['Time'].replace('(135)','', regex=True, inplace=True)

which outputs:

>>> df
                    Time
0  5/10/2017 () 01:05:03

I was wondering what I'm doing wrong here.

Body:
You can use replace by regex:

First need escape () by \ because special chars in regex, then match all ints by \d+ and last match zero or more whitespaces after ) by \s*.

df['Time'] = df['Time'].str.replace("\(\d+\)\s*", '')
print (df)
                 Time
0  5/10/2017 01:05:03
1  5/11/2017 04:05:06

And if need convert to datetime:

df['Time'] = pd.to_datetime(df['Time'].str.replace("\(\d+\)\s*", ''))
print (df)
                 Time
0 2017-05-10 01:05:03
1 2017-05-11 04:05:06

EDIT:

In your sample are mising escaping chars \ and is possible use instead \d+ [0-9]+:

df['Time'].replace('\([0-9]+\)\s*','', regex=True, inplace=True)
print (df)
                 Time
0  5/10/2017 01:05:03
1  5/11/2017 04:05:06


问:
Android WhatsApp image sharing
I am developing an application in which i have to share image and text on WhatsApp with in my application.

Is there any best way to do that.

I am capturing my application screen, and need to send that image via WhatsApp

答:
After Spending some time I am able to share Image and Text to whatsapp from my application using this code :

```<code>String smsNumber = "91xxxxxxxxxx"; //without '+'
    try {
        Uri imageUri = null;
        try {
            imageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),
                    BitmapFactory.decodeResource(getResources(), R.drawable.whatsapp_image), null, null));
        } catch (NullPointerException e) {
        }
        Intent shareIntent = new Intent("android.intent.action.MAIN");
        shareIntent.setType("*/*");
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "App - Link");
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        shareIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
        shareIntent.setPackage("com.whatsapp");
        startActivity(Intent.createChooser(shareIntent, "send"));
    } catch (Exception e) {
    }
</code>```

Happy Coding :)

Title: Android WhatsApp image sharing

Body:
After Spending some time I am able to share Image and Text to whatsapp from my application using this code :

String smsNumber = "91xxxxxxxxxx"; //without '+'
    try {
        Uri imageUri = null;
        try {
            imageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),
                    BitmapFactory.decodeResource(getResources(), R.drawable.whatsapp_image), null, null));
        } catch (NullPointerException e) {
        }
        Intent shareIntent = new Intent("android.intent.action.MAIN");
        shareIntent.setType("*/*");
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "App - Link");
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        shareIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
        shareIntent.setPackage("com.whatsapp");
        startActivity(Intent.createChooser(shareIntent, "send"));
    } catch (Exception e) {
    }

Happy Coding :)


问:
Link Additional Files in Visual Studio
I am trying to include stylecop.json in my C# project on Visual Studio 2017. I have figured out how to do this by modifying the .csproj in any text editor:

<AdditionalFiles Include="stylecop.json">
    <Link>stylecop.json</Link>
</AdditionalFiles>
```

I am wondering if there is a way to do this without making any text edits. I understand I can always add it like any other files but that would make a copy of the file within project folder and not link it externally.

答:
You can add a Directory.Build.targets file somewhere in your solution directory (will apply to all projects at or below that directory) with the following contents:

    <Project>
      <ItemGroup>
        <AdditionalFiles Update="@(AdditionalFiles)">
          <Link Condition="'%(Link)' == ''">%(Identity)</Link>
       </AdditionalFiles>
      </ItemGroup>
    </Project>
```
<p>Note that using <code>%(Identity)</code> here isn't optimal for items outside the "project cone" - e.g. when you have <code><AdditionalFiles Include="..\..\foo.bar" /></code>. For this you can use a mechanism similar to what SDK-based projects will do in VS 2017 15.3 / .net core 2.0 tooling:</p>
<pre class="lang-xml prettyprint-override"><code>    <Project>
      <ItemGroup>
        <AdditionalFiles Update="@(AdditionalFiles)">
          <LinkBase Condition="'%(LinkBase)' != ''">$([MSBuild]::EnsureTrailingSlash(%(LinkBase)))</LinkBase>
          <Link Condition="'%(Link)' == '' And !$([MSBuild]::ValueOrDefault('%(FullPath)', '').StartsWith($([MSBuild]::EnsureTrailingSlash($(MSBuildProjectDirectory)))))">%(LinkBase)%(RecursiveDir)%(Filename)%(Extension)</Link>
       </AdditionalFiles>
      </ItemGroup>
    </Project>
</code>```

This will even preserve directory hierarchies of items matched with e.g. ..\shared\**\*.json and the target folder could be set using the LinkBase metadata:

    <AdditionalFiles Include="..\shared\**\*">
      <LinkBase>SharedFiles</LinkBase>
    </AdditionalFiles>
```

Note that you may need to close and re-open the solution after making changes to Directory.Build.targets. In the upcoming VS 2017 15.3 update, changes will be monitored by VS automatically. In previous versions, the file will be cached by VS until the solution is closed.

ContentLicense: CC BY-SA 4.0

Title: Link Additional Files in Visual Studio

Body:
I am trying to include stylecop.json in my C# project on Visual Studio 2017. I have figured out how to do this by modifying the .csproj in any text editor:

<AdditionalFiles Include="stylecop.json">
    <Link>stylecop.json</Link>
</AdditionalFiles>

I am wondering if there is a way to do this without making any text edits. I understand I can always add it like any other files but that would make a copy of the file within project folder and not link it externally.

Body:
You can add a Directory.Build.targets file somewhere in your solution directory (will apply to all projects at or below that directory) with the following contents:

    <Project>
      <ItemGroup>
        <AdditionalFiles Update="@(AdditionalFiles)">
          <Link Condition="'%(Link)' == ''">%(Identity)</Link>
       </AdditionalFiles>
      </ItemGroup>
    </Project>

Note that using %(Identity) here isn't optimal for items outside the "project cone" - e.g. when you have <AdditionalFiles Include="..\..\foo.bar" />. For this you can use a mechanism similar to what SDK-based projects will do in VS 2017 15.3 / .net core 2.0 tooling:

    <Project>
      <ItemGroup>
        <AdditionalFiles Update="@(AdditionalFiles)">
          <LinkBase Condition="'%(LinkBase)' != ''">$([MSBuild]::EnsureTrailingSlash(%(LinkBase)))</LinkBase>
          <Link Condition="'%(Link)' == '' And !$([MSBuild]::ValueOrDefault('%(FullPath)', '').StartsWith($([MSBuild]::EnsureTrailingSlash($(MSBuildProjectDirectory)))))">%(LinkBase)%(RecursiveDir)%(Filename)%(Extension)</Link>
       </AdditionalFiles>
      </ItemGroup>
    </Project>

This will even preserve directory hierarchies of items matched with e.g. ..\shared\**\*.json and the target folder could be set using the LinkBase metadata:

    <AdditionalFiles Include="..\shared\**\*">
      <LinkBase>SharedFiles</LinkBase>
    </AdditionalFiles>

Note that you may need to close and re-open the solution after making changes to Directory.Build.targets. In the upcoming VS 2017 15.3 update, changes will be monitored by VS automatically. In previous versions, the file will be cached by VS until the solution is closed.


问:
Select an option from a dropdown list by onClick on data-table row
I have a data-table when user click on the table row it will get the {{ content.id }} and pop up another child table.

```<code>    <table id="project-content-datatable" class="display table table-hover table-responsive" style="width: 100%">
    <thead>
    <tr>
        <th class="small text-muted text-uppercase"><strong>ID</strong></th>
        <th class="small text-muted text-uppercase"><strong>Name</strong></th>
        <th class="small text-muted text-uppercase"><strong>Description</strong></th>
    </tr>
    </thead>
    <tbody>
    {% for content in content_list %}
        {% if content.search_type.name == searchtype.name %}
            <tr class="text-primary">
                <td class="text-left" style="cursor: pointer"
                    onclick='load_workorder({{ content.id }});'>
                    {{ content.id }}
                </td>
                <td class="text-left" style="cursor: pointer" onclick='load_workorder({{ content.id }});'>
                    {{ content.name }} </td>
                <td class="text-left"> {{ content.description }} </td>
            </tr>
        {% endif %}
    {% endfor content_list %}
    </tbody>

<script>
    function load_workorder(content_id) {
    workorder_path = "/dashboard/workorder_list/" + content_id + "/?format=json";
    workorder_table.api().ajax.url(workorder_path).load();
</script>
</code>```

Inside the child table I have a button to pop up a modal form to create a new content in it, one of its field is a dropdown ForeignKey field.

```<code><div class="modal-body">
<div class="field">
<label>Project Type</label>
<select name="parent_project_content" required="" id="id_parent_project_content">
      <option value="">---------</option>

      <option value="1" selected="">Iron man suit</option>

      <option value="2">SEQ 001</option>

      <option value="4">SEQ 002</option>

    </select>
</div>
</code>```

The <option> value is equal to the {{ content.id }}.I want to hide this field from user so how can I change the <option> to selected based on the {{ content.id }} click by user.

Any help is much appreaciated, Thanks

答:
So if the content.id value matches that of the option in the select dropdown the jQuery for that is pretty straightforward.

Here's a little example but all you need to do is call the selectOption() function and pass through your content.id value:

```<code>// my simplified example to grab a value from the table
$('td').click(function(){
  var value = $(this).text();
  selectOption(value);
});

// pass the value to this function
function selectOption(v){
  $('#id_parent_project_content option[value="'+v+'"]').prop('selected', true);
}
</code>```

Body:
I have a data-table when user click on the table row it will get the {{ content.id }} and pop up another child table.

        ID
        Name
        Description

    {% for content in content_list %}
        {% if content.search_type.name == searchtype.name %}

                    {{ content.id }}

                    {{ content.name }}
                 {{ content.description }}

        {% endif %}
    {% endfor content_list %}

Inside the child table I have a button to pop up a modal form to create a new content in it, one of its field is a dropdown ForeignKey field.

Project Type
<select name="parent_project_content" required="" id="id_parent_project_content">
      <option value="">---------</option>

      <option value="1" selected="">Iron man suit</option>

      <option value="2">SEQ 001</option>

      <option value="4">SEQ 002</option>

    </select>

The <option> value is equal to the {{ content.id }}.I want to hide this field from user so how can I change the <option> to selected based on the {{ content.id }} click by user.

Any help is much appreaciated, Thanks

Body:
So if the content.id value matches that of the option in the select dropdown the jQuery for that is pretty straightforward.

Here's a little example but all you need to do is call the selectOption() function and pass through your content.id value:

// my simplified example to grab a value from the table
$('td').click(function(){
  var value = $(this).text();
  selectOption(value);
});

// pass the value to this function
function selectOption(v){
  $('#id_parent_project_content option[value="'+v+'"]').prop('selected', true);
}


问:
Codeigniter and AJAX delete item from table leaves page blank
I managed to integrate ajax into my pagination and search. it seems to work fine so far. However, when I delete an item and try to refresh the list, my page just returns blank. I was hoping someone could guide me on the proper way to do this as I have tried various methods and want to try to use ajax. Thank you.

My view

```<code><script>
function searchFilter(page_num) {
    page_num = page_num?page_num:0;
    var keywords = $('#search').val();
        console.log(keywords);
        console.log('<?php echo site_url('/AdminDocuments/'); ?>'+page_num);
    $.ajax({
        type: 'POST',
        url: '<?php echo site_url('/AdminDocuments/Search/'); ?>'+page_num,
        data:'page='+page_num+'&keywords='+keywords,
        beforeSend: function () {
            $('.loading').show();
        },
        success: function (html) {
            $('#list').html(html);
            $('.loading').fadeOut("slow");
        }
    });
}

function deleteDocument(input){
    var id = input;
    console.log(id);
    $.ajax({
        type:'POST',
        url:'<?php echo site_url('/AdminDocuments/Delete'); ?>',
        data:'id='+id,
        beforeSend: function () {
            $('.loading').show();
        },
        success:function(result){
            console.log(result);
            $('#list').html(result);
            $('.loading').fadeOut("slow");
        }
    });
}
</script>
<div id="successid" style="display: none;" class="alert alert-success">
    <button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
        ×
    </button>
    Success
</div>
<div id="maincontainer">
    <div id="list" class="row">
        <div class="col-sm-12 table-responsive">
            <table class="table">
                <thead>
                    <tr class="text-left">
                        <td>Period</td>
                        <td>Name</td>
                        <td>Account Number</td>
                        <td></td>
                        <td></td>
                    </tr>
                </thead>
                <tbody>
                    <?php
                        if(!empty($datatable)){
                            foreach ($datatable as $data){
                    ?>
                        <tr class="text-left">
                            <td><?php echo $data['month']."/"; ?><?php echo $data['year']; ?></td>
                            <td><?php echo $data['first_name']; ?> <?php echo $data['last_name']; ?></td>
                            <td><?php echo $data['account_number']; ?></td>
                            <td><a href="<?php echo $data['file_link'];?>"><i class="fa fa-file" aria-hidden="true"></i> View</a></td>
                            <!--<td><a href="<?php echo site_url('AdminDocuments/Delete/'.$data['document_id']);?>"><i class="fa fa-trash" aria-hidden="true"></i> Delete</a></td>-->
                            <td><a href="#" id="delete" onclick="deleteDocument(<?php echo $data['document_id'];?>)"><i class="fa fa-trash" aria-hidden="true"></i> Delete</a></td>
                        </tr>
                    <?php
                        }
                    }else{
                    ?>
                        <tr>
                            <td colspan="7">You do not have any items at the moment</td>
                        </tr>
                    <?php
                    }
                    ?>
                </tbody>
            </table>
        </div>
        <div class="pagination-links pull-right">
            <?php echo $links; ?>
        </div>
    </div>
    <div class="loading" style="display: none;">
        <div class="content">
            <img src="<?php echo base_url().'assets/images/loading/loading.gif'; ?>"/>
        </div>
    </div>
</div>
</code>```

Controller

```<code>public function delete(){
        $id = $this->input->post('id');
        unlink($this->DocumentModel->admin_get($id)['file_location']);
        $result = $this->DocumentModel->delete($id);
        $activity = array(
            'page'=>'Documents',
            'action'=>'Deleted document',
            'created_on'=>date('Y-m-d'),
            'time_on'=>date('h:i:s')
        );
        $this->ActivitiesModel->admin_create($activity);
        if($result===false){
            echo "false";
        }else{
            echo "true";
        }
    }
</code>```

答:
You did a mistake I think. Please comment this line // $('#list').html(result);, because this will replace your #list div with result data

```<code>function deleteDocument(input){
    var id = input;
    console.log(id);
    $.ajax({
        type:'POST',
        url:'<?php echo site_url('/AdminDocuments/Delete'); ?>',
        data:'id='+id,
        beforeSend: function () {
            $('.loading').show();
        },
        success:function(result){
            console.log(result);
            // $('#list').html(result);
            $('.loading').fadeOut("slow");
        }
    });
}
</code>```

Let me know if it not works for you.

Body:
I managed to integrate ajax into my pagination and search. it seems to work fine so far. However, when I delete an item and try to refresh the list, my page just returns blank. I was hoping someone could guide me on the proper way to do this as I have tried various methods and want to try to use ajax. Thank you.

My view

    <button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
        ×
    </button>
    Success

                        Period
                        Name
                        Account Number

                    <?php
                        if(!empty($datatable)){
                            foreach ($datatable as $data){
                    ?>

                            <?php echo $data['month']."/"; ?><?php echo $data['year']; ?>
                            <?php echo $data['first_name']; ?> <?php echo $data['last_name']; ?>
                            <?php echo $data['account_number']; ?>
                            <a href="<?php echo $data['file_link'];?>"> View

                            <a href="#" id="delete" onclick="deleteDocument(<?php echo $data['document_id'];?>)"> Delete

                    <?php
                        }
                    }else{
                    ?>

                            You do not have any items at the moment

                    <?php
                    }
                    ?>

            <?php echo $links; ?>

            <img src="<?php echo base_url().'assets/images/loading/loading.gif'; ?>"/>

Controller

public function delete(){
        $id = $this->input->post('id');
        unlink($this->DocumentModel->admin_get($id)['file_location']);
        $result = $this->DocumentModel->delete($id);
        $activity = array(
            'page'=>'Documents',
            'action'=>'Deleted document',
            'created_on'=>date('Y-m-d'),
            'time_on'=>date('h:i:s')
        );
        $this->ActivitiesModel->admin_create($activity);
        if($result===false){
            echo "false";
        }else{
            echo "true";
        }
    }

Body:
You did a mistake I think. Please comment this line // $('#list').html(result);, because this will replace your #list div with result data

function deleteDocument(input){
    var id = input;
    console.log(id);
    $.ajax({
        type:'POST',
        url:'<?php echo site_url('/AdminDocuments/Delete'); ?>',
        data:'id='+id,
        beforeSend: function () {
            $('.loading').show();
        },
        success:function(result){
            console.log(result);
            // $('#list').html(result);
            $('.loading').fadeOut("slow");
        }
    });
}

Let me know if it not works for you.


问:
How to set text from bundle (toolbar)
How to set text from bundle (toolbar) I have no idea how to set it.

toolbar.xml

```<code><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ToolbarColor">

    <TextView
        android:id="@+id/textView_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="My example"
        android:gravity="center"/>
</android.support.v7.widget.Toolbar>
</code>```

DetailActivity.java

```<code>Bundle bundle = getIntent().getExtras();
        if (bundle!=null){
            String name = bundle.getString("nameCar");
        }

   Toolbar toolbar = (Toolbar) findViewById(R.id.m_tool_bar_detail);
        TextView textToolbar = (TextView) toolbar.findViewById(R.id.textView_toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar()!=null){

            textToolbar.setText(name); ///ERROR(name)
            getSupportActionBar().setIcon(getDrawable(R.drawable.ic_action_name));
        }
</code>```

I've tried textToolbar.setText("xxxxx"); but it gives an error.

I want to get name in bundle to set Textview in toolbar.

答:
No need for bundle for Single text transfer.

step 1.Put content(write a code put string value in first activity)

```<code>    String strnamecar="Maruti";
    Intent intent=new Intent(CurrentActivity.this,NextActivity.class);
    intent.putExtra("nameCar",strnamecar);
    startActivity(intent);
</code>```

step 2.getcontent(get a string value in next activity)

```<code>     Intent carintent=getIntent();
     if(carintent!=null){
        String str=carintent.getStringExtra("nameCar");
     }
</code>```

If u need Bundle then using this

step 1.Put content(write a code put string value in first activity)

```<code>    String strnamecar="Maruti";
    Bundle b=new Bundle();
    b.putString("nameCar",strnamecar);
    Intent intent=new Intent(CurrentActivity.this,NextActivity.class);
    intent.putExtra("nameCar",strnamecar);
    intent.putExtras(b);
    startActivity(intent);
</code>```

step 2.getcontent(get a string value in next activity)

```<code>    Intent carintent=getIntent();
    if(carintent!=null){
        Bundle getb=carintent.getExtras();
        String str=getb.getString("nameCar");
    }
</code>```

Title: How to set text from bundle (toolbar)

Body:
How to set text from bundle (toolbar) I have no idea how to set it.

toolbar.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ToolbarColor">

    <TextView
        android:id="@+id/textView_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="My example"
        android:gravity="center"/>
</android.support.v7.widget.Toolbar>

DetailActivity.java

Bundle bundle = getIntent().getExtras();
        if (bundle!=null){
            String name = bundle.getString("nameCar");
        }

   Toolbar toolbar = (Toolbar) findViewById(R.id.m_tool_bar_detail);
        TextView textToolbar = (TextView) toolbar.findViewById(R.id.textView_toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar()!=null){

            textToolbar.setText(name); ///ERROR(name)
            getSupportActionBar().setIcon(getDrawable(R.drawable.ic_action_name));
        }

I've tried textToolbar.setText("xxxxx"); but it gives an error.

I want to get name in bundle to set Textview in toolbar.

Body:
No need for bundle for Single text transfer.

step 1.Put content(write a code put string value in first activity)

    String strnamecar="Maruti";
    Intent intent=new Intent(CurrentActivity.this,NextActivity.class);
    intent.putExtra("nameCar",strnamecar);
    startActivity(intent);

step 2.getcontent(get a string value in next activity)

     Intent carintent=getIntent();
     if(carintent!=null){
        String str=carintent.getStringExtra("nameCar");
     }

If u need Bundle then using this

step 1.Put content(write a code put string value in first activity)

    String strnamecar="Maruti";
    Bundle b=new Bundle();
    b.putString("nameCar",strnamecar);
    Intent intent=new Intent(CurrentActivity.this,NextActivity.class);
    intent.putExtra("nameCar",strnamecar);
    intent.putExtras(b);
    startActivity(intent);

step 2.getcontent(get a string value in next activity)

    Intent carintent=getIntent();
    if(carintent!=null){
        Bundle getb=carintent.getExtras();
        String str=getb.getString("nameCar");
    }


问:
Multiple Correspondence Analysis with None-Binary Categorical Dummy Variables in Python using mca and prince modules
I am using a python package for multiple correspondence analysis on multiple categorical variable. I am studying a set geological data, here is a sample preview:

```<code>    Quartz  Oxides  Hematite    Limonite    Geothite    Clay    Soil_Type
       1      2       3            4            1        0         A
       2      1       4            3            0        1         B
       3      4       2            1            4        0         A
       4      3       1            2            0        3         C
       0      2       3            4            1        2         D
       1      0       2            4            3        4         C
</code>```

0 - not present, 1 - present in very small (trace) amounts, 2 - present in small amount, 3 - present in medium amount, 4- present in abundant amounts.

my code is as follow:

```<code>geology = pd.read_csv('geology_data.csv')
x = geology[['RigNumber','Quartz','Oxides','Hematite','Limonite','Geothite','Clay']].fillna(0)
y = geology[['Soil_Type']]
print 'Dimensionality Reduction'
mca_ben = mca.mca(x)
print mca_ben
mca_ind = mca.mca(x, benzecri=False)
print mca_ind
print(mca.MCA.__doc__)
</code>```

However I am receiving an error stating:

```<code>Traceback (most recent call last):
  File "C:\Users\root\Desktop\Data\raw data\new raw\merged wit npt\multiclass without productive\parameter propagation\New Predict\clustering-mca.py", line 33, in <module>
    mca_ben = mca.mca(x, ncols=31)
  File "C:\Users\root\AppData\Roaming\Python\Python27\site-packages\mca.py", line 47, in __init__
    self.D_r = numpy.diag(1/numpy.sqrt(self.r))
  File "C:\Python27\lib\site-packages\numpy\lib\twodim_base.py", line 302, in diag
    res = zeros((n, n), v.dtype)
MemoryError
</code>```

I am suspecting that mca is only limited to dichotomous dummy variables.

I also tried to transform each dummy variable into separate columns by using

```<code>x = pd.get_dummies(x)
</code>```

but to no avail, I am still getting the same error.

Note that I do not want to use PCA because of obvious reasons.

I also used another python package called prince and I tried the example found in the documentation, unfortunately I am also receiving an error:

```<code>Traceback (most recent call last):
  File "C:\Users\root\Desktop\Data\raw data\new raw\merged wit npt\multiclass without productive\parameter propagation\New Predict\clustering-mca.py", line 14, in <module>
    mca = prince.MCA(df, n_components=-1)
  File "C:\Python27\lib\site-packages\prince\mca.py", line 42, in __init__
    super(MCA, self).__init__(
TypeError: super() argument 1 must be type, not classobj
</code>```

Any advice?

答: I'm not sure about the first, but the second error is likely because prince is a python3-only package which doesn't support python 2.</p>

Body:
I am using a python package for multiple correspondence analysis on multiple categorical variable. I am studying a set geological data, here is a sample preview:

    Quartz  Oxides  Hematite    Limonite    Geothite    Clay    Soil_Type
       1      2       3            4            1        0         A
       2      1       4            3            0        1         B
       3      4       2            1            4        0         A
       4      3       1            2            0        3         C
       0      2       3            4            1        2         D
       1      0       2            4            3        4         C

0 - not present, 1 - present in very small (trace) amounts, 2 - present in small amount, 3 - present in medium amount, 4- present in abundant amounts.

my code is as follow:

geology = pd.read_csv('geology_data.csv')
x = geology[['RigNumber','Quartz','Oxides','Hematite','Limonite','Geothite','Clay']].fillna(0)
y = geology[['Soil_Type']]
print 'Dimensionality Reduction'
mca_ben = mca.mca(x)
print mca_ben
mca_ind = mca.mca(x, benzecri=False)
print mca_ind
print(mca.MCA.__doc__)

However I am receiving an error stating:

Traceback (most recent call last):
  File "C:\Users\root\Desktop\Data\raw data\new raw\merged wit npt\multiclass without productive\parameter propagation\New Predict\clustering-mca.py", line 33, in <module>
    mca_ben = mca.mca(x, ncols=31)
  File "C:\Users\root\AppData\Roaming\Python\Python27\site-packages\mca.py", line 47, in __init__
    self.D_r = numpy.diag(1/numpy.sqrt(self.r))
  File "C:\Python27\lib\site-packages\numpy\lib\twodim_base.py", line 302, in diag
    res = zeros((n, n), v.dtype)
MemoryError

I am suspecting that mca is only limited to dichotomous dummy variables.

I also tried to transform each dummy variable into separate columns by using

x = pd.get_dummies(x)

but to no avail, I am still getting the same error.

Note that I do not want to use PCA because of obvious reasons.

I also used another python package called prince and I tried the example found in the documentation, unfortunately I am also receiving an error:

Traceback (most recent call last):
  File "C:\Users\root\Desktop\Data\raw data\new raw\merged wit npt\multiclass without productive\parameter propagation\New Predict\clustering-mca.py", line 14, in <module>
    mca = prince.MCA(df, n_components=-1)
  File "C:\Python27\lib\site-packages\prince\mca.py", line 42, in __init__
    super(MCA, self).__init__(
TypeError: super() argument 1 must be type, not classobj

Any advice?