问:
How to display sending messages on right side and receiving messages on left side?
I am working on chat application.Here I am able to send and receive the messages.But i want to display the sending messages on right side and receiving messages on left

var grp = angular.module("grpApp", [])
    .controller("grpCtrl", function ($scope, $state, $http, $stateParams) {
        $scope.uName = $state.params.usermail;
        console.log("bigid" + " " + $scope.digId);
        document.getElementById("frndName").innerHTML = "Group";
        $scope.message = '';
        $scope.messages = [];

        /*...............................image upload......................................*/
        $("#profileImage").click(function (e) {
            $("#imageUpload").click();
        });

        function fasterPreview(uploader) {
            if (uploader.files && uploader.files[0]) {
                $('#profileImage').attr('src',
                    window.URL.createObjectURL(uploader.files[0]));
            }
        }

        $("#imageUpload").change(function () {
            fasterPreview(this);
        });
        /*...............................image upload end................................*/
        var socket = io('http://colourssoftware.com:3000/chat');
        console.log("socket" + socket);
        console.log("devi" + socket);
        var username = $scope.uName;
        var noChat = 0; //setting 0 if all chats histroy is not loaded. 1 if all chats loaded.
        var msgCount = 0; //counting total number of messages displayed.
        var oldInitDone = 0; //it is 0 when old-chats-init is not executed and 1 if executed.
        var roomId; //variable for setting room.
        var toUser;

        //passing data on connection.
        socket.on('connect', function () {
            socket.emit('set-user-data', $scope.uName);
            console.log("emitted" + $scope.uName);
        }); //end of connect event.

        //receiving onlineStack.
        socket.on('onlineStack', function (stack) {
            $('#list').empty();
            $('#list').append($('
').append($('<button id="ubtn" class="btn btn-primary btn btn-sm"></button>').text("Group").css({
                "font-size": "13px"
            })));
            var totalOnline = 0;
            for (var user in stack) {
                //setting txt1. shows users button.
                if (user == $scope.uName) {
                    var txt1 = $('').text(user).css({
                        "font-size": "13px"
                    });
                } else {
                    var txt1 = $('').text(user).css({
                        "font-size": "13px"
                    });
                }
                //setting txt2. shows online status.
                if (stack[user] == "Online") {
                    var txt2 = $('').text("*" + stack[user]).css({
                        "float": "right",
                        "color": "#009933",
                        "font-size": "13px"
                    });
                    totalOnline++;
                } else {
                    var txt2 = $('').text(stack[user]).css({
                        "float": "right",
                        "color": "#a6a6a6",
                        "font-size": "13px"
                    });
                }
                //listing all users.
                $('#list').append($('
').append(txt1, txt2));
                $('#totalOnline').text(totalOnline);
            } //end of for.
            $('#scrl1').scrollTop($('#scrl1').prop("scrollHeight"));
        }); //end of receiving onlineStack event.

        //on button click function.
        $(document).on("click", "#ubtn", function () {

            //                    $scope.toUser = touser;
            console.log("username" + toUser);
            //empty messages.
            $('#messages').empty();
            $('#typing').text("");
            msgCount = 0;
            noChat = 0;
            oldInitDone = 0;

            //assigning friends name to whom messages will send,(in case of group its value is Group).
            toUser = $(this).text();

            //showing and hiding relevant information.
            $('#frndName').text(toUser);
            $('#initMsg').hide();
            $('#chatForm').show(); //showing chat form.
            $('#sendBtn').hide(); //hiding send button to prevent sending of empty messages.

            //assigning two names for room. which helps in one-to-one and also group chat.
            if (toUser == "Group") {
                var currentRoom = "Group-Group";
                var reverseRoom = "Group-Group";
            } else {
                var currentRoom = username + "-" + toUser;
                var reverseRoom = toUser + "-" + username;
            }

            //event to set room and join.
            socket.emit('set-room', {
                name1: currentRoom,
                name2: reverseRoom
            });
            console.log("room" + currentRoom + " " + reverseRoom);
        });
        //event for setting roomId.
        socket.on('set-room', function (room) {
            //empty messages.
            $('#messages').empty();
            $('#typing').text("");
            msgCount = 0;
            noChat = 0;
            oldInitDone = 0;
            //assigning room id to roomId variable. which helps in one-to-one and group chat.
            roomId = room;
            console.log("roomId : " + roomId);
            //event to get chat history on button click or as room is set.
            socket.emit('old-chats-init', {
                room: roomId,
                username: $scope.uName,
                msgCount: msgCount
            });
            $scope.deleteCht = function () {
                $http({
                    url: 'http://colourssoftware.com:3000/clearchat/' + roomId,
                    method: 'DELETE',
                }).then(function (res) {
                    //document.getElementById("scrl2").value = "";
                    //data.result.length = 0;
                    console.log("del chat " + JSON.stringify(res.data));
                }, function (error) {
                    console.log("errorblock" + error);
                });

            }

        }); //end of set-room event.

        //on scroll load more old-chats.
        $('#scrl2').scroll(function () {

            if ($('#scrl2').scrollTop() == 0 && noChat == 0 && oldInitDone == 1) {
                $('#loading').show();
                socket.emit('old-chats', {
                    room: roomId,
                    username: username,
                    msgCount: msgCount
                });
            }

        }); // end of scroll event.

        //listening old-chats event.
        socket.on('old-chats', function (data) {

            if (data.room == roomId) {
                console.log("name" + JSON.stringify(data));
                oldInitDone = 1; //setting value to implies that old-chats first event is done.
                if (data.result.length != 0) {
                    $('#noChat').hide(); //hiding no more chats message.
                    for (var i = 0; i < data.result.length; i++) {
                        //styling of chat message.
                        var chatDate = moment(data.result[i].createdOn).format("MMMM Do YYYY, hh:mm:ss a");
                        var txt1 = $('').text(data.result[i].msgFrom + " : ").css({
                            "color": "#006080"
                        });
                        var txt2 = $('').text(chatDate).css({
                            "float": "right",
                            "color": "#a6a6a6",
                            "font-size": "16px"
                        });
                        var txt3 = $('

').append(txt1, txt2);
                        var txt4 = $('

').text(data.result[i].msg).css({
                            "color": "#000000"
                        });
                        //showing chat in chat box.
                        $('#messages').prepend($('
').append(txt3, txt4));
                        msgCount++;

                    } //end of for.
                    console.log(msgCount);
                } else {
                    $('#noChat').show(); //displaying no more chats message.
                    noChat = 1; //to prevent unnecessary scroll event.
                    console.log("devi");
                }
                //hiding loading bar.
                $('#loading').hide();

                //setting scrollbar position while first 5 chats loads.
                if (msgCount <= 5) {
                    $('#scrl2').scrollTop($('#scrl2').prop("scrollHeight"));
                }
            } //end of outer if.

        }); // end of listening old-chats event.

        // keyup handler.
        $('#myMsg').keyup(function () {
            if ($('#myMsg').val()) {
                $('#sendBtn').show(); //showing send button.
                socket.emit('typing');
            } else {
                $('#sendBtn').hide(); //hiding send button to prevent sending empty messages.
            }
        }); //end of keyup handler.

        //receiving typing message.
        socket.on('typing', function (msg) {
            var setTime;
            //clearing previous setTimeout function.
            clearTimeout(setTime);
            //showing typing message.
            $('#typing').text(msg);
            //showing typing message only for few seconds.
            setTime = setTimeout(function () {
                $('#typing').text("");
            }, 3000);
        }); //end of typing event.

        //sending message.

        $('form').submit(function () {
            socket.emit('chat-msg', {
                msg: $('#myMsg').val(),
                msgTo: toUser,
                date: Date.now()
            });
            console.log("date" + Date.now());
            $('#myMsg').val("");
            $('#sendBtn').hide();
            return false;
        });

        //end of sending message.

        //receiving messages.
        socket.on('chat-msg', function (data) {
            //styling of chat message.
            var chatDate = moment(data.date).format("MMMM Do YYYY, hh:mm:ss a");
            var txt1 = $('').text(data.msgFrom + " : ").css({
                "color": "#006080"
            });
            var txt2 = $('').text(chatDate).css({
                "float": "right",
                "color": "#a6a6a6",
                "font-size": "13px"
            });
            var txt3 = $('

').append(txt1, txt2);
            var txt4 = $('

').text(data.msg).css({
                "color": "#000000"
            });
            //showing chat in chat box.
            $('#messages').append($('
').append(txt3, txt4));
            msgCount = msgCount + 1;
            console.log(msgCount);
            $('#typing').text("");
            $('#scrl2').scrollTop($('#scrl2').prop("scrollHeight"));
        }); //end of receiving messages.

        //on disconnect event.
        //passing data on connection.
        socket.on('disconnect', function () {
            //showing and hiding relevant information.
            $('#list').empty();
            $('#messages').empty();
            $('#typing').text("");
            $('#frndName').text("Disconnected..");
            $('#loading').hide();
            $('#noChat').hide();
            $('#initMsg').show().text("...Please, Refresh Your Page...");
            $('#chatForm').hide();
            msgCount = 0;
            noChat = 0;
        }); //end of connect event.

        //end of function.
        /*...................................socket...................................................*/

        /*  $http.get("http://colourssoftware.com:3000/friendrequests/" + $scope.uName)
                .then(function (response) {

                    $scope.seefrnds = response.data;
                    console.log("response" + "   " + JSON.stringify(response.data));
                    $scope.reqName = response.requestname;

                    //console.log("array print" + JSON.stringify($scope.usersList));
                }, function (response) {
                    console.log("response");
                });
*/

        /*FRIEND REQUESTS*/
        //$scope.userName = $state.params.usermail;
        console.log("username:" + $scope.uName);
        $scope.userId = $state.params.userid;

        $scope.msgFrm = $state.params.usermail;
        $scope.uid = $state.params.user;
        $scope.frndN;
        $scope.msgdata = [];
        $scope.frndData = [];

        var frndata = {
                method: 'GET',
                url: 'http://colourssoftware.com:3000/userslist',
            }
            //document.getElementById("name").innerHTML = "Group";

        $scope.usersList = [];
        $scope.friendsList = [];

        var d = new Date();
        $scope.time = d.toLocaleString();
        console.log("hlooo" + $scope.time);

        /*document.getElementById("myMsg").addEventListener("keyup", function (event) {
    if (event.keyCode == 13) {
        document.getElementById("sendBtn").click();
    }
});*/
        /*getting all the friends accepted by me and who accepts me*/
        $scope.acceptedFrnds = [];
        $scope.getFrnds = function () {

            $http.get("http://colourssoftware.com:3000/Accept_Requests/" + $scope.uid)
                .then(function (response) {
                        console.log("acceptedlist" + JSON.stringify(response));
                        $scope.acceptedFrnds = response.data;
                    },
                    function (response) {
                        console.log("error");

                    });
            $http.get("http://colourssoftware.com:3000/Accepted_By_Others/" + $scope.msgFrm)
                .then(function (response) {
                        console.log("acceptedbyothers" + JSON.stringify(response));
                        $scope.acceptedFrnds = response.data;
                    },
                    function (response) {
                        console.log("error");
                    });

        }
        $scope.fgrp = function (name) {
            document.getElementById("frndName").innerHTML = name;

        }

        $scope.frndgrp = function (frnd) {
            document.getElementById("name").innerHTML = frnd;
            $scope.msgdata = [];
            $scope.frndN = frnd;
            console.log("frndnnnnn" + $scope.frndN);

        }
        console.log("hiauhdurhk" + $scope.frndN);
        /*sending chat messages*/
        $scope.send = function () {
            $scope.msgdata = [];
            //console.log("shgsd" + frnds);
            document.getElementById("submitmsg").disabled = false;

            $scope.msgdata.push($scope.message + " " + " " + $scope.time);

            /*posting the chat messages*/
            var data = {
                "msgFrom": $scope.msgFrm,

                "msgTo": $scope.frndN,
                "msg": $scope.msgdata,
                "room": $scope.msgFrm
            };
            console.log(data);

            var req = {
                method: 'POST',
                url: 'http://colourssoftware.com:3000/chatroute',
                data: data
            }
            $http(req).then(function (response) {
                console.log("hjhuhjh" + JSON.stringify(response.data));
                $scope.msgdata = "";
                $scope.displayFun();

            }, function (response) {
                console.log(response);
            });
            $scope.displayFun = function () {
                    $http.get("http://colourssoftware.com:3000/chathistory")
                        .then(function (response) {

                            $scope.msgdata = response.data;

                            console.log("array print" + JSON.stringify($scope.msgdata));
                        }, function (response) {
                            console.log("error block");

                            // $window.sessionStorage.setItem("Mydata", JSON.stringify($scope.usersList));
                        });
                }
                //            $http.get("http://192.168.2.48:3000/chathistory")
                //        .then(function (response) {
                //
                //            $scope.msgdata = response.data;
                //
                //            console.log("array print" + JSON.stringify($scope.msgdata));
                //
                //           // $window.sessionStorage.setItem("Mydata", JSON.stringify($scope.usersList));
                //        });

            //$scope.msgdata = "";

        }
        $scope.showGrp = function () {
            document.getElementById("frndName").innerHTML = "Group";
            $scope.msgdata = [];
            // var retData = localStorage.getItem("storedData");
            // var retrieveData = JSON.parse(retData);
            //console.log("heloooo" + retrieveData);
            // $scope.msgdata.push(retrieveData);
        }

        $scope.deleteFrnd = function (Id) {
            // $scope.seefrnds.splice(index, 1);
            $scope.Id = Id;
            console.log("show id" + Id);
            $http({
                url: 'http://colourssoftware.com:3000/deletefriends/' + $scope.Id,
                method: 'DELETE',
                data: {
                    id: $scope.Id
                },
                //                headers: {
                //                    "Content-Type": "application/json;charset=utf-8"
                //                }
            }).then(function (res) {
                console.log(JSON.stringify(res.data));

            }, function (error) {
                console.log("errorblock" + error);
            });

        }

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
    <div class="container-fluid">
        <input type="hidden" id="user" value="<%= user.username %>" />
        <div class="row">
            <div class="col-sm-4">
                <div class="panel panel-primary" style="height:500px;overflow: scroll">
                    <div class="panel-heading">
                        <div data-toggle="modal" data-target="#myModal">
                            <img class="img-circle" src="images.jpg" width="80px" height="80px" style="float:left">
                            <span>{{uName}}</span>
                            <h5></h5>
                        </div>
                        <!--model------------------------------------------------------------------->
                        <div id="myModal" class="modal fade" role="dialog">
                            <div class="modal-dialog">

                                <!-- Modal content-->
                                <div class="modal-content">
                                    <div class="modal-header" id="profile-container">
                                        <img class=" img-circle " src="images.jpg" width="80px" height="80px" align='center' id="profileImage">

                                        <button type="button" class="close" data-dismiss="modal">×</button>

                                    </div>
                                    <input id="imageUpload" type="file" name="profile_photo" placeholder="Photo" required="" capture align="center" ng-hide=true>
                                    <div class="modal-body">
                                        <p>Some text in the modal.</p>
                                        <p ng-bind="uName"></p>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                    </div>
                                </div>

                            </div>
                        </div>
                        <!--------------------------------------------------- model close------------------------------------->
                        <br>
                        <br>
                        <br>
                        <input type="text" name="search" placeholder="Search.." class="search focus" id="Searchtab1">
                        <h4>Friends</h4>
                    </div>
                    <div class="panel-body list-group" id="scrl1">
                        <ul id="list" style="cursor: pointer" class="list-group list-group-item"></ul>
                    </div>
                    <!--<div class="panel-footer">
                        <p id="typing"></p>
                    </div>-->
                </div>
            </div>
            <div class=".space"></div>
            <div>
                <div class="col-sm-8">
                    <!--<script>
    document.div.style.backgroundImage = url("p.jpg");
</script>-->
                    <div class="panel panel-primary" style="height:500px;overflow: scroll">
                        <div class="panel-heading">
                            <h4 id="frndName" align="center">Chat Room</h4>
                            <span id="typing"></span>
                            <i class="glyphicon glyphicon-trash" style="float:right;margin-top:-4%" ng-click="deleteCht()" title="clear chat"></i>
                        </div>
                        <div class="panel-body" id="scrl2">
                            <p id="loading">Loading.....</p>
                            <p id="noChat">No More Chats To Display.....</p>
                            <p id="initMsg">!!...Click On User Or Group Button To Start Chat...!!</p>
                            <ul id="messages"></ul>
                        </div>
                        <div class="panel-footer input-group" style="width:100%">

                            <form id="chatForm" action="" onsubmit="return false">
                                <input id="myMsg" class="input-box-send  form-control" ng-model="message" autocomplete="off" style="width:90%" placeholder="Write Message Here.." />
                                <button type="submit" id="sendBtn" class=" btn btn-primary " style="width:10%" ng-disabled="!message" name="btn"><span class="glyphicon glyphicon-send"></span></button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</main></code>```

side.how can I meet that requirement?
Here I am attaching my code.

答:
Just create two classes for right and left aligned blocks. And when you show this add classes to messages. E.g. for messages you sent item--left-align.
However, you have to not forget about pseudo elements

```<code>.item--left-align {
  float: left;
}

.item--left-align:after,
.item--left-align:before {
  content: '';
  display: table;
  clear: both;
}
</code>```

You need it for control on elements that will change their position caused by float

Body:
I am working on chat application.Here I am able to send and receive the messages.But i want to display the sending messages on right side and receiving messages on left

var grp = angular.module("grpApp", [])
    .controller("grpCtrl", function ($scope, $state, $http, $stateParams) {
        $scope.uName = $state.params.usermail;
        console.log("bigid" + " " + $scope.digId);
        document.getElementById("frndName").innerHTML = "Group";
        $scope.message = '';
        $scope.messages = [];

        /*...............................image upload......................................*/
        $("#profileImage").click(function (e) {
            $("#imageUpload").click();
        });

        function fasterPreview(uploader) {
            if (uploader.files && uploader.files[0]) {
                $('#profileImage').attr('src',
                    window.URL.createObjectURL(uploader.files[0]));
            }
        }

        $("#imageUpload").change(function () {
            fasterPreview(this);
        });
        /*...............................image upload end................................*/
        var socket = io('http://colourssoftware.com:3000/chat');
        console.log("socket" + socket);
        console.log("devi" + socket);
        var username = $scope.uName;
        var noChat = 0; //setting 0 if all chats histroy is not loaded. 1 if all chats loaded.
        var msgCount = 0; //counting total number of messages displayed.
        var oldInitDone = 0; //it is 0 when old-chats-init is not executed and 1 if executed.
        var roomId; //variable for setting room.
        var toUser;

        //passing data on connection.
        socket.on('connect', function () {
            socket.emit('set-user-data', $scope.uName);
            console.log("emitted" + $scope.uName);
        }); //end of connect event.

        //receiving onlineStack.
        socket.on('onlineStack', function (stack) {
            $('#list').empty();
            $('#list').append($('
').append($('<button id="ubtn" class="btn btn-primary btn btn-sm"></button>').text("Group").css({
                "font-size": "13px"
            })));
            var totalOnline = 0;
            for (var user in stack) {
                //setting txt1. shows users button.
                if (user == $scope.uName) {
                    var txt1 = $('').text(user).css({
                        "font-size": "13px"
                    });
                } else {
                    var txt1 = $('').text(user).css({
                        "font-size": "13px"
                    });
                }
                //setting txt2. shows online status.
                if (stack[user] == "Online") {
                    var txt2 = $('').text("*" + stack[user]).css({
                        "float": "right",
                        "color": "#009933",
                        "font-size": "13px"
                    });
                    totalOnline++;
                } else {
                    var txt2 = $('').text(stack[user]).css({
                        "float": "right",
                        "color": "#a6a6a6",
                        "font-size": "13px"
                    });
                }
                //listing all users.
                $('#list').append($('
').append(txt1, txt2));
                $('#totalOnline').text(totalOnline);
            } //end of for.
            $('#scrl1').scrollTop($('#scrl1').prop("scrollHeight"));
        }); //end of receiving onlineStack event.

        //on button click function.
        $(document).on("click", "#ubtn", function () {

            //                    $scope.toUser = touser;
            console.log("username" + toUser);
            //empty messages.
            $('#messages').empty();
            $('#typing').text("");
            msgCount = 0;
            noChat = 0;
            oldInitDone = 0;

            //assigning friends name to whom messages will send,(in case of group its value is Group).
            toUser = $(this).text();

            //showing and hiding relevant information.
            $('#frndName').text(toUser);
            $('#initMsg').hide();
            $('#chatForm').show(); //showing chat form.
            $('#sendBtn').hide(); //hiding send button to prevent sending of empty messages.

            //assigning two names for room. which helps in one-to-one and also group chat.
            if (toUser == "Group") {
                var currentRoom = "Group-Group";
                var reverseRoom = "Group-Group";
            } else {
                var currentRoom = username + "-" + toUser;
                var reverseRoom = toUser + "-" + username;
            }

            //event to set room and join.
            socket.emit('set-room', {
                name1: currentRoom,
                name2: reverseRoom
            });
            console.log("room" + currentRoom + " " + reverseRoom);
        });
        //event for setting roomId.
        socket.on('set-room', function (room) {
            //empty messages.
            $('#messages').empty();
            $('#typing').text("");
            msgCount = 0;
            noChat = 0;
            oldInitDone = 0;
            //assigning room id to roomId variable. which helps in one-to-one and group chat.
            roomId = room;
            console.log("roomId : " + roomId);
            //event to get chat history on button click or as room is set.
            socket.emit('old-chats-init', {
                room: roomId,
                username: $scope.uName,
                msgCount: msgCount
            });
            $scope.deleteCht = function () {
                $http({
                    url: 'http://colourssoftware.com:3000/clearchat/' + roomId,
                    method: 'DELETE',
                }).then(function (res) {
                    //document.getElementById("scrl2").value = "";
                    //data.result.length = 0;
                    console.log("del chat " + JSON.stringify(res.data));
                }, function (error) {
                    console.log("errorblock" + error);
                });

            }

        }); //end of set-room event.

        //on scroll load more old-chats.
        $('#scrl2').scroll(function () {

            if ($('#scrl2').scrollTop() == 0 && noChat == 0 && oldInitDone == 1) {
                $('#loading').show();
                socket.emit('old-chats', {
                    room: roomId,
                    username: username,
                    msgCount: msgCount
                });
            }

        }); // end of scroll event.

        //listening old-chats event.
        socket.on('old-chats', function (data) {

            if (data.room == roomId) {
                console.log("name" + JSON.stringify(data));
                oldInitDone = 1; //setting value to implies that old-chats first event is done.
                if (data.result.length != 0) {
                    $('#noChat').hide(); //hiding no more chats message.
                    for (var i = 0; i < data.result.length; i++) {
                        //styling of chat message.
                        var chatDate = moment(data.result[i].createdOn).format("MMMM Do YYYY, hh:mm:ss a");
                        var txt1 = $('').text(data.result[i].msgFrom + " : ").css({
                            "color": "#006080"
                        });
                        var txt2 = $('').text(chatDate).css({
                            "float": "right",
                            "color": "#a6a6a6",
                            "font-size": "16px"
                        });
                        var txt3 = $('

').append(txt1, txt2);
                        var txt4 = $('

').text(data.result[i].msg).css({
                            "color": "#000000"
                        });
                        //showing chat in chat box.
                        $('#messages').prepend($('
').append(txt3, txt4));
                        msgCount++;

                    } //end of for.
                    console.log(msgCount);
                } else {
                    $('#noChat').show(); //displaying no more chats message.
                    noChat = 1; //to prevent unnecessary scroll event.
                    console.log("devi");
                }
                //hiding loading bar.
                $('#loading').hide();

                //setting scrollbar position while first 5 chats loads.
                if (msgCount <= 5) {
                    $('#scrl2').scrollTop($('#scrl2').prop("scrollHeight"));
                }
            } //end of outer if.

        }); // end of listening old-chats event.

        // keyup handler.
        $('#myMsg').keyup(function () {
            if ($('#myMsg').val()) {
                $('#sendBtn').show(); //showing send button.
                socket.emit('typing');
            } else {
                $('#sendBtn').hide(); //hiding send button to prevent sending empty messages.
            }
        }); //end of keyup handler.

        //receiving typing message.
        socket.on('typing', function (msg) {
            var setTime;
            //clearing previous setTimeout function.
            clearTimeout(setTime);
            //showing typing message.
            $('#typing').text(msg);
            //showing typing message only for few seconds.
            setTime = setTimeout(function () {
                $('#typing').text("");
            }, 3000);
        }); //end of typing event.

        //sending message.

        $('form').submit(function () {
            socket.emit('chat-msg', {
                msg: $('#myMsg').val(),
                msgTo: toUser,
                date: Date.now()
            });
            console.log("date" + Date.now());
            $('#myMsg').val("");
            $('#sendBtn').hide();
            return false;
        });

        //end of sending message.

        //receiving messages.
        socket.on('chat-msg', function (data) {
            //styling of chat message.
            var chatDate = moment(data.date).format("MMMM Do YYYY, hh:mm:ss a");
            var txt1 = $('').text(data.msgFrom + " : ").css({
                "color": "#006080"
            });
            var txt2 = $('').text(chatDate).css({
                "float": "right",
                "color": "#a6a6a6",
                "font-size": "13px"
            });
            var txt3 = $('

').append(txt1, txt2);
            var txt4 = $('

').text(data.msg).css({
                "color": "#000000"
            });
            //showing chat in chat box.
            $('#messages').append($('
').append(txt3, txt4));
            msgCount = msgCount + 1;
            console.log(msgCount);
            $('#typing').text("");
            $('#scrl2').scrollTop($('#scrl2').prop("scrollHeight"));
        }); //end of receiving messages.

        //on disconnect event.
        //passing data on connection.
        socket.on('disconnect', function () {
            //showing and hiding relevant information.
            $('#list').empty();
            $('#messages').empty();
            $('#typing').text("");
            $('#frndName').text("Disconnected..");
            $('#loading').hide();
            $('#noChat').hide();
            $('#initMsg').show().text("...Please, Refresh Your Page...");
            $('#chatForm').hide();
            msgCount = 0;
            noChat = 0;
        }); //end of connect event.

        //end of function.
        /*...................................socket...................................................*/

        /*  $http.get("http://colourssoftware.com:3000/friendrequests/" + $scope.uName)
                .then(function (response) {

                    $scope.seefrnds = response.data;
                    console.log("response" + "   " + JSON.stringify(response.data));
                    $scope.reqName = response.requestname;

                    //console.log("array print" + JSON.stringify($scope.usersList));
                }, function (response) {
                    console.log("response");
                });
*/

        /*FRIEND REQUESTS*/
        //$scope.userName = $state.params.usermail;
        console.log("username:" + $scope.uName);
        $scope.userId = $state.params.userid;

        $scope.msgFrm = $state.params.usermail;
        $scope.uid = $state.params.user;
        $scope.frndN;
        $scope.msgdata = [];
        $scope.frndData = [];

        var frndata = {
                method: 'GET',
                url: 'http://colourssoftware.com:3000/userslist',
            }
            //document.getElementById("name").innerHTML = "Group";

        $scope.usersList = [];
        $scope.friendsList = [];

        var d = new Date();
        $scope.time = d.toLocaleString();
        console.log("hlooo" + $scope.time);

        /*document.getElementById("myMsg").addEventListener("keyup", function (event) {
    if (event.keyCode == 13) {
        document.getElementById("sendBtn").click();
    }
});*/
        /*getting all the friends accepted by me and who accepts me*/
        $scope.acceptedFrnds = [];
        $scope.getFrnds = function () {

            $http.get("http://colourssoftware.com:3000/Accept_Requests/" + $scope.uid)
                .then(function (response) {
                        console.log("acceptedlist" + JSON.stringify(response));
                        $scope.acceptedFrnds = response.data;
                    },
                    function (response) {
                        console.log("error");

                    });
            $http.get("http://colourssoftware.com:3000/Accepted_By_Others/" + $scope.msgFrm)
                .then(function (response) {
                        console.log("acceptedbyothers" + JSON.stringify(response));
                        $scope.acceptedFrnds = response.data;
                    },
                    function (response) {
                        console.log("error");
                    });

        }
        $scope.fgrp = function (name) {
            document.getElementById("frndName").innerHTML = name;

        }

        $scope.frndgrp = function (frnd) {
            document.getElementById("name").innerHTML = frnd;
            $scope.msgdata = [];
            $scope.frndN = frnd;
            console.log("frndnnnnn" + $scope.frndN);

        }
        console.log("hiauhdurhk" + $scope.frndN);
        /*sending chat messages*/
        $scope.send = function () {
            $scope.msgdata = [];
            //console.log("shgsd" + frnds);
            document.getElementById("submitmsg").disabled = false;

            $scope.msgdata.push($scope.message + " " + " " + $scope.time);

            /*posting the chat messages*/
            var data = {
                "msgFrom": $scope.msgFrm,

                "msgTo": $scope.frndN,
                "msg": $scope.msgdata,
                "room": $scope.msgFrm
            };
            console.log(data);

            var req = {
                method: 'POST',
                url: 'http://colourssoftware.com:3000/chatroute',
                data: data
            }
            $http(req).then(function (response) {
                console.log("hjhuhjh" + JSON.stringify(response.data));
                $scope.msgdata = "";
                $scope.displayFun();

            }, function (response) {
                console.log(response);
            });
            $scope.displayFun = function () {
                    $http.get("http://colourssoftware.com:3000/chathistory")
                        .then(function (response) {

                            $scope.msgdata = response.data;

                            console.log("array print" + JSON.stringify($scope.msgdata));
                        }, function (response) {
                            console.log("error block");

                            // $window.sessionStorage.setItem("Mydata", JSON.stringify($scope.usersList));
                        });
                }
                //            $http.get("http://192.168.2.48:3000/chathistory")
                //        .then(function (response) {
                //
                //            $scope.msgdata = response.data;
                //
                //            console.log("array print" + JSON.stringify($scope.msgdata));
                //
                //           // $window.sessionStorage.setItem("Mydata", JSON.stringify($scope.usersList));
                //        });

            //$scope.msgdata = "";

        }
        $scope.showGrp = function () {
            document.getElementById("frndName").innerHTML = "Group";
            $scope.msgdata = [];
            // var retData = localStorage.getItem("storedData");
            // var retrieveData = JSON.parse(retData);
            //console.log("heloooo" + retrieveData);
            // $scope.msgdata.push(retrieveData);
        }

        $scope.deleteFrnd = function (Id) {
            // $scope.seefrnds.splice(index, 1);
            $scope.Id = Id;
            console.log("show id" + Id);
            $http({
                url: 'http://colourssoftware.com:3000/deletefriends/' + $scope.Id,
                method: 'DELETE',
                data: {
                    id: $scope.Id
                },
                //                headers: {
                //                    "Content-Type": "application/json;charset=utf-8"
                //                }
            }).then(function (res) {
                console.log(JSON.stringify(res.data));

            }, function (error) {
                console.log("errorblock" + error);
            });

        }

    });

        <input type="hidden" id="user" value="<%= user.username %>" />

                            {{uName}}

                                        <button type="button" class="close" data-dismiss="modal">×</button>

                                    <input id="imageUpload" type="file" name="profile_photo" placeholder="Photo" required="" capture align="center" ng-hide=true>

Some text in the modal.

                                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                        <input type="text" name="search" placeholder="Search.." class="search focus" id="Searchtab1">

Friends

Chat Room

Loading.....

No More Chats To Display.....

!!...Click On User Or Group Button To Start Chat...!!

                            <form id="chatForm" action="" onsubmit="return false">
                                <input id="myMsg" class="input-box-send  form-control" ng-model="message" autocomplete="off" style="width:90%" placeholder="Write Message Here.." />
                                <button type="submit" id="sendBtn" class=" btn btn-primary " style="width:10%" ng-disabled="!message" name="btn"></button>
                            </form>

side.how can I meet that requirement?
Here I am attaching my code.

Body:
Just create two classes for right and left aligned blocks. And when you show this add classes to messages. E.g. for messages you sent item--left-align.
However, you have to not forget about pseudo elements

.item--left-align {
  float: left;
}

.item--left-align:after,
.item--left-align:before {
  content: '';
  display: table;
  clear: both;
}

You need it for control on elements that will change their position caused by float


来源: stackexchange

问:
Simple Vuejs Validation code not working as expected?
I want to post some js objects to backend only if all items are numbers , here is the code :

```<code>  var MyApp = new Vue({

        el: '#my_element',
        data: {
            errors: [],
            votes: []
        },

        methods: {
           send_votes: function(){
             if(this.validate_votes(this.votes) === true){
                 return this.$http.post('/vote', this.votes).then(
                     function (response) {
                          // success message
                     },
                     function (error) {
                          // error message
                      }
                 )
              },
            }

        },

        validate_votes : function (votes) {

                var all_votes_are_number = true;
                $.each(votes, function (item) {
                    if(isNaN(item)){
                        all_votes_are_number = false;
                        MyApp.errors.push('one of votes is not a number');
                    }
                })

                return all_votes_are_number;
         }

   }
</code>```

But My validation to check if one of votes is not a number, does not work and code continue posting and saving data in db! what am I doing wrong ?

Also I want to add more validation:  all votes should be unique.

答:
The issue is your validate_votes function. When using the $.each function, the first argument is the index of the item, and the second argument is the item itself. So if votes was an array equal to ['A','B','C'] you would be checking against 0,1,2. Try the below instead:

```<code>validate_votes : function (votes) {

                var all_votes_are_number = true;
                $.each(votes, function (item, el) {
                    if(isNaN(el)){
                        all_votes_are_number = false;
                        MyApp.errors.push('one of votes is not a number');
                    }
                });

                return all_votes_are_number;
         }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to post some js objects to backend only if all items are numbers , here is the code :

  var MyApp = new Vue({

        el: '#my_element',
        data: {
            errors: [],
            votes: []
        },

        methods: {
           send_votes: function(){
             if(this.validate_votes(this.votes) === true){
                 return this.$http.post('/vote', this.votes).then(
                     function (response) {
                          // success message
                     },
                     function (error) {
                          // error message
                      }
                 )
              },
            }

        },

        validate_votes : function (votes) {

                var all_votes_are_number = true;
                $.each(votes, function (item) {
                    if(isNaN(item)){
                        all_votes_are_number = false;
                        MyApp.errors.push('one of votes is not a number');
                    }
                })

                return all_votes_are_number;
         }

   }

But My validation to check if one of votes is not a number, does not work and code continue posting and saving data in db! what am I doing wrong ?

Also I want to add more validation:  all votes should be unique.

Body:
The issue is your validate_votes function. When using the $.each function, the first argument is the index of the item, and the second argument is the item itself. So if votes was an array equal to ['A','B','C'] you would be checking against 0,1,2. Try the below instead:

validate_votes : function (votes) {

                var all_votes_are_number = true;
                $.each(votes, function (item, el) {
                    if(isNaN(el)){
                        all_votes_are_number = false;
                        MyApp.errors.push('one of votes is not a number');
                    }
                });

                return all_votes_are_number;
         }


问:
How to create hidden folders
I want to create some hidden folders like photo hide app and hide the selected image from gallery or camera to  selected hidden folder.i googled a lot but i couldn't find any solution.please find me a solution..
Thanks in advance</p>

答:
try this code,</p>

```<code>String iconsStoragePath = Environment.getExternalStorageDirectory() + "/.NewFolder";
    File sdIconStorageDir = new File(iconsStoragePath);
    if(!sdIconStorageDir.isDirectory()){
        sdIconStorageDir.mkdirs();//create storage directories, if they don't exist
    }
</code>```

Title: How to create hidden folders

Body:
try this code,

String iconsStoragePath = Environment.getExternalStorageDirectory() + "/.NewFolder";
    File sdIconStorageDir = new File(iconsStoragePath);
    if(!sdIconStorageDir.isDirectory()){
        sdIconStorageDir.mkdirs();//create storage directories, if they don't exist
    }


问:
dataGridView hos go simulate a cell click
I have a dataGridView and I want to simulate that a cell that was clicked.

I want to do this using a button outside the table (a "Send button").

How can I access the row and column that was added?

I thought doing it with:

```<code>dataGridView_MyTable.Rows[rowIndex].Cells[index].Selected = true;
</code>```

However, this didn't work.

答:
I manage to slove it.

This is what i wrote:

```<code>        Int32 GetNextRow = dataGridView_OverrideTable.CurrentCell.RowIndex;

        dataGridView_OverrideTable_CellContentClick(dataGridView_OverrideTable, new DataGridViewCellEventArgs(SEND_COLUMN_INDEX_IN_GRID, GetNextRow));
</code>```

Body:
I have a dataGridView and I want to simulate that a cell that was clicked.

I want to do this using a button outside the table (a "Send button").

How can I access the row and column that was added?

I thought doing it with:

dataGridView_MyTable.Rows[rowIndex].Cells[index].Selected = true;

However, this didn't work.

Body:
I manage to slove it.

This is what i wrote:

        Int32 GetNextRow = dataGridView_OverrideTable.CurrentCell.RowIndex;

        dataGridView_OverrideTable_CellContentClick(dataGridView_OverrideTable, new DataGridViewCellEventArgs(SEND_COLUMN_INDEX_IN_GRID, GetNextRow));


问:
Handling "refresh" or "back" in AJAX to keep "parent" html
So I'm fairly new to AJAX, I have a simple 3 page project which I am using AJAX to transition between pages.

I have an index.html page which loads all the html / body / scripts etc:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax practice</title>

    <link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>

    <div class="" id="wrapper">
    <div class="overlay"></div>
        <header>
            <nav>
                <ul>
                    <li><a class="aboutBtn" href="main.html">Home</a></li>
                    <li><a class="aboutBtn" href="about.html">About</a></li>
                    <li><a class="aboutBtn" href="#">Menu</a></li>
                    <li><a class="aboutBtn" href="#">Contact</a></li>
                </ul>
            </nav>
        </header>

        <div class="page wrapper" id="page">
            <div class="circle" id="black"></div>
            <div class="circle" id="red"></div>
            <div class="circle" id="blue"></div>

            <section class="mainSplash main">

                <div class="mainSplash__content" id="content">

                </div>

            </section>
        </div> <!-- page -->
    </div> <!-- wrapper -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="scripts/index.js"></script>

</body>
</html>
</code>```

and my 2 pages are:

main.html:

```<code><h1 class="mainSplash__header--h1">Main</h1>
</code>```

about.html:

```<code><h1 class="mainSplash__header--h1">About</h1>
</code>```

Here is the AJAX which transitions the pages:

```<code>    $(document).ready(function() {

  var pathname = window.location.pathname; // Returns path only

  console.log(pathname);

    // $('.mainSplash').css('height',$(window).height() - 60);

    $(".aboutBtn").click(function(e) {
        e.preventDefault();
        var pageTitle =  $(this).text();
        var pageUrl = $(this).attr('href');

        changePage(pageUrl, true, pageTitle);
    }); // click

    function changePage(url, bool, pageTitle){
        $('#page').addClass('fadeOut');

        loadContent(url, bool, pageTitle);
    }

    function loadContent(url, bool, pageTitle){
      $.ajax({
        url: './' + url,
        type: 'get',
        contentType: 'html',
        success: function(data){
          $('#page').one('animationend',
            function(e) {
            // load content
            $('#page').removeClass('fadeOut');
            $('#page').addClass('fadeIn');
            $('#content').html(data);
            //$("html").html(data);
            // Change url
            if(url != window.location){
              window.history.pushState({path: url}, pageTitle, url);
            }
          });
                }
        });
    }

  function removeAnimation(){
    $('#page').removeClass('animate');
  }

});
</code>```

So my transitions work fine when I have come from index.html, though when I refresh main.html or about.html, they do not keep the code from index.html (obviously).

My question is:

How do I handle a refresh or back button from my pages without losing the index.html content? Any help or advice is appreciated - thank you in advance.

PS: If anyone knows of any AJAX html page transition examples I would love to know so I can improve my code, as I'm looking for best practice for AJAX transitions!

答:
I would suggest using the browser page hash and on navigation check for the given hash and load the corresponding page.

```<code>let hash = window.location.hash;
</code>```

When the hash changes, your browser adds a new history for that page.

Body:
So I'm fairly new to AJAX, I have a simple 3 page project which I am using AJAX to transition between pages.

I have an index.html page which loads all the html / body / scripts etc:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Ajax practice</title>

    <link rel="stylesheet" href="styles/index.processed.css">

Home

About

Menu

Contact

and my 2 pages are:

main.html:

Main

about.html:

About

Here is the AJAX which transitions the pages:

    $(document).ready(function() {

  var pathname = window.location.pathname; // Returns path only

  console.log(pathname);

    // $('.mainSplash').css('height',$(window).height() - 60);

    $(".aboutBtn").click(function(e) {
        e.preventDefault();
        var pageTitle =  $(this).text();
        var pageUrl = $(this).attr('href');

        changePage(pageUrl, true, pageTitle);
    }); // click

    function changePage(url, bool, pageTitle){
        $('#page').addClass('fadeOut');

        loadContent(url, bool, pageTitle);
    }

    function loadContent(url, bool, pageTitle){
      $.ajax({
        url: './' + url,
        type: 'get',
        contentType: 'html',
        success: function(data){
          $('#page').one('animationend',
            function(e) {
            // load content
            $('#page').removeClass('fadeOut');
            $('#page').addClass('fadeIn');
            $('#content').html(data);
            //$("html").html(data);
            // Change url
            if(url != window.location){
              window.history.pushState({path: url}, pageTitle, url);
            }
          });
                }
        });
    }

  function removeAnimation(){
    $('#page').removeClass('animate');
  }

});

So my transitions work fine when I have come from index.html, though when I refresh main.html or about.html, they do not keep the code from index.html (obviously).

My question is:

How do I handle a refresh or back button from my pages without losing the index.html content? Any help or advice is appreciated - thank you in advance.

PS: If anyone knows of any AJAX html page transition examples I would love to know so I can improve my code, as I'm looking for best practice for AJAX transitions!

Body:
I would suggest using the browser page hash and on navigation check for the given hash and load the corresponding page.

let hash = window.location.hash;

When the hash changes, your browser adds a new history for that page.


问:
Perl pattern matching where we print all matching parts, but only the matching parts (not the rest)
I am looking for a solution to do this in Perl.

Example:
If my string is:

```<code>my $content = 'toto /app/blah titi\nhuh/app/ttt wew';
</code>```

and my pattern is: /app/something I want to get as output in an array: /app/blah and /app/ttt.

(which is basically what grep -E -o '\/app\/[a-z]*' does)

I can't get it work !
I tried:

```<code>my $content = 'toto /app/blah titi\nhuh/app/ttt wew';
$content =~ m/(\/app\/[a-z]*)/;
print "Group: $1 $2\n";
</code>```

but this only prints: /app/blah (not /app/ttt)

and anyway, I don't know how to put the results in a table:

```<code>my (@table) = @_;
</code>```

the table does not contain anything!

thx

答:
I was working on a one liner for some quick bash scripting where Perl would play one part, this worked for me:

```<code>$ echo foo000bar000baz | perl -ne 'for(m/(foo)|(baz)/g){ if ($_ ne "") { print "$_\n"}}'
foo
baz
</code>```

Works with multiline too

```<code>$ echo 'foo
> 123
> bar
> 456
> baz ' | perl -ne 'for(m/(foo)|(baz)/g){ if ($_ ne "") { print "$_\n"}}'
foo
baz
</code>```

Explanation (Forgive and correct my mistakes as I'm not advanced level at Perl):

STDIN piped to perl : Could be anything, like cat $file

m/Regular Expression within parenthesis indicating capture group/g

Make for loop from matches above

Print if match is not "" (empty)

Body:
I am looking for a solution to do this in Perl.

Example:
If my string is:

my $content = 'toto /app/blah titi\nhuh/app/ttt wew';

and my pattern is: /app/something I want to get as output in an array: /app/blah and /app/ttt.

(which is basically what grep -E -o '\/app\/[a-z]*' does)

I can't get it work !
I tried:

my $content = 'toto /app/blah titi\nhuh/app/ttt wew';
$content =~ m/(\/app\/[a-z]*)/;
print "Group: $1 $2\n";

but this only prints: /app/blah (not /app/ttt)

and anyway, I don't know how to put the results in a table:

my (@table) = @_;

the table does not contain anything!

thx

Body:
I was working on a one liner for some quick bash scripting where Perl would play one part, this worked for me:

$ echo foo000bar000baz | perl -ne 'for(m/(foo)|(baz)/g){ if ($_ ne "") { print "$_\n"}}'
foo
baz

Works with multiline too

$ echo 'foo
> 123
> bar
> 456
> baz ' | perl -ne 'for(m/(foo)|(baz)/g){ if ($_ ne "") { print "$_\n"}}'
foo
baz

Explanation (Forgive and correct my mistakes as I'm not advanced level at Perl):

STDIN piped to perl : Could be anything, like cat $file

m/Regular Expression within parenthesis indicating capture group/g

Make for loop from matches above

Print if match is not "" (empty)


问:
PayPal Express Checkout.js - send custom parameters
How I can send a custom parameter to new Paypal Express checkout. I need to send the booking_id and get the same after success full payment.

I have gone through the paypal official document, but can't found how we can send?

Please see below is my file code:

```<code><!DOCTYPE html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <script src="https://www.paypalobjects.com/api/checkout.js"></script>
</head>
<body>
    <div id="paypal-button-container"></div>
    <script>
        paypal.Button.render({
            env: 'sandbox', // sandbox | production
            client: {
                sandbox:    'AYbCnvobq09Ptmsd1TRp3019CMrSTyaAmrHNv6ox0jl86H9OZFmGCPqHqqfPtqpTYTiIuy_e5UGnclMw',
                //production: '<insert production client id>'
            },
            commit: true,
            payment: function(data, actions) {
                return actions.payment.create({
                    payment: {
                        transactions: [
                            {
                                amount: { total: '0.01', currency: 'USD' }
                            }
                        ]
                    }
                });
            },
            onAuthorize: function(data, actions) {
                return actions.payment.execute().then(function() {
                    window.alert('Payment Complete!');
                });
            }
        }, '#paypal-button-container');
    </script>
</body>
</code>```

答:
I have solved issues, we can pass the parameters in the payment method. like the below code:

```<code>payment: function(data, actions) {
    return actions.payment.create({
        payment: {
            transactions: [
                {
                    amount: { total: '10', currency: 'USD' },
                    custom: '1452'
                }
            ]
        }
    });
},
</code>```

Hope this will help for developers.

Body:
How I can send a custom parameter to new Paypal Express checkout. I need to send the booking_id and get the same after success full payment.

I have gone through the paypal official document, but can't found how we can send?

Please see below is my file code:

<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

Body:
I have solved issues, we can pass the parameters in the payment method. like the below code:

payment: function(data, actions) {
    return actions.payment.create({
        payment: {
            transactions: [
                {
                    amount: { total: '10', currency: 'USD' },
                    custom: '1452'
                }
            ]
        }
    });
},

Hope this will help for developers.


问:
Convert json_objects to array
I have this query

```<code>SELECT json_object('image_name', image_name, 'iid', iid)
FROM `posts_images`
WHERE `pid` = '62'
</code>```

That result in this

Image:

can I convert these result into one line JSON array in same query?

答:
You can do something like below:</p>

```<code>$query = "SELECT json_object('image_name', image_name, 'iid', iid) FROM `posts_images` WHERE `pid` = '62'";
$result = mysqli_query($query);
$data = array();
while($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}
print json_encode($data);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Convert json_objects to array

Body:
I have this query

SELECT json_object('image_name', image_name, 'iid', iid)
FROM `posts_images`
WHERE `pid` = '62'

That result in this

Image:

can I convert these result into one line JSON array in same query?

Body:
You can do something like below:

$query = "SELECT json_object('image_name', image_name, 'iid', iid) FROM `posts_images` WHERE `pid` = '62'";
$result = mysqli_query($query);
$data = array();
while($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}
print json_encode($data);


问:
In This Case Different Between For Loop and While loop?
```<code><?php
while($d=mysqli_fetch_assoc($data))
?>
</code>```

And

```<code><?php
for(;$d=mysqli_fetch_assoc($data);)
?>
</code>```

this both loop are work same but any different between while and for loop?

答:
for lets you add an initial statement and a statement that's executed every loop. If you remove those, then yes, it should result in an identical behaviour as a while loop. The syntax is:

```<code>for (initial; comparison; every_loop)
</code>```

If you want to use some sort of iterator-like variable, which changes every loop, it's often easier to use for. Do note though that you ALWAYS can recreate a for-loop using a while-loop. All you need to do is to add the initial statement outside the loop and the "every_loop"-statement at the end of the loop. But because these two are so common, it's often easier to just use for. An example of this is:

```<code>for ($i = 0; $i < 10; $i++)
{
    echo $i;
}
</code>```

...which can be rewritten as...

```<code>$i = 0; //initial
while($i < 10)
{
    echo $i;
    $i++; //every_loop
}
</code>```

Body:
<?php
while($d=mysqli_fetch_assoc($data))
?>

And

<?php
for(;$d=mysqli_fetch_assoc($data);)
?>

this both loop are work same but any different between while and for loop?

Body:
for lets you add an initial statement and a statement that's executed every loop. If you remove those, then yes, it should result in an identical behaviour as a while loop. The syntax is:

for (initial; comparison; every_loop)

If you want to use some sort of iterator-like variable, which changes every loop, it's often easier to use for. Do note though that you ALWAYS can recreate a for-loop using a while-loop. All you need to do is to add the initial statement outside the loop and the "every_loop"-statement at the end of the loop. But because these two are so common, it's often easier to just use for. An example of this is:

for ($i = 0; $i < 10; $i++)
{
    echo $i;
}

...which can be rewritten as...

$i = 0; //initial
while($i < 10)
{
    echo $i;
    $i++; //every_loop
}


答:
Using a combination of:

display: flex; flex-direction: column; on parent

align-self: flex-endon children

everything should be really easy to achieve.

.chat {
  display: flex;

  /* column reverse to have chat-style message ordering*/
  flex-direction: column-reverse;
}

.message {
  border: 1px solid gray;
  margin: 5px;
  padding: 5px;
  width: 60%;
}

.message.is-sent {
  background: cyan;

  /* use align-self */
  align-self: flex-end;
}
.message.is-received {
  background: pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="chat">

<div class="message is-received">
 Received - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus corporis delectus in mollitia nulla numquam perferendis, porro provident sint ullam! A eos ipsum maiores quisquam vero? Enim nihil quisquam rerum.
</div>

<div class="message is-sent">
 Sent - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus corporis delectus in mollitia nulla numquam perferendis, porro provident sint ullam! A eos ipsum maiores quisquam vero? Enim nihil quisquam rerum.
</div>

</div></code>```

Title: How to display sending messages on right side and receiving messages on left side?

Body:
I am working on chat application.Here I am able to send and receive the messages.But i want to display the sending messages on right side and receiving messages on left

var grp = angular.module("grpApp", [])
    .controller("grpCtrl", function ($scope, $state, $http, $stateParams) {
        $scope.uName = $state.params.usermail;
        console.log("bigid" + " " + $scope.digId);
        document.getElementById("frndName").innerHTML = "Group";
        $scope.message = '';
        $scope.messages = [];

        /*...............................image upload......................................*/
        $("#profileImage").click(function (e) {
            $("#imageUpload").click();
        });

        function fasterPreview(uploader) {
            if (uploader.files && uploader.files[0]) {
                $('#profileImage').attr('src',
                    window.URL.createObjectURL(uploader.files[0]));
            }
        }

        $("#imageUpload").change(function () {
            fasterPreview(this);
        });
        /*...............................image upload end................................*/
        var socket = io('http://colourssoftware.com:3000/chat');
        console.log("socket" + socket);
        console.log("devi" + socket);
        var username = $scope.uName;
        var noChat = 0; //setting 0 if all chats histroy is not loaded. 1 if all chats loaded.
        var msgCount = 0; //counting total number of messages displayed.
        var oldInitDone = 0; //it is 0 when old-chats-init is not executed and 1 if executed.
        var roomId; //variable for setting room.
        var toUser;

        //passing data on connection.
        socket.on('connect', function () {
            socket.emit('set-user-data', $scope.uName);
            console.log("emitted" + $scope.uName);
        }); //end of connect event.

        //receiving onlineStack.
        socket.on('onlineStack', function (stack) {
            $('#list').empty();
            $('#list').append($('
').append($('<button id="ubtn" class="btn btn-primary btn btn-sm"></button>').text("Group").css({
                "font-size": "13px"
            })));
            var totalOnline = 0;
            for (var user in stack) {
                //setting txt1. shows users button.
                if (user == $scope.uName) {
                    var txt1 = $('').text(user).css({
                        "font-size": "13px"
                    });
                } else {
                    var txt1 = $('').text(user).css({
                        "font-size": "13px"
                    });
                }
                //setting txt2. shows online status.
                if (stack[user] == "Online") {
                    var txt2 = $('').text("*" + stack[user]).css({
                        "float": "right",
                        "color": "#009933",
                        "font-size": "13px"
                    });
                    totalOnline++;
                } else {
                    var txt2 = $('').text(stack[user]).css({
                        "float": "right",
                        "color": "#a6a6a6",
                        "font-size": "13px"
                    });
                }
                //listing all users.
                $('#list').append($('
').append(txt1, txt2));
                $('#totalOnline').text(totalOnline);
            } //end of for.
            $('#scrl1').scrollTop($('#scrl1').prop("scrollHeight"));
        }); //end of receiving onlineStack event.

        //on button click function.
        $(document).on("click", "#ubtn", function () {

            //                    $scope.toUser = touser;
            console.log("username" + toUser);
            //empty messages.
            $('#messages').empty();
            $('#typing').text("");
            msgCount = 0;
            noChat = 0;
            oldInitDone = 0;

            //assigning friends name to whom messages will send,(in case of group its value is Group).
            toUser = $(this).text();

            //showing and hiding relevant information.
            $('#frndName').text(toUser);
            $('#initMsg').hide();
            $('#chatForm').show(); //showing chat form.
            $('#sendBtn').hide(); //hiding send button to prevent sending of empty messages.

            //assigning two names for room. which helps in one-to-one and also group chat.
            if (toUser == "Group") {
                var currentRoom = "Group-Group";
                var reverseRoom = "Group-Group";
            } else {
                var currentRoom = username + "-" + toUser;
                var reverseRoom = toUser + "-" + username;
            }

            //event to set room and join.
            socket.emit('set-room', {
                name1: currentRoom,
                name2: reverseRoom
            });
            console.log("room" + currentRoom + " " + reverseRoom);
        });
        //event for setting roomId.
        socket.on('set-room', function (room) {
            //empty messages.
            $('#messages').empty();
            $('#typing').text("");
            msgCount = 0;
            noChat = 0;
            oldInitDone = 0;
            //assigning room id to roomId variable. which helps in one-to-one and group chat.
            roomId = room;
            console.log("roomId : " + roomId);
            //event to get chat history on button click or as room is set.
            socket.emit('old-chats-init', {
                room: roomId,
                username: $scope.uName,
                msgCount: msgCount
            });
            $scope.deleteCht = function () {
                $http({
                    url: 'http://colourssoftware.com:3000/clearchat/' + roomId,
                    method: 'DELETE',
                }).then(function (res) {
                    //document.getElementById("scrl2").value = "";
                    //data.result.length = 0;
                    console.log("del chat " + JSON.stringify(res.data));
                }, function (error) {
                    console.log("errorblock" + error);
                });

            }

        }); //end of set-room event.

        //on scroll load more old-chats.
        $('#scrl2').scroll(function () {

            if ($('#scrl2').scrollTop() == 0 && noChat == 0 && oldInitDone == 1) {
                $('#loading').show();
                socket.emit('old-chats', {
                    room: roomId,
                    username: username,
                    msgCount: msgCount
                });
            }

        }); // end of scroll event.

        //listening old-chats event.
        socket.on('old-chats', function (data) {

            if (data.room == roomId) {
                console.log("name" + JSON.stringify(data));
                oldInitDone = 1; //setting value to implies that old-chats first event is done.
                if (data.result.length != 0) {
                    $('#noChat').hide(); //hiding no more chats message.
                    for (var i = 0; i < data.result.length; i++) {
                        //styling of chat message.
                        var chatDate = moment(data.result[i].createdOn).format("MMMM Do YYYY, hh:mm:ss a");
                        var txt1 = $('').text(data.result[i].msgFrom + " : ").css({
                            "color": "#006080"
                        });
                        var txt2 = $('').text(chatDate).css({
                            "float": "right",
                            "color": "#a6a6a6",
                            "font-size": "16px"
                        });
                        var txt3 = $('

').append(txt1, txt2);
                        var txt4 = $('

').text(data.result[i].msg).css({
                            "color": "#000000"
                        });
                        //showing chat in chat box.
                        $('#messages').prepend($('
').append(txt3, txt4));
                        msgCount++;

                    } //end of for.
                    console.log(msgCount);
                } else {
                    $('#noChat').show(); //displaying no more chats message.
                    noChat = 1; //to prevent unnecessary scroll event.
                    console.log("devi");
                }
                //hiding loading bar.
                $('#loading').hide();

                //setting scrollbar position while first 5 chats loads.
                if (msgCount <= 5) {
                    $('#scrl2').scrollTop($('#scrl2').prop("scrollHeight"));
                }
            } //end of outer if.

        }); // end of listening old-chats event.

        // keyup handler.
        $('#myMsg').keyup(function () {
            if ($('#myMsg').val()) {
                $('#sendBtn').show(); //showing send button.
                socket.emit('typing');
            } else {
                $('#sendBtn').hide(); //hiding send button to prevent sending empty messages.
            }
        }); //end of keyup handler.

        //receiving typing message.
        socket.on('typing', function (msg) {
            var setTime;
            //clearing previous setTimeout function.
            clearTimeout(setTime);
            //showing typing message.
            $('#typing').text(msg);
            //showing typing message only for few seconds.
            setTime = setTimeout(function () {
                $('#typing').text("");
            }, 3000);
        }); //end of typing event.

        //sending message.

        $('form').submit(function () {
            socket.emit('chat-msg', {
                msg: $('#myMsg').val(),
                msgTo: toUser,
                date: Date.now()
            });
            console.log("date" + Date.now());
            $('#myMsg').val("");
            $('#sendBtn').hide();
            return false;
        });

        //end of sending message.

        //receiving messages.
        socket.on('chat-msg', function (data) {
            //styling of chat message.
            var chatDate = moment(data.date).format("MMMM Do YYYY, hh:mm:ss a");
            var txt1 = $('').text(data.msgFrom + " : ").css({
                "color": "#006080"
            });
            var txt2 = $('').text(chatDate).css({
                "float": "right",
                "color": "#a6a6a6",
                "font-size": "13px"
            });
            var txt3 = $('

').append(txt1, txt2);
            var txt4 = $('

').text(data.msg).css({
                "color": "#000000"
            });
            //showing chat in chat box.
            $('#messages').append($('
').append(txt3, txt4));
            msgCount = msgCount + 1;
            console.log(msgCount);
            $('#typing').text("");
            $('#scrl2').scrollTop($('#scrl2').prop("scrollHeight"));
        }); //end of receiving messages.

        //on disconnect event.
        //passing data on connection.
        socket.on('disconnect', function () {
            //showing and hiding relevant information.
            $('#list').empty();
            $('#messages').empty();
            $('#typing').text("");
            $('#frndName').text("Disconnected..");
            $('#loading').hide();
            $('#noChat').hide();
            $('#initMsg').show().text("...Please, Refresh Your Page...");
            $('#chatForm').hide();
            msgCount = 0;
            noChat = 0;
        }); //end of connect event.

        //end of function.
        /*...................................socket...................................................*/

        /*  $http.get("http://colourssoftware.com:3000/friendrequests/" + $scope.uName)
                .then(function (response) {

                    $scope.seefrnds = response.data;
                    console.log("response" + "   " + JSON.stringify(response.data));
                    $scope.reqName = response.requestname;

                    //console.log("array print" + JSON.stringify($scope.usersList));
                }, function (response) {
                    console.log("response");
                });
*/

        /*FRIEND REQUESTS*/
        //$scope.userName = $state.params.usermail;
        console.log("username:" + $scope.uName);
        $scope.userId = $state.params.userid;

        $scope.msgFrm = $state.params.usermail;
        $scope.uid = $state.params.user;
        $scope.frndN;
        $scope.msgdata = [];
        $scope.frndData = [];

        var frndata = {
                method: 'GET',
                url: 'http://colourssoftware.com:3000/userslist',
            }
            //document.getElementById("name").innerHTML = "Group";

        $scope.usersList = [];
        $scope.friendsList = [];

        var d = new Date();
        $scope.time = d.toLocaleString();
        console.log("hlooo" + $scope.time);

        /*document.getElementById("myMsg").addEventListener("keyup", function (event) {
    if (event.keyCode == 13) {
        document.getElementById("sendBtn").click();
    }
});*/
        /*getting all the friends accepted by me and who accepts me*/
        $scope.acceptedFrnds = [];
        $scope.getFrnds = function () {

            $http.get("http://colourssoftware.com:3000/Accept_Requests/" + $scope.uid)
                .then(function (response) {
                        console.log("acceptedlist" + JSON.stringify(response));
                        $scope.acceptedFrnds = response.data;
                    },
                    function (response) {
                        console.log("error");

                    });
            $http.get("http://colourssoftware.com:3000/Accepted_By_Others/" + $scope.msgFrm)
                .then(function (response) {
                        console.log("acceptedbyothers" + JSON.stringify(response));
                        $scope.acceptedFrnds = response.data;
                    },
                    function (response) {
                        console.log("error");
                    });

        }
        $scope.fgrp = function (name) {
            document.getElementById("frndName").innerHTML = name;

        }

        $scope.frndgrp = function (frnd) {
            document.getElementById("name").innerHTML = frnd;
            $scope.msgdata = [];
            $scope.frndN = frnd;
            console.log("frndnnnnn" + $scope.frndN);

        }
        console.log("hiauhdurhk" + $scope.frndN);
        /*sending chat messages*/
        $scope.send = function () {
            $scope.msgdata = [];
            //console.log("shgsd" + frnds);
            document.getElementById("submitmsg").disabled = false;

            $scope.msgdata.push($scope.message + " " + " " + $scope.time);

            /*posting the chat messages*/
            var data = {
                "msgFrom": $scope.msgFrm,

                "msgTo": $scope.frndN,
                "msg": $scope.msgdata,
                "room": $scope.msgFrm
            };
            console.log(data);

            var req = {
                method: 'POST',
                url: 'http://colourssoftware.com:3000/chatroute',
                data: data
            }
            $http(req).then(function (response) {
                console.log("hjhuhjh" + JSON.stringify(response.data));
                $scope.msgdata = "";
                $scope.displayFun();

            }, function (response) {
                console.log(response);
            });
            $scope.displayFun = function () {
                    $http.get("http://colourssoftware.com:3000/chathistory")
                        .then(function (response) {

                            $scope.msgdata = response.data;

                            console.log("array print" + JSON.stringify($scope.msgdata));
                        }, function (response) {
                            console.log("error block");

                            // $window.sessionStorage.setItem("Mydata", JSON.stringify($scope.usersList));
                        });
                }
                //            $http.get("http://192.168.2.48:3000/chathistory")
                //        .then(function (response) {
                //
                //            $scope.msgdata = response.data;
                //
                //            console.log("array print" + JSON.stringify($scope.msgdata));
                //
                //           // $window.sessionStorage.setItem("Mydata", JSON.stringify($scope.usersList));
                //        });

            //$scope.msgdata = "";

        }
        $scope.showGrp = function () {
            document.getElementById("frndName").innerHTML = "Group";
            $scope.msgdata = [];
            // var retData = localStorage.getItem("storedData");
            // var retrieveData = JSON.parse(retData);
            //console.log("heloooo" + retrieveData);
            // $scope.msgdata.push(retrieveData);
        }

        $scope.deleteFrnd = function (Id) {
            // $scope.seefrnds.splice(index, 1);
            $scope.Id = Id;
            console.log("show id" + Id);
            $http({
                url: 'http://colourssoftware.com:3000/deletefriends/' + $scope.Id,
                method: 'DELETE',
                data: {
                    id: $scope.Id
                },
                //                headers: {
                //                    "Content-Type": "application/json;charset=utf-8"
                //                }
            }).then(function (res) {
                console.log(JSON.stringify(res.data));

            }, function (error) {
                console.log("errorblock" + error);
            });

        }

    });

        <input type="hidden" id="user" value="<%= user.username %>" />

                            {{uName}}

                                        <button type="button" class="close" data-dismiss="modal">×</button>

                                    <input id="imageUpload" type="file" name="profile_photo" placeholder="Photo" required="" capture align="center" ng-hide=true>

Some text in the modal.

                                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                        <input type="text" name="search" placeholder="Search.." class="search focus" id="Searchtab1">

Friends

Chat Room

Loading.....

No More Chats To Display.....

!!...Click On User Or Group Button To Start Chat...!!

                            <form id="chatForm" action="" onsubmit="return false">
                                <input id="myMsg" class="input-box-send  form-control" ng-model="message" autocomplete="off" style="width:90%" placeholder="Write Message Here.." />
                                <button type="submit" id="sendBtn" class=" btn btn-primary " style="width:10%" ng-disabled="!message" name="btn"></button>
                            </form>

side.how can I meet that requirement?
Here I am attaching my code.

Body:
Using a combination of:

display: flex; flex-direction: column; on parent

align-self: flex-endon children

everything should be really easy to achieve.

.chat {
  display: flex;

  /* column reverse to have chat-style message ordering*/
  flex-direction: column-reverse;
}

.message {
  border: 1px solid gray;
  margin: 5px;
  padding: 5px;
  width: 60%;
}

.message.is-sent {
  background: cyan;

  /* use align-self */
  align-self: flex-end;
}
.message.is-received {
  background: pink;
}

<div class="chat">

<div class="message is-received">
 Received - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus corporis delectus in mollitia nulla numquam perferendis, porro provident sint ullam! A eos ipsum maiores quisquam vero? Enim nihil quisquam rerum.
</div>

<div class="message is-sent">
 Sent - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus corporis delectus in mollitia nulla numquam perferendis, porro provident sint ullam! A eos ipsum maiores quisquam vero? Enim nihil quisquam rerum.
</div>

</div>


问:
C++/CLI convert existing application do managed code
I've got an existing application written in Borland C++ Builder. My client wants it rewritten in C#/WPF. This requires a lot of work and is a complex task because I need to rewrite the whole (huge) algorithm. I was thinking of a way to reuse the code and to be able to create only GUI in C#/WPF. Is this possible? Would that be easy? How can I make C++ classes visible to .NET ?

If you could give me brief answers with some links/examples I would be grateful.

答:
You can wrap your old C++ code in a C++/CLI wrapper and build it into a DLL file. It should then be visible in any .NET project.

Depending on your algorithm/function structure, this may change a little, but the basic form, and the way I did this, is the following. Keep in mind this is a VERY basic example, but I tried to include the key points:

1. Define the CLI wrapper

```<code>using namespace System;

#include "myAlgorithmClass"

public ref class MyCLIWrapperClass //the 'ref' keyword specifies that this is a managed class
{
public:

    MyCLIWrapperClass(); //Constructor

    //function definitions are the same, though some types,
    //like string, change a little. Here's an example:
    String ^ GetAString(); //the "String" is the .NET "System.String" and the ^ is sort of a pointer for managed classes

    //int, double, long, char, etc do not need to be specified as managed.
    //.NET code will know how to handle these types.

    //Here you want to define some functions in the wrapper that will call
    //the functions from your un-managed class. Here are some examples:
    //Say that your functions in the Algorithm class are int Func1, double Func2, and std::string Func3:
    int Func1();
    double Func2();
    String ^ Func3();

private:
    //All private functions and members here
    myAlgorithmClass algor;
};
</code>```

2. Implement the wrapper class

```<code>using namespace System;
#include <string> //For the string function ex. below
#include "myAlgorithmClass"

MyCLIWrapperClass::MyCLIWrapperClass()
{
    algor = myAlgorithmClass(); //create instance of your un-managed class
}

int MyCLIWrapperClass::Func1()
{
    return algor.Func1(); //Call the un-managed class function.
}

double MyCLIWrapperClass::Func2()
{
    return algor.Func2(); //Call the un-managed class function.
}

String ^ MyCLIWrapperClass::Func3()
{
    //Converting a std::string to a System.String requires some conversion
    //but I'm sure you can find that somewhere on Google or here on SO

    String ^ myString = "";
    std::string myUnmanagedString = algor.Func3(); //Call the un-managed class function.

    //Convert myUnmanagedString from std::string to System.String here

    return myString;
}
</code>```

After you write the wrapper class and compile it into a class library you can create a reference to the .DLL file in a C# project and C# should see the managed wrapper class and all its public functions.

Another thing to note is that if you are creating new managed objects in C++ you use the keyword "gcnew" instead of "new". So a new string would be String ^ someString = gcnew String();

Finally, here are some links to some things about CLI that may help:

CLI - Wikipedia

CLI - Code Project

CLI - FunctionX

ContentLicense: CC BY-SA 2.5

Body:
You can wrap your old C++ code in a C++/CLI wrapper and build it into a DLL file. It should then be visible in any .NET project.

Depending on your algorithm/function structure, this may change a little, but the basic form, and the way I did this, is the following. Keep in mind this is a VERY basic example, but I tried to include the key points:

1. Define the CLI wrapper

using namespace System;

#include "myAlgorithmClass"

public ref class MyCLIWrapperClass //the 'ref' keyword specifies that this is a managed class
{
public:

    MyCLIWrapperClass(); //Constructor

    //function definitions are the same, though some types,
    //like string, change a little. Here's an example:
    String ^ GetAString(); //the "String" is the .NET "System.String" and the ^ is sort of a pointer for managed classes

    //int, double, long, char, etc do not need to be specified as managed.
    //.NET code will know how to handle these types.

    //Here you want to define some functions in the wrapper that will call
    //the functions from your un-managed class. Here are some examples:
    //Say that your functions in the Algorithm class are int Func1, double Func2, and std::string Func3:
    int Func1();
    double Func2();
    String ^ Func3();

private:
    //All private functions and members here
    myAlgorithmClass algor;
};

2. Implement the wrapper class

using namespace System;
#include <string> //For the string function ex. below
#include "myAlgorithmClass"

MyCLIWrapperClass::MyCLIWrapperClass()
{
    algor = myAlgorithmClass(); //create instance of your un-managed class
}

int MyCLIWrapperClass::Func1()
{
    return algor.Func1(); //Call the un-managed class function.
}

double MyCLIWrapperClass::Func2()
{
    return algor.Func2(); //Call the un-managed class function.
}

String ^ MyCLIWrapperClass::Func3()
{
    //Converting a std::string to a System.String requires some conversion
    //but I'm sure you can find that somewhere on Google or here on SO

    String ^ myString = "";
    std::string myUnmanagedString = algor.Func3(); //Call the un-managed class function.

    //Convert myUnmanagedString from std::string to System.String here

    return myString;
}

After you write the wrapper class and compile it into a class library you can create a reference to the .DLL file in a C# project and C# should see the managed wrapper class and all its public functions.

Another thing to note is that if you are creating new managed objects in C++ you use the keyword "gcnew" instead of "new". So a new string would be String ^ someString = gcnew String();

Finally, here are some links to some things about CLI that may help:

CLI - Wikipedia

CLI - Code Project

CLI - FunctionX


问:
Error in Python when dealing with lists read from a text file
Here is my code. I am newbie to Python:

```<code>    f=open('dt2.txt','r').read().split('\n')
    for i in range (len(f)):
        a=f[i].split('\t')
        print type(a)
        print str(a[1])," with roll no: ",str(a[0])," ",
        c=0
        d=0
        for j in range (0,100):
            try:
                if str(a[j])=="HU101":
                    c+=1
                if str(a[j])=="HU301":
                    c+=1
                if str(a[j])=="HU481":
                    c+=1
                if str(a[j])=="HU501":
                    c+=1
                if str(a[j])=="HU601":
                    c+=1
                if str(a[j])=="HU781":
                    c+=1
                if str(a[j])=="HU801A":
                    c+=1
                if str(a[j])=="HU801B":
                    c+=1
                if str(a[j])=="M101":
                    d+=1
            except IndexError:
                continue
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"
</code>```

I am getting this error:

enter image description here

答:
Let's see if I can help... In python the csv-library and with ... open is considered more "pythonic". The with ... open ensures the file is properly closed after being opened.

```<code>import csv
with open('dt2.txt') as f:
    mydata = [i for i in csv.reader(f, delimiter='\t')] # one-liner
</code>```

Another tip... you can also shorten your code dramatically by writing:

```<code>if str(a[j]) in ["HU101","HU301",...,"HU801B"]:
   c+=1
</code>```

Body:
Here is my code. I am newbie to Python:

    f=open('dt2.txt','r').read().split('\n')
    for i in range (len(f)):
        a=f[i].split('\t')
        print type(a)
        print str(a[1])," with roll no: ",str(a[0])," ",
        c=0
        d=0
        for j in range (0,100):
            try:
                if str(a[j])=="HU101":
                    c+=1
                if str(a[j])=="HU301":
                    c+=1
                if str(a[j])=="HU481":
                    c+=1
                if str(a[j])=="HU501":
                    c+=1
                if str(a[j])=="HU601":
                    c+=1
                if str(a[j])=="HU781":
                    c+=1
                if str(a[j])=="HU801A":
                    c+=1
                if str(a[j])=="HU801B":
                    c+=1
                if str(a[j])=="M101":
                    d+=1
            except IndexError:
                continue
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"

I am getting this error:

enter image description here

Body:
Let's see if I can help... In python the csv-library and with ... open is considered more "pythonic". The with ... open ensures the file is properly closed after being opened.

import csv
with open('dt2.txt') as f:
    mydata = [i for i in csv.reader(f, delimiter='\t')] # one-liner

Another tip... you can also shorten your code dramatically by writing:

if str(a[j]) in ["HU101","HU301",...,"HU801B"]:
   c+=1


问:
servicestack with asp.net core read web.config
How to read  appsettings.json or web.config with ServiceStack ASP.Net Core?

```<code>IAppSettings appSettings = new AppSettings();
appSettings.Get<string>("Hello");
</code>```

does not find anything.

答:
ServiceStack's default AppSettings for .NET Core can read <appSettings/>, SimpleAuth.Mvc web.config is an example project that uses this.

Using .NET Core's IConfiguration config model

With the new ServiceStack v5 that's now available on MyGet you can choose to instead use .NET Core's IConfiguration model with the new NetCoreAppSettings IAppSettings adapter.

.NET Core's IConfiguration class is automatically pre-configured when running your .NET Core app using the recommended .NET Core 2.0 Startup config, i.e:

```<code>public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
</code>```

Where you can request to get it injected into the Startup constructor and assign it to a property with:

```<code>public class Startup
{
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration) => Configuration = configuration;

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseServiceStack(new AppHost
        {
            AppSettings = new NetCoreAppSettings(Configuration)
        });
    }
}
</code>```

Then you can get ServiceStack to use it with the NetCoreAppSettings adapter as seen above.

This works as a normal IAppSettings which you can use to read individual config values, e.g:

```<code>public class AppHost : AppHostBase
{
    public override void Configure(Container container)
    {
        SetConfig(new HostConfig
        {
            DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)
        });
    }
}
</code>```

Or bind to complex Types using the IAppSettings.Get<T>() APIs.

An example .NET Core 2.0 ServiceStack v5 project that uses it is NetCoreTemplates/react-spa.

Body:
How to read  appsettings.json or web.config with ServiceStack ASP.Net Core?

IAppSettings appSettings = new AppSettings();
appSettings.Get<string>("Hello");

does not find anything.

Body:
ServiceStack's default AppSettings for .NET Core can read <appSettings/>, SimpleAuth.Mvc web.config is an example project that uses this.

Using .NET Core's IConfiguration config model

With the new ServiceStack v5 that's now available on MyGet you can choose to instead use .NET Core's IConfiguration model with the new NetCoreAppSettings IAppSettings adapter.

.NET Core's IConfiguration class is automatically pre-configured when running your .NET Core app using the recommended .NET Core 2.0 Startup config, i.e:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

Where you can request to get it injected into the Startup constructor and assign it to a property with:

public class Startup
{
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration) => Configuration = configuration;

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseServiceStack(new AppHost
        {
            AppSettings = new NetCoreAppSettings(Configuration)
        });
    }
}

Then you can get ServiceStack to use it with the NetCoreAppSettings adapter as seen above.

This works as a normal IAppSettings which you can use to read individual config values, e.g:

public class AppHost : AppHostBase
{
    public override void Configure(Container container)
    {
        SetConfig(new HostConfig
        {
            DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)
        });
    }
}

Or bind to complex Types using the IAppSettings.Get<T>() APIs.

An example .NET Core 2.0 ServiceStack v5 project that uses it is NetCoreTemplates/react-spa.