问:
Angular ngDialog not Displaying model data in $scope
Continually having issues with ng-dialog properly displaying model data.  My app uses two ng-dialog instances, one to add data (in this case for a League) and a second dialog to edit data.  Both use the the same ng-model data.  When add League is selected, the first dialog pops up, the user populates the fields, and saves the record, the dialog is closed and the main page displays the created League along with its data.  An EDIT button is presented.

The issue in this case occurs when the EDIT button is pressed.

The controller's openEditLeague method is called, which prepopulates the leagueForm with the data for the league I am trying to edit.

```<code>'use strict';

angular.module('ma-app')
    .filter('trustUrl', function ($sce) {
        return function(url) {
            return $sce.trustAsResourceUrl(url);
        };
    })
    .controller('HomeController', ['$scope', 'ngDialog', 'authService', 'coreDataService', 'userService', '$rootScope', 'clubService', 'schedulingService', function($scope, ngDialog, authService, coreDataService, userService, $rootScope, clubService, schedulingService) {

        ....

        $scope.leagueForm = {
            name: '',
            shortname: '',
            minAgeGroup: null,
            maxAgeGroup: null,
            type: null,
            rescheduleDays: '',
            consequence: '',
            fine: '',
            logoURL: '',
            leagueId: ''
        };

        ....

        $scope.openEditLeague = function(league) {
            console.log("\n\nOpening dialog to edit league");
            console.log(league);

            $scope.leagueForm = {
                name: league.name,
                shortname: league.short_name,
                minAgeGroup: league.min_age_group,
                maxAgeGroup: league.max_age_group,
                type: league.type,
                rescheduleDays: league.reschedule_time,
                consequence: league.reschedule_consequence,
                fine: league.reschedule_fine,
                logoURL: league.logo_url
            };

            console.log("Current entries include: ");
            console.log($scope.leagueForm);
            ngDialog.open({ template: 'views/editLeague.html', scope: $scope, className: 'ngdialog-theme-default custom-width-600', controller:"HomeController" });
        };

        ....

    }])
;
</code>```

I am logging the contents of the $scope.leagueForm prior to opening the ng-dialog, and the data contents are correct.
When the dialog opens however, all fields are empty.

This should be fairly straight forward data-binding, so I must be doing something wrong.

Here are the contents of the editLeague.html that are used to generate the ng-dialog:

```<code><div class="ngdialog-message">
    <div>
        <h3>Edit League</h3>
    </div>
    <div> </div>
    <div>
        <form class="form-horizontal" ng-submit="editLeague()">
            <div class="form-group">
                <label class="sr-only" for="name">League Name</label>
                <div class="col-xs-12 col-sm-6">
                    <input type="text" class="form-control" id="name" placeholder="league name" ng-model="leagueForm.name">
                </div>
                <label class="sr-only" for="shortname">League Abbreviation</label>
                <div class="col-xs-12 col-sm-6">
                    <input type="text" class="form-control" id="shortname" placeholder="league abbreviation" ng-model="leagueForm.shortname">
                </div>
            </div>

            <div class="form-group">
                <label class="sr-only" for="minage">Minimum Age Group</label>
                <div class="col-xs-12 col-sm-6">
                    <div class="input-group">
                        <div class="input-group-addon">Min Age Group</div>
                        <select id="minage" class="form-control" ng-model="leagueForm.minAgeGroup" ng-options="ageGroup as ageGroup.name for ageGroup in ageGroups"></select>
                    </div>
                </div>
                <label class="sr-only" for="maxage">Maximum Age Group</label>
                <div class="col-xs-12 col-sm-6">
                    <div class="input-group">
                        <div class="input-group-addon">Max Age Group</div>
                        <select id="maxage" class="form-control" ng-model="leagueForm.maxAgeGroup" ng-options="ageGroup as ageGroup.name for ageGroup in ageGroups"></select>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="sr-only" for="type">League Type</label>
                <div class="col-xs-12 col-sm-6">
                    <div class="input-group">
                        <div class="input-group-addon">Type</div>
                        <select id="type" class="form-control" ng-model="leagueForm.type" ng-options="leagueType as leagueType.name for leagueType in leagueTypes"></select>
                    </div>
                </div>
                <label class="sr-only" for="days">Day to Reschedule</label>
                <div class="col-xs-12 col-sm-6">
                    <div class="input-group">
                        <input type="text" class="form-control" id="days" placeholder="days to reschedule" ng-model="leagueForm.rescheduleDays">
                        <div class="input-group-addon">Days</div>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="sr-only" for="consequence">Missed Reschedule Date Consequence</label>
                <div class="col-xs-12 col-sm-6">
                    <div class="input-group">
                        <div class="input-group-addon">Consequence</div>
                        <select id="consequence" class="form-control" ng-model="leagueForm.consequence">
                            <option value =""></option>
                            <option value="NONE">N/A</option>
                            <option value="FORFEIT">Forfeit</option>
                            <option value="FINE">Fine</option>
                        </select>
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6">
                    <div class="input-group" ng-show="!fineHidden">
                        <label class="sr-only" for="fine">Fine</label>
                        <div class="input-group-addon">$</div>
                        <input type="text" class="form-control" id="fine" placeholder="fine" ng-model="leagueForm.fine">
                        <div class="input-group-addon">.00</div>
                    </div>
                </div>
            </div>

            <button type="submit" class="btn btn-info">Update</button>
            <button type="button" class="btn btn-default" ng-click=closeThisDialog("Cancel")>Cancel</button>
        </form>
    </div>
    <div> </div>
</div>
</code>```

答:
Resolved.  Was very simple after all.  Just needed to remove the empty definition of

```<code>$scope.leagueForm = {
            name: '',
            shortname: '',
            minAgeGroup: null,
            maxAgeGroup: null,
            type: null,
            rescheduleDays: '',
            consequence: '',
            fine: '',
            logoURL: '',
            leagueId: ''
        };
</code>```

from the controller.  Then reference leagueForm.name, etc, as the ng-model in the Add dialog, and finally my $scope.openEditLeague function works as it is specified in the original post.

Body:
Continually having issues with ng-dialog properly displaying model data.  My app uses two ng-dialog instances, one to add data (in this case for a League) and a second dialog to edit data.  Both use the the same ng-model data.  When add League is selected, the first dialog pops up, the user populates the fields, and saves the record, the dialog is closed and the main page displays the created League along with its data.  An EDIT button is presented.

The issue in this case occurs when the EDIT button is pressed.

The controller's openEditLeague method is called, which prepopulates the leagueForm with the data for the league I am trying to edit.

'use strict';

angular.module('ma-app')
    .filter('trustUrl', function ($sce) {
        return function(url) {
            return $sce.trustAsResourceUrl(url);
        };
    })
    .controller('HomeController', ['$scope', 'ngDialog', 'authService', 'coreDataService', 'userService', '$rootScope', 'clubService', 'schedulingService', function($scope, ngDialog, authService, coreDataService, userService, $rootScope, clubService, schedulingService) {

        ....

        $scope.leagueForm = {
            name: '',
            shortname: '',
            minAgeGroup: null,
            maxAgeGroup: null,
            type: null,
            rescheduleDays: '',
            consequence: '',
            fine: '',
            logoURL: '',
            leagueId: ''
        };

        ....

        $scope.openEditLeague = function(league) {
            console.log("\n\nOpening dialog to edit league");
            console.log(league);

            $scope.leagueForm = {
                name: league.name,
                shortname: league.short_name,
                minAgeGroup: league.min_age_group,
                maxAgeGroup: league.max_age_group,
                type: league.type,
                rescheduleDays: league.reschedule_time,
                consequence: league.reschedule_consequence,
                fine: league.reschedule_fine,
                logoURL: league.logo_url
            };

            console.log("Current entries include: ");
            console.log($scope.leagueForm);
            ngDialog.open({ template: 'views/editLeague.html', scope: $scope, className: 'ngdialog-theme-default custom-width-600', controller:"HomeController" });
        };

        ....

    }])
;

I am logging the contents of the $scope.leagueForm prior to opening the ng-dialog, and the data contents are correct.
When the dialog opens however, all fields are empty.

This should be fairly straight forward data-binding, so I must be doing something wrong.

Here are the contents of the editLeague.html that are used to generate the ng-dialog:

Edit League

        <form class="form-horizontal" ng-submit="editLeague()">

                League Name

                    <input type="text" class="form-control" id="name" placeholder="league name" ng-model="leagueForm.name">

                League Abbreviation

                    <input type="text" class="form-control" id="shortname" placeholder="league abbreviation" ng-model="leagueForm.shortname">

                Minimum Age Group

Min Age Group

                        <select id="minage" class="form-control" ng-model="leagueForm.minAgeGroup" ng-options="ageGroup as ageGroup.name for ageGroup in ageGroups"></select>

                Maximum Age Group

Max Age Group

                        <select id="maxage" class="form-control" ng-model="leagueForm.maxAgeGroup" ng-options="ageGroup as ageGroup.name for ageGroup in ageGroups"></select>

                League Type

Type

                        <select id="type" class="form-control" ng-model="leagueForm.type" ng-options="leagueType as leagueType.name for leagueType in leagueTypes"></select>

                Day to Reschedule

                        <input type="text" class="form-control" id="days" placeholder="days to reschedule" ng-model="leagueForm.rescheduleDays">

Days

                Missed Reschedule Date Consequence

Consequence

                        <select id="consequence" class="form-control" ng-model="leagueForm.consequence">
                            <option value =""></option>
                            <option value="NONE">N/A</option>
                            <option value="FORFEIT">Forfeit</option>
                            <option value="FINE">Fine</option>
                        </select>

                        Fine

$

                        <input type="text" class="form-control" id="fine" placeholder="fine" ng-model="leagueForm.fine">

.00

            <button type="submit" class="btn btn-info">Update</button>
            <button type="button" class="btn btn-default" ng-click=closeThisDialog("Cancel")>Cancel</button>
        </form>

Body:
Resolved.  Was very simple after all.  Just needed to remove the empty definition of

$scope.leagueForm = {
            name: '',
            shortname: '',
            minAgeGroup: null,
            maxAgeGroup: null,
            type: null,
            rescheduleDays: '',
            consequence: '',
            fine: '',
            logoURL: '',
            leagueId: ''
        };

from the controller.  Then reference leagueForm.name, etc, as the ng-model in the Add dialog, and finally my $scope.openEditLeague function works as it is specified in the original post.


来源: stackexchange

问:
Free resource being processed for new Task in C#
As question, I'm having 2 or more tasks (using Task.Run to create new Task every time) accessing same objects(mostly List) sequentially and what I want to do is the previous task will free the resources so that the later one can access. The operation to process my object is a long running one (accessing database) so that I don't want to use Task.Wait(). I tried to use CancellationTokenResource but it doesn't work for me as the task still runs and holds the object. Any suggestions on what I should to make that happen?

答:
First off Task cancellation is cooperative, which means that the processing task has to periodically check if a cancellation has been requested and terminate accordingly. Not doing this is likely why your attempt at using CancellationToken failed.

That said, it sounds like you are trying to solve a variation of (or maybe even exactly) the producer-consumer problem. If so, strongly consider using the BlockingCollection<T> class as it deals with all the edge cases and provides a really easy interface. Producers just call Add:

```<code>myBlockingCollection.Add(item);
</code>```

And a consumption thread uses GetConsumingEnumerable:

```<code>foreach (var item in myBlockingCollection.GetConsumingEnumerable())
{
}
</code>```

When all producers are done, call CompleteAdding to let the consumption thread terminate.

ContentLicense: CC BY-SA 3.0

Body:
First off Task cancellation is cooperative, which means that the processing task has to periodically check if a cancellation has been requested and terminate accordingly. Not doing this is likely why your attempt at using CancellationToken failed.

That said, it sounds like you are trying to solve a variation of (or maybe even exactly) the producer-consumer problem. If so, strongly consider using the BlockingCollection<T> class as it deals with all the edge cases and provides a really easy interface. Producers just call Add:

myBlockingCollection.Add(item);

And a consumption thread uses GetConsumingEnumerable:

foreach (var item in myBlockingCollection.GetConsumingEnumerable())
{
}

When all producers are done, call CompleteAdding to let the consumption thread terminate.


问:
Data Arrangement in SQL Server
I have output from a SQL query in this format:

Now, I want my output to look like this instead:

Please guide me on the best possible solution. Thanks!

答:
I would do this as:

```<code>select v.*
from t cross apply
     (values ('2012-2013', t.Delta2012_2013, t.Percent2012_2013),
             ('2012-2014', t.Delta2012_2014, t.Percent2012_2014)
     ) v(row, delta, percent);
</code>```

It is unclear how to calculate the total.  Is it a constant?  Is it delta / percent ?  In any case, you can add the appropriate calculation.

Title: Data Arrangement in SQL Server

Body:
I would do this as:

select v.*
from t cross apply
     (values ('2012-2013', t.Delta2012_2013, t.Percent2012_2013),
             ('2012-2014', t.Delta2012_2014, t.Percent2012_2014)
     ) v(row, delta, percent);

It is unclear how to calculate the total.  Is it a constant?  Is it delta / percent ?  In any case, you can add the appropriate calculation.


问:
Why Are These Animations Not Opposites?
I'm trying to play an animation in reverse by using jQuery. The original animation (which works perfectly) is as follows:

```<code>    function initialSuccess(){
    $('#box3').animate({
                left: '-50%'
                    }, 300, function() {
            $('#box3').css('left', '150%');
             });

            $('#box3').next().animate({
                left: '50%'
            }, 300);

};
function initialError(){
    $('.step3-tag').html("Whoops, Something Went Wrong");
    $('.loader').replaceWith("<img src='images/error.png' id='error-img'>");
    $('#box3').append("<button class='step3-retry-button' id='retryBtn'>Try Again</button>")
$('#retryBtn').click(function() {

    $('#box3').empty();

    $('#box3').animate({
                left: '150%'
                    }, 300, function() {
            $('#box3').css('left', '150%');
             });

            $('#box3').prev().animate({
                left: '50%'
            }, 300);
             $('#box3').append("<h3 class='step3-tag'>Let Us Check That For You, One Sec!</h3> <div class='loader'></div>")
}

);
}
</code>```

Any ideas why this is happening? I've also tried leaving the numbers the same, but changing the direction from left to right, but that also did not work.

Added Information
This is the JsFiddle example, I am trying to reverse the animation (go from div 3 to div 2 if the user presses a button)

http://jsfiddle.net/jtbowden/ykbgT/

Added Information

```<code>    function initialSuccess(){
    $('#box3').animate({
                left: '-50%'
                    }, 300, function() {
            $('#box3').css('left', '150%');
             });

            $('#box3').next().animate({
                left: '50%'
            }, 300);

};
function initialError(){
    $('.step3-tag').html("Whoops, Something Went Wrong");
    $('.loader').replaceWith("<img src='images/error.png' id='error-img'>");
    $('#box3').append("<button class='step3-retry-button' id='retryBtn'>Try Again</button>")
$('#retryBtn').click(function() {

    $('#box3').animate({
                left: '-50%'
                    }, 300, function() {
            $('#box3').css('left', '-50%');
             });

            $('#box3').next().animate({
                left: '-50%'
            }, 300);

});
}
</code>```

initialSuccess() is the result then al goes well, and causes the div to slide off the screen to the left ad be replaced with the next div in live. initialFailure() happens when another operation fails, and is supposed to act as a "Back" button of sorts. initialFailure()'s animation is the one that is failing/ pushing the divs in the same (wrong) direction regardless of the changes in the animation itself.

答:
It looks like what you need is following set of animations:

$('.box').click(function () {
    $('.box').each(function () {
        if ($(this).offset().left < 0) {
            $(this).animate({
                left: '50%',
            }, 500);
        } else if ($(this).offset().left > $('#container').width()) {
            $(this).css("left", "-150%");
        } else {
            $(this).animate({
                left: '150%',
            }, 500);
        }
    });
});
```

<p>You can see a full example with 2 sets of animations at http://jsfiddle.net/af88ukfx/1/</p>

<p><strong>Update</strong></p>

<p>I'm still not sure what is your exact layout and what exactly should happen but as I wild guess I think that you need something like this:</p>

```function initialError2() {
    $('.step3-tag').html("Whoops, Something Went Wrong");
    $('.loader').replaceWith("");
    $('#box3').append("<button class='step3-retry-button' id='retryBtn'>Try Again</button>")
    $('#retryBtn').click(function () {
        $('#box3').animate({
            left: '150%'
        }, 300);

        $('#box3').prev().animate({
            left: '50%'
        }, 300);
    });
}
```

Title: Why Are These Animations Not Opposites?

Body:
I'm trying to play an animation in reverse by using jQuery. The original animation (which works perfectly) is as follows:

    function initialSuccess(){
    $('#box3').animate({
                left: '-50%'
                    }, 300, function() {
            $('#box3').css('left', '150%');
             });

            $('#box3').next().animate({
                left: '50%'
            }, 300);

};
function initialError(){
    $('.step3-tag').html("Whoops, Something Went Wrong");
    $('.loader').replaceWith("");
    $('#box3').append("<button class='step3-retry-button' id='retryBtn'>Try Again</button>")
$('#retryBtn').click(function() {

    $('#box3').empty();

    $('#box3').animate({
                left: '150%'
                    }, 300, function() {
            $('#box3').css('left', '150%');
             });

            $('#box3').prev().animate({
                left: '50%'
            }, 300);
             $('#box3').append("
Let Us Check That For You, One Sec!

")
}

);
}

Any ideas why this is happening? I've also tried leaving the numbers the same, but changing the direction from left to right, but that also did not work.

Added Information
This is the JsFiddle example, I am trying to reverse the animation (go from div 3 to div 2 if the user presses a button)

http://jsfiddle.net/jtbowden/ykbgT/

Added Information

    function initialSuccess(){
    $('#box3').animate({
                left: '-50%'
                    }, 300, function() {
            $('#box3').css('left', '150%');
             });

            $('#box3').next().animate({
                left: '50%'
            }, 300);

};
function initialError(){
    $('.step3-tag').html("Whoops, Something Went Wrong");
    $('.loader').replaceWith("");
    $('#box3').append("<button class='step3-retry-button' id='retryBtn'>Try Again</button>")
$('#retryBtn').click(function() {

    $('#box3').animate({
                left: '-50%'
                    }, 300, function() {
            $('#box3').css('left', '-50%');
             });

            $('#box3').next().animate({
                left: '-50%'
            }, 300);

});
}

initialSuccess() is the result then al goes well, and causes the div to slide off the screen to the left ad be replaced with the next div in live. initialFailure() happens when another operation fails, and is supposed to act as a "Back" button of sorts. initialFailure()'s animation is the one that is failing/ pushing the divs in the same (wrong) direction regardless of the changes in the animation itself.

Body:
It looks like what you need is following set of animations:

$('.box').click(function () {
    $('.box').each(function () {
        if ($(this).offset().left < 0) {
            $(this).animate({
                left: '50%',
            }, 500);
        } else if ($(this).offset().left > $('#container').width()) {
            $(this).css("left", "-150%");
        } else {
            $(this).animate({
                left: '150%',
            }, 500);
        }
    });
});

You can see a full example with 2 sets of animations at http://jsfiddle.net/af88ukfx/1/

Update

I'm still not sure what is your exact layout and what exactly should happen but as I wild guess I think that you need something like this:

function initialError2() {
    $('.step3-tag').html("Whoops, Something Went Wrong");
    $('.loader').replaceWith("<img src='images/error.png' id='error-img'>");
    $('#box3').append("<button class='step3-retry-button' id='retryBtn'>Try Again</button>")
    $('#retryBtn').click(function () {
        $('#box3').animate({
            left: '150%'
        }, 300);

        $('#box3').prev().animate({
            left: '50%'
        }, 300);
    });
}


问:
ORA-06502, ORA-06512 Oracle stored procedure error
These are the errors I am getting when I try to execute the stored procedure from my c# code.

```<code>ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at "MYAPP.PRO_COMPANYSEARCH", line 28
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 1
</code>```

My c# code looks like this:

```<code>using (var mCon = new OracleConnection(MyConnectionString))
{
    myCon.Open();

    using (OracleCommand myOracleCmd = myCon.CreateCommand())
    {
        myOracleCmd.CommandType = CommandType.StoredProcedure;
        myOracleCmd.CommandText = "PRO_COMPANYSEARCH";
        myOracleCmd.Parameters.Add("o_result_cur", OracleDbType.RefCursor, ParameterDirection.Output);
        myOracleCmd.Parameters.Add("o_sqlcode", OracleDbType.Int32, ParameterDirection.Output);
        myOracleCmd.Parameters.Add("o_sqlmsg", OracleDbType.Varchar2, ParameterDirection.Output);

        var reader = myOracleCmd.ExecuteReader();
        dtCompany.Load(reader);
        reader.Dispose();
    }
}
</code>```

There are 3 output parameters, 2 of which are used for tracking exceptions and the other one for the result.

EDIT: This is my stored procedure, (cant believe I forgot to post it)

```<code>CREATE OR REPLACE
PROCEDURE PRO_COMPANYSEARCH (
    o_result_cur OUT SYS_REFCURSOR,
    o_sqlcode OUT NUMBER,
    o_sqlmsg OUT VARCHAR2)

IS
BEGIN
  o_sqlmsg  := 'SUCCESS';
  o_sqlcode := 0;
  OPEN o_result_cur FOR Select distinct irint, irname, irabbv, iropt From vw_issue;

EXCEPTION
WHEN NO_DATA_FOUND THEN
  o_sqlcode := SQLCODE * -1;
  o_sqlmsg  := 'NO DATA FOUND';
WHEN OTHERS THEN
  o_sqlcode := SQLCODE * -1;     --This is line 28, I removed unnecessary comments.
  o_sqlmsg  := SUBSTR(SQLERRM, 1, 200);
END PRO_COMPANYSEARCH;
</code>```

答:
```<code>using (OracleConnection connection = new OracleDbConnector().OracleConnection)

using (OracleCommand cmd = connection.CreateCommand())
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "MyFunction";
    cmd.Parameters.Add("returnVal", OracleDbType.Varchar2, ParameterDirection.ReturnValue);
    cmd.Parameters["returnVal"].Size = 200;
    cmd.Parameters.Add("application", OracleDbType.Varchar2, "InputValue", ParameterDirection.Input);
    cmd.ExecuteNonQuery();
    string returnValue = cmd.Parameters["returnVal"].Value.ToString();
}
</code>```

Body:
These are the errors I am getting when I try to execute the stored procedure from my c# code.

ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at "MYAPP.PRO_COMPANYSEARCH", line 28
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 1

My c# code looks like this:

using (var mCon = new OracleConnection(MyConnectionString))
{
    myCon.Open();

    using (OracleCommand myOracleCmd = myCon.CreateCommand())
    {
        myOracleCmd.CommandType = CommandType.StoredProcedure;
        myOracleCmd.CommandText = "PRO_COMPANYSEARCH";
        myOracleCmd.Parameters.Add("o_result_cur", OracleDbType.RefCursor, ParameterDirection.Output);
        myOracleCmd.Parameters.Add("o_sqlcode", OracleDbType.Int32, ParameterDirection.Output);
        myOracleCmd.Parameters.Add("o_sqlmsg", OracleDbType.Varchar2, ParameterDirection.Output);

        var reader = myOracleCmd.ExecuteReader();
        dtCompany.Load(reader);
        reader.Dispose();
    }
}

There are 3 output parameters, 2 of which are used for tracking exceptions and the other one for the result.

EDIT: This is my stored procedure, (cant believe I forgot to post it)

CREATE OR REPLACE
PROCEDURE PRO_COMPANYSEARCH (
    o_result_cur OUT SYS_REFCURSOR,
    o_sqlcode OUT NUMBER,
    o_sqlmsg OUT VARCHAR2)

IS
BEGIN
  o_sqlmsg  := 'SUCCESS';
  o_sqlcode := 0;
  OPEN o_result_cur FOR Select distinct irint, irname, irabbv, iropt From vw_issue;

EXCEPTION
WHEN NO_DATA_FOUND THEN
  o_sqlcode := SQLCODE * -1;
  o_sqlmsg  := 'NO DATA FOUND';
WHEN OTHERS THEN
  o_sqlcode := SQLCODE * -1;     --This is line 28, I removed unnecessary comments.
  o_sqlmsg  := SUBSTR(SQLERRM, 1, 200);
END PRO_COMPANYSEARCH;


问:
How do I start a php server in the background as a daemon in a docker container
I was trying to follow the tutorial here using upStart (Run php script as daemon process), but I ran into some snags when I get the error 'startserver: unrecognized service'

Here is some images to show what I tried

At the bottom of the console is where the errors are. I also show proof that my file is in /etc/init where it should be in the docker container.  I logged in using docker exec -it draftandpermit_web_1 bash

Am I missing something?

Other Reference Data:

startserver.conf

```<code># Info
description "Start Server"
author      "Joseph Astrahan"

# Events
start on startup
stop on shutdown

# Automatically respawn
respawn
respawn limit 20 5

# Run the script!
# Note, in this example, if your PHP script returns
# the string "ERROR", the daemon will stop itself.
script
    [ $(exec /usr/bin/php -f /var/www/callcenter/livesite/bin/startwebsocketserver.php) = 'ERROR' ] && ( stop; exit 1; )
end script
</code>```

I activate it either manually as you saw in the images or using my convenience script

```<code>echo "Copying startserver.conf to /etc/init"
docker exec -it draftandpermit_web_1 bash -c "cd /app/docker; cp -f startserver.conf /etc/init/"

echo "Stopping & Starting the WebSocket & HTTP Server"
docker exec -it draftandpermit_web_1 bash -c "service startserver stop"
docker exec -it draftandpermit_web_1 bash -c "service startserver start"
</code>```

Keep in mind paths are correct for where the file is since I manually went into the container to look at /etc/init as shown in the images.

答:
Docker is neither an init system nor does it run traditional init systems without some hacks. The first process you run in the Docker container will be PID 1. This could be a supervisor (like supervisord, s6, dumb-init).

However, more generally, you can just run the process you want and handle running in the foreground or background with options to the docker run command. In this example your Docker command (or CMD in the Dockerfile) can just be php -f /var/www/callcenter/livesite/bin/startwebsocketserver.php. Then, run your container with the -d option and it will run in the background. You can attach to it with docker attach or just watch the output with docker logs.

If you actually need to use some sort of process supervisor (such as, when you need to have multiple processes running in the container), then I'd start looking to Docker init options out there. I mentioned a couple and there are more. Upstart won't work inside a container.

Body:
I was trying to follow the tutorial here using upStart (Run php script as daemon process), but I ran into some snags when I get the error 'startserver: unrecognized service'

Here is some images to show what I tried

At the bottom of the console is where the errors are. I also show proof that my file is in /etc/init where it should be in the docker container.  I logged in using docker exec -it draftandpermit_web_1 bash

Am I missing something?

Other Reference Data:

startserver.conf

# Info
description "Start Server"
author      "Joseph Astrahan"

# Events
start on startup
stop on shutdown

# Automatically respawn
respawn
respawn limit 20 5

# Run the script!
# Note, in this example, if your PHP script returns
# the string "ERROR", the daemon will stop itself.
script
    [ $(exec /usr/bin/php -f /var/www/callcenter/livesite/bin/startwebsocketserver.php) = 'ERROR' ] && ( stop; exit 1; )
end script

I activate it either manually as you saw in the images or using my convenience script

echo "Copying startserver.conf to /etc/init"
docker exec -it draftandpermit_web_1 bash -c "cd /app/docker; cp -f startserver.conf /etc/init/"

echo "Stopping & Starting the WebSocket & HTTP Server"
docker exec -it draftandpermit_web_1 bash -c "service startserver stop"
docker exec -it draftandpermit_web_1 bash -c "service startserver start"

Keep in mind paths are correct for where the file is since I manually went into the container to look at /etc/init as shown in the images.


问:
How to add default constructor in SQLiteOpenHelper?
My app works fine but when I try to generate signed APK I get this error in my messages.

```<code>Error:Error: This class should provide a default constructor (a public constructor with no arguments) (com.example.emilythacker.myapplication.MyDBHandler) [Instantiatable]
</code>```

When I add the empty constructor

```<code> public MyDBHandler(){}
</code>```

to my code I get this error instead

```<code>    Error:(18, 25) error: no suitable constructor found for SQLiteOpenHelper(no arguments)
constructor SQLiteOpenHelper.SQLiteOpenHelper(Context,String,CursorFactory,int) is not applicable
(actual and formal argument lists differ in length)
constructor SQLiteOpenHelper.SQLiteOpenHelper(Context,String,CursorFactory,int,DatabaseErrorHandler) is not applicable
(actual and formal argument lists differ in length)
</code>```

Here is my MyDBHelper.class

```<code>public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";

public MyDBHandler(){

}

public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_PRODUCTNAME + " TEXT " +
            ");";
    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
    onCreate(db);
}

//add a new row to the database
public void addProduct(Products product){

    SQLiteDatabase db = this.getReadableDatabase();
    if(DatabaseUtils.queryNumEntries(db, TABLE_PRODUCTS) <= 4){
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
    }
    else{
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        db.insert(TABLE_PRODUCTS, null, values);
        deleteProduct();
        db.close();
    }
}

//code coming from MainActivity
public void addButtonClicked(String highscore1){
    Products product = new Products(highscore1);
    addProduct(product);
    updateDatabase();
}

//code coming from MainActivity
public void updateDatabase(){
        String dbString = databaseToString();
        MainActivity.productText.setText(dbString);
}

//delete a product from the database
public void deleteProduct(){
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM products WHERE _id NOT IN"+
                //only reading first digit of double digit numbers
               //" (SELECT _id FROM products ORDER BY  productname DESC LIMIT 5)");
            //this runs but isnt putting double digit scores into the high score textView
            " (SELECT _id FROM products ORDER BY CAST(productname AS NUMBER) DESC LIMIT 5)");

}

//print out the database as a string
public String databaseToString(){
    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";

    //Cursor point to location in your results
    Cursor c = db.query(TABLE_PRODUCTS, null, null, null, null, null, COLUMN_PRODUCTNAME +" DESC");
    //Move to the first row in your results
    c.moveToFirst();

    while(!c.isAfterLast()){
        if(c.getString(c.getColumnIndex("productname")) != null){
            dbString += c.getString(c.getColumnIndex("productname"));
            dbString += "\n";
        }
        c.moveToNext();

    }

    db.close();
    return dbString;

}
</code>```

How can I fix this?

答:
In order to create a subclass of any parent class - in this case MyDBHandler and SQLiteOpenHelper respectively, you must first create an instance of the parent class. In order to do this, the first line of your constructor, must call the constructor of the parent.

in public MyDBHandler(){} you do not do this.

At the very least you will need to get a reference to a context so that it can be passed to the parent. The rest of the arguments are definable from your constructor, or can be null.

Here is an example from one of my projects. NAME and VERSION are class constants. Name is a String that is the name of the database file, and Version is an int specifying the current version number of your database schema.

```<code>public DBHelper(Context context) {
    super(context, NAME, null, VERSION);
}
</code>```

So you can either remove the no argument constructor public MyDBHandler(){}, and use the other constructor that you have, or modify it so that it calls the superclass constructor similar to the example above.

Body:
My app works fine but when I try to generate signed APK I get this error in my messages.

Error:Error: This class should provide a default constructor (a public constructor with no arguments) (com.example.emilythacker.myapplication.MyDBHandler) [Instantiatable]

When I add the empty constructor

 public MyDBHandler(){}

to my code I get this error instead

    Error:(18, 25) error: no suitable constructor found for SQLiteOpenHelper(no arguments)
constructor SQLiteOpenHelper.SQLiteOpenHelper(Context,String,CursorFactory,int) is not applicable
(actual and formal argument lists differ in length)
constructor SQLiteOpenHelper.SQLiteOpenHelper(Context,String,CursorFactory,int,DatabaseErrorHandler) is not applicable
(actual and formal argument lists differ in length)

Here is my MyDBHelper.class

public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";

public MyDBHandler(){

}

public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_PRODUCTNAME + " TEXT " +
            ");";
    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
    onCreate(db);
}

//add a new row to the database
public void addProduct(Products product){

    SQLiteDatabase db = this.getReadableDatabase();
    if(DatabaseUtils.queryNumEntries(db, TABLE_PRODUCTS) <= 4){
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
    }
    else{
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        db.insert(TABLE_PRODUCTS, null, values);
        deleteProduct();
        db.close();
    }
}

//code coming from MainActivity
public void addButtonClicked(String highscore1){
    Products product = new Products(highscore1);
    addProduct(product);
    updateDatabase();
}

//code coming from MainActivity
public void updateDatabase(){
        String dbString = databaseToString();
        MainActivity.productText.setText(dbString);
}

//delete a product from the database
public void deleteProduct(){
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM products WHERE _id NOT IN"+
                //only reading first digit of double digit numbers
               //" (SELECT _id FROM products ORDER BY  productname DESC LIMIT 5)");
            //this runs but isnt putting double digit scores into the high score textView
            " (SELECT _id FROM products ORDER BY CAST(productname AS NUMBER) DESC LIMIT 5)");

}

//print out the database as a string
public String databaseToString(){
    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";

    //Cursor point to location in your results
    Cursor c = db.query(TABLE_PRODUCTS, null, null, null, null, null, COLUMN_PRODUCTNAME +" DESC");
    //Move to the first row in your results
    c.moveToFirst();

    while(!c.isAfterLast()){
        if(c.getString(c.getColumnIndex("productname")) != null){
            dbString += c.getString(c.getColumnIndex("productname"));
            dbString += "\n";
        }
        c.moveToNext();

    }

    db.close();
    return dbString;

}

How can I fix this?

Body:
In order to create a subclass of any parent class - in this case MyDBHandler and SQLiteOpenHelper respectively, you must first create an instance of the parent class. In order to do this, the first line of your constructor, must call the constructor of the parent.

in public MyDBHandler(){} you do not do this.

At the very least you will need to get a reference to a context so that it can be passed to the parent. The rest of the arguments are definable from your constructor, or can be null.

Here is an example from one of my projects. NAME and VERSION are class constants. Name is a String that is the name of the database file, and Version is an int specifying the current version number of your database schema.

public DBHelper(Context context) {
    super(context, NAME, null, VERSION);
}

So you can either remove the no argument constructor public MyDBHandler(){}, and use the other constructor that you have, or modify it so that it calls the superclass constructor similar to the example above.


问:
Database Design: name-value pairs - good or bad?
Say I have an online store wherein each product has a single category (and there are hundreds of categories to choose from) assigned to it (e.g. "book", "portable DVD player", etc.). If I needed to provide descriptive fields for each category (e.g. "author" would be a field for the "book" category), what is the best way to represent this in a database?

Option 1 (name value pairs):

```<code>===========================
 field
===========================
- field_id
- category_id (FK, referring to category like "book")
- name
- value
</code>```

This means I can rely on one table for any category. I'm concerned that the pivoting required to display this data side by side with other books might be a potential problem.

Option 2 (individual tables):

```<code>===========================
 book_field
===========================
- book_field_id
- book_id (FK, referring to the actual book)
- author
- title
- publisher
- date_published
...
</code>```

This means I need a table for each category.

NOTE: not that I think it matters, but the category would be coming from a hierarchy of categories (e.g. Electronics ->  DVD Players -> Portable DVD Players).

答:
Are you sure you want to restrict only to one category. I mean, can you think of any case where you product can be belong to multiple categories?

Well, anyway here's one solution which might be usefull to you:

UPDATE (few layers added)

```<code>========
products
========
- product_id
- name

====================
categories_products
====================
- category_product_id
- product_id (FK)
- category_id (FK)

===========
categories
===========
- category_id
- name

=============================
products_detail_values_types
=============================
- product_detail_value_type_id
- product_id (FK)
- detail_value_type_id (FK)

====================
detail_values_types
====================
- detail_value_type_id
- detail_value_id (FK)
- detail_type_id (FK)

===============
detail_values
===============
- detail_value_id
- value

=============
detail_types
=============
- detail_type_id
- name
</code>```

You have type called "director":

```<code> detail_type:
   detail_type_id: 100
   name: "director"
</code>```

And some value:

```<code>detail_value:
  detail_value_id: 200
  value: "James Cameron"
</code>```

Mapping of type and value:

```<code>detail_value_type:
  detail_value_type_id: 300
  detail_value_id: 200
  detail_type_id: 100
</code>```

Which details belong to product:

```<code>product_detail_value_type:
  product_detail_value_type: 400
  product_id: 500
  detail_value_type_id: 300
</code>```

Then we have categories:

```<code>category:
  category_id: 600
  name: "movie"
</code>```

And category-product mapping:

```<code>category_product:
  category_product_id: 700
  product_id: 500
  category_id: 600
</code>```

And finally the product itself:

```<code>product:
  product_id: 500
  name: "Aliens"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Say I have an online store wherein each product has a single category (and there are hundreds of categories to choose from) assigned to it (e.g. "book", "portable DVD player", etc.). If I needed to provide descriptive fields for each category (e.g. "author" would be a field for the "book" category), what is the best way to represent this in a database?

Option 1 (name value pairs):

===========================
 field
===========================
- field_id
- category_id (FK, referring to category like "book")
- name
- value

This means I can rely on one table for any category. I'm concerned that the pivoting required to display this data side by side with other books might be a potential problem.

Option 2 (individual tables):

===========================
 book_field
===========================
- book_field_id
- book_id (FK, referring to the actual book)
- author
- title
- publisher
- date_published
...

This means I need a table for each category.

NOTE: not that I think it matters, but the category would be coming from a hierarchy of categories (e.g. Electronics ->  DVD Players -> Portable DVD Players).

Body:
Are you sure you want to restrict only to one category. I mean, can you think of any case where you product can be belong to multiple categories?

Well, anyway here's one solution which might be usefull to you:

UPDATE (few layers added)

========
products
========
- product_id
- name

====================
categories_products
====================
- category_product_id
- product_id (FK)
- category_id (FK)

===========
categories
===========
- category_id
- name

=============================
products_detail_values_types
=============================
- product_detail_value_type_id
- product_id (FK)
- detail_value_type_id (FK)

====================
detail_values_types
====================
- detail_value_type_id
- detail_value_id (FK)
- detail_type_id (FK)

===============
detail_values
===============
- detail_value_id
- value

=============
detail_types
=============
- detail_type_id
- name

You have type called "director":

 detail_type:
   detail_type_id: 100
   name: "director"

And some value:

detail_value:
  detail_value_id: 200
  value: "James Cameron"

Mapping of type and value:

detail_value_type:
  detail_value_type_id: 300
  detail_value_id: 200
  detail_type_id: 100

Which details belong to product:

product_detail_value_type:
  product_detail_value_type: 400
  product_id: 500
  detail_value_type_id: 300

Then we have categories:

category:
  category_id: 600
  name: "movie"

And category-product mapping:

category_product:
  category_product_id: 700
  product_id: 500
  category_id: 600

And finally the product itself:

product:
  product_id: 500
  name: "Aliens"


问:
Run a setInterval function, stop it for 3 seconds and continue running it
I have a setInterval function going trough some div classes, if it finds a div with a particular class it should stop for 3 seconds and then continue running. Notice how I am using:

```<code>   clearInterval(myInterval);
</code>```

but I need something else, to start the sequence again or make it to continue running from there.

e.g:

```<code>var myInterval =  setInterval(function() {
                    move.removeClass( "girlFromRight" );

                    runFromRight -= 9;
                    move = $("#grid"+ runFromRight);
                    move.addClass("girlFromRight");

                    if (move.hasClass("man") === true ||
                        move.hasClass("man-right") === true ||
                        move.hasClass("man-left") === true )
                        {

                          clearInterval(myInterval);

                          move.addClass('inLove');
                          move.removeClass('girlFromRight');

                          setTimeout(function() {
                          move.removeClass('inLove');
                          move.addClass('man');

                          }, 3000);

                    }

                    if (c == 9){
                      clearInterval(myInterval);
                    }
                    }, 300);

                   keyPressed = false;

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

答:
Consider using setTimeout and setting the interval (300 or 3000) after each run based on a test. That way you don't have to start and stop setInterval.

A quick example is below, it highlights each div in sequence, pausing longer on any where the text content is evenly divisible by 3 (as an example test).

function doLoop(){
  var divs = document.querySelectorAll('div');
  var i = 0;
  function loop(){
    var selected = document.querySelectorAll('.selected');
    [].forEach.call(selected,function(el) {
      el.className = 'notSelected';
    });
    divs[i].className = 'selected';
    setTimeout(loop, divs[i].textContent % 3? 300 : 3000);
    i = ++i % (divs.length - 2);
  }
  loop();
}

window.onload = doLoop;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.notSelected{}
.selected{
  background-color: blue;
}</code>```

0

1

2

3

4

5
```

Body:
I have a setInterval function going trough some div classes, if it finds a div with a particular class it should stop for 3 seconds and then continue running. Notice how I am using:

   clearInterval(myInterval);

but I need something else, to start the sequence again or make it to continue running from there.

e.g:

var myInterval =  setInterval(function() {
                    move.removeClass( "girlFromRight" );

                    runFromRight -= 9;
                    move = $("#grid"+ runFromRight);
                    move.addClass("girlFromRight");

                    if (move.hasClass("man") === true ||
                        move.hasClass("man-right") === true ||
                        move.hasClass("man-left") === true )
                        {

                          clearInterval(myInterval);

                          move.addClass('inLove');
                          move.removeClass('girlFromRight');

                          setTimeout(function() {
                          move.removeClass('inLove');
                          move.addClass('man');

                          }, 3000);

                    }

                    if (c == 9){
                      clearInterval(myInterval);
                    }
                    }, 300);

                   keyPressed = false;

        }, randomTime);
        }

Body:
Consider using setTimeout and setting the interval (300 or 3000) after each run based on a test. That way you don't have to start and stop setInterval.

A quick example is below, it highlights each div in sequence, pausing longer on any where the text content is evenly divisible by 3 (as an example test).

function doLoop(){
  var divs = document.querySelectorAll('div');
  var i = 0;
  function loop(){
    var selected = document.querySelectorAll('.selected');
    [].forEach.call(selected,function(el) {
      el.className = 'notSelected';
    });
    divs[i].className = 'selected';
    setTimeout(loop, divs[i].textContent % 3? 300 : 3000);
    i = ++i % (divs.length - 2);
  }
  loop();
}

window.onload = doLoop;

.notSelected{}
.selected{
  background-color: blue;
}

<div class="notSelected">0</div>
<div class="notSelected">1</div>
<div class="notSelected">2</div>
<div class="notSelected">3</div>
<div class="notSelected">4</div>
<div class="notSelected">5</div>


问:
Epson printer connect fails status ERR_CONN
I have an Epson printer and I used epos2_printer (sample project) code given with SDK to integrate with my app. I have copied the same code but it never seems to work!

However, the same works when I connect the sample project to my printer.

```<code>private boolean runPrintReceiptSequence() {
    if (!initializeObject()) {
        return false;
    }

    if (!createReceiptData()) {
        finalizeObject();
        return false;
    }

    if (!printData()) {
        finalizeObject();
        return false;
    }

    return true;
}

private boolean initializeObject() {
    try {

        final SpnModelsItem spnModel = new SpnModelsItem("TM-T82 Series", Printer.TM_T82);
        final SpnModelsItem spnLang = new SpnModelsItem("ANK", Printer.MODEL_ANK);

        mPrinter = new Printer(spnModel.getModelConstant(),
                                spnLang.getModelConstant(), this);
    }
    catch (Exception e) {
        Log.e("Printer", e.toString());
        return false;
    }

    mPrinter.setReceiveEventListener(this);

    return true;
}

private boolean createReceiptData() {
    String method = "";
    Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.logo_saltnpepper);
    StringBuilder textData = new StringBuilder();
    final int barcodeWidth = 2;
    final int barcodeHeight = 100;
    Date currentDate = new Date();
    info.saltnpepper.ordersmart2.MenuItem currItem = null;

    double price = 0;
    double total = 0;
    int totalQty =0;

    if (mPrinter == null) {
        return false;
    }

    try {
        method = "addTextAlign";
        mPrinter.addTextAlign(Printer.ALIGN_CENTER);

        method = "addImage";
        mPrinter.addImage(logoData, 0, 0,
                          logoData.getWidth(),
                          logoData.getHeight(),
                          Printer.COLOR_1,
                          Printer.MODE_MONO,
                          Printer.HALFTONE_DITHER,
                          Printer.PARAM_DEFAULT,
                          Printer.COMPRESS_AUTO);

        method = "addFeedLine";
        mPrinter.addFeedLine(1);
        textData.append("SALT-N-PEPPER\n");
        //textData.append("STORE DIRECTOR â€“ John Smith\n");
        textData.append("\n");
        textData.append((new SimpleDateFormat("dd/MM/yy HH:mm:ss")).format(currentDate).toString() + "\n");
        //textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());
        if(alFinalOrder != null)
        {
            for(int i=0; i < alFinalOrder.size(); i++)
            {
                currItem = alFinalOrder.get(i);
                textData.append(currItem.getName()+"  "+currItem.getQty()+"  "+currItem.getPrice()+"\n");

                //calculate total quantity
                totalQty = totalQty + currItem.getQty();

                //calculate price
                double dPrice = currItem.getQty()*Double.parseDouble(currItem.getPrice().substring(1));
                total = total + dPrice;
                total = Math.round(total*100.0)/100.0;

            }
        }
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());

        textData.append("TOTAL                   "+"\n");
        textData.append("TAX                     "+"\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());
</code>```

mPrinter.addFeedLine(2);

```<code>        method = "addBarcode";
        mPrinter.addBarcode("01209457",
                            Printer.BARCODE_CODE39,
                            Printer.HRI_BELOW,
                            Printer.FONT_A,
                            barcodeWidth,
                            barcodeHeight);

        method = "addCut";
        mPrinter.addCut(Printer.CUT_FEED);
    }
    catch (Exception e) {
        //ShowMsg.showException(e, method, mContext);
        return false;
    }

    textData = null;

    return true;
}

private boolean printData() {
    if (mPrinter == null) {
        return false;
    }

    if (!connectPrinter()) {
        return false;
    }

    PrinterStatusInfo status = mPrinter.getStatus();

    dispPrinterWarnings(status);

    if (!isPrintable(status)) {
        Log.e("Printer", "Is not printable");
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    try {
        mPrinter.sendData(Printer.PARAM_DEFAULT);
    }
    catch (Exception e) {
        Log.e("Printer", e.getMessage());
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    return true;
}

private boolean connectPrinter() {
    boolean isBeginTransaction = false;

    if (mPrinter == null) {
        return false;
    }

    try {
        mPrinter.connect("TCP:"+mIP, Printer.PARAM_DEFAULT);
    }
    catch (Epos2Exception e) {
        //ShowMsg.showException(e, "connect", this);
        if(e.getErrorStatus() == Epos2Exception.ERR_CONNECT)
        {
            Log.e("testing", "error connect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_OPENED)
        {
            Log.e("testing", "already open");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_USED)
        {
            Log.e("testing", "already used");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_CLIENT_OVER)
        {
            Log.e("testing", "box client over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_COUNT_OVER)
        {
            Log.e("testing", "count over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_DISCONNECT)
        {
            Log.e("testing", "disconnect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_FAILURE)
        {
            Log.e("testing", "failure");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ILLEGAL)
        {
            Log.e("testing", "illegal");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_IN_USE)
        {
            Log.e("testing", "in use");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_MEMORY)
        {
            Log.e("testing", "memory");
        }
        return false;
    }

    try {
        mPrinter.beginTransaction();
        isBeginTransaction = true;
    }
    catch (Exception e) {
        Log.e("Printer", e.toString ());
    }

    if (isBeginTransaction == false) {
        try {
            mPrinter.disconnect();
        }
        catch (Epos2Exception e) {
            // Do nothing
            return false;
        }
    }

    return true;
}
</code>```

It always gives me exception ERR_CONNECT on printer.connect inside connectprinter function.

What am I doing wrong?

This code works fine with the sample app.
P.S: I have tried to connect this app before connecting the sample app to check if the sample app holds the connection and does not allow other apps to connect but that is not the case. Epson help is unable to provide any further help.

My AndroidManifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xyz"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="21"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MenuActivity" >
    </activity>
    <activity
        android:name=".SaltnPepperActivity"
        android:label="@string/title_activity_saltn_pepper" >
    </activity>
            <activity
        android:name=".FinalOrder"
         ></activity>
                <activity
        android:name=".ZinVietActivity"
         >
    </activity>
     <activity
        android:name="com.epson.epos2_printer.DiscoverActivity"
         ></activity>

</application>
</code>```

答:
Looks like you don't have the proper permissions in your manifest. Try putting these in your project under the manifest tag:

<uses-permission android:name="android.permission.BLUETOOTH"/>

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

They also have the

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

permission but I'm not sure you need it. I think the essentials are Bluetooth and Internet permissions.

Body:
I have an Epson printer and I used epos2_printer (sample project) code given with SDK to integrate with my app. I have copied the same code but it never seems to work!

However, the same works when I connect the sample project to my printer.

private boolean runPrintReceiptSequence() {
    if (!initializeObject()) {
        return false;
    }

    if (!createReceiptData()) {
        finalizeObject();
        return false;
    }

    if (!printData()) {
        finalizeObject();
        return false;
    }

    return true;
}

private boolean initializeObject() {
    try {

        final SpnModelsItem spnModel = new SpnModelsItem("TM-T82 Series", Printer.TM_T82);
        final SpnModelsItem spnLang = new SpnModelsItem("ANK", Printer.MODEL_ANK);

        mPrinter = new Printer(spnModel.getModelConstant(),
                                spnLang.getModelConstant(), this);
    }
    catch (Exception e) {
        Log.e("Printer", e.toString());
        return false;
    }

    mPrinter.setReceiveEventListener(this);

    return true;
}

private boolean createReceiptData() {
    String method = "";
    Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.logo_saltnpepper);
    StringBuilder textData = new StringBuilder();
    final int barcodeWidth = 2;
    final int barcodeHeight = 100;
    Date currentDate = new Date();
    info.saltnpepper.ordersmart2.MenuItem currItem = null;

    double price = 0;
    double total = 0;
    int totalQty =0;

    if (mPrinter == null) {
        return false;
    }

    try {
        method = "addTextAlign";
        mPrinter.addTextAlign(Printer.ALIGN_CENTER);

        method = "addImage";
        mPrinter.addImage(logoData, 0, 0,
                          logoData.getWidth(),
                          logoData.getHeight(),
                          Printer.COLOR_1,
                          Printer.MODE_MONO,
                          Printer.HALFTONE_DITHER,
                          Printer.PARAM_DEFAULT,
                          Printer.COMPRESS_AUTO);

        method = "addFeedLine";
        mPrinter.addFeedLine(1);
        textData.append("SALT-N-PEPPER\n");
        //textData.append("STORE DIRECTOR â€“ John Smith\n");
        textData.append("\n");
        textData.append((new SimpleDateFormat("dd/MM/yy HH:mm:ss")).format(currentDate).toString() + "\n");
        //textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());
        if(alFinalOrder != null)
        {
            for(int i=0; i < alFinalOrder.size(); i++)
            {
                currItem = alFinalOrder.get(i);
                textData.append(currItem.getName()+"  "+currItem.getQty()+"  "+currItem.getPrice()+"\n");

                //calculate total quantity
                totalQty = totalQty + currItem.getQty();

                //calculate price
                double dPrice = currItem.getQty()*Double.parseDouble(currItem.getPrice().substring(1));
                total = total + dPrice;
                total = Math.round(total*100.0)/100.0;

            }
        }
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());

        textData.append("TOTAL                   "+"\n");
        textData.append("TAX                     "+"\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());

mPrinter.addFeedLine(2);

        method = "addBarcode";
        mPrinter.addBarcode("01209457",
                            Printer.BARCODE_CODE39,
                            Printer.HRI_BELOW,
                            Printer.FONT_A,
                            barcodeWidth,
                            barcodeHeight);

        method = "addCut";
        mPrinter.addCut(Printer.CUT_FEED);
    }
    catch (Exception e) {
        //ShowMsg.showException(e, method, mContext);
        return false;
    }

    textData = null;

    return true;
}

private boolean printData() {
    if (mPrinter == null) {
        return false;
    }

    if (!connectPrinter()) {
        return false;
    }

    PrinterStatusInfo status = mPrinter.getStatus();

    dispPrinterWarnings(status);

    if (!isPrintable(status)) {
        Log.e("Printer", "Is not printable");
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    try {
        mPrinter.sendData(Printer.PARAM_DEFAULT);
    }
    catch (Exception e) {
        Log.e("Printer", e.getMessage());
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    return true;
}

private boolean connectPrinter() {
    boolean isBeginTransaction = false;

    if (mPrinter == null) {
        return false;
    }

    try {
        mPrinter.connect("TCP:"+mIP, Printer.PARAM_DEFAULT);
    }
    catch (Epos2Exception e) {
        //ShowMsg.showException(e, "connect", this);
        if(e.getErrorStatus() == Epos2Exception.ERR_CONNECT)
        {
            Log.e("testing", "error connect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_OPENED)
        {
            Log.e("testing", "already open");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_USED)
        {
            Log.e("testing", "already used");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_CLIENT_OVER)
        {
            Log.e("testing", "box client over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_COUNT_OVER)
        {
            Log.e("testing", "count over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_DISCONNECT)
        {
            Log.e("testing", "disconnect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_FAILURE)
        {
            Log.e("testing", "failure");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ILLEGAL)
        {
            Log.e("testing", "illegal");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_IN_USE)
        {
            Log.e("testing", "in use");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_MEMORY)
        {
            Log.e("testing", "memory");
        }
        return false;
    }

    try {
        mPrinter.beginTransaction();
        isBeginTransaction = true;
    }
    catch (Exception e) {
        Log.e("Printer", e.toString ());
    }

    if (isBeginTransaction == false) {
        try {
            mPrinter.disconnect();
        }
        catch (Epos2Exception e) {
            // Do nothing
            return false;
        }
    }

    return true;
}

It always gives me exception ERR_CONNECT on printer.connect inside connectprinter function.

What am I doing wrong?

This code works fine with the sample app.
P.S: I have tried to connect this app before connecting the sample app to check if the sample app holds the connection and does not allow other apps to connect but that is not the case. Epson help is unable to provide any further help.

My AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xyz"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="21"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MenuActivity" >
    </activity>
    <activity
        android:name=".SaltnPepperActivity"
        android:label="@string/title_activity_saltn_pepper" >
    </activity>
            <activity
        android:name=".FinalOrder"
         ></activity>
                <activity
        android:name=".ZinVietActivity"
         >
    </activity>
     <activity
        android:name="com.epson.epos2_printer.DiscoverActivity"
         ></activity>

</application>


问:
Sizing elements to percentage of screen width/height
Is there a simple (non-LayoutBuilder) way to size an element relative to screen size (width/height)? For example: how do I set the width of a CardView to be 65% of the screen width.

It can't be done inside the build method (obviously) so it would have to be deferred until post build. Is there a preferred place to put logic like this?

答:
FractionallySizedBox may also be useful.
You can also read the screen width directly out of MediaQuery.of(context).size and create a sized box based on that

```<code>MediaQuery.of(context).size.width * 0.65
</code>```

if you really want to size as a fraction of the screen regardless of what the layout is.

Body:
FractionallySizedBox may also be useful.
You can also read the screen width directly out of MediaQuery.of(context).size and create a sized box based on that

MediaQuery.of(context).size.width * 0.65

if you really want to size as a fraction of the screen regardless of what the layout is.

ContentLicense: CC BY-SA 4.0


问:
Prevent kafka consumer from timing out for long process
I need to prevent the kafka consumer from timing out while the application waits for a particular process to complete. My approach is to pause the partitions and then resume them once the process is completed.

```<code>List<TopicPartition> partitionList = new ArrayList<>();
partitionList.addAll(kafkaConsumer.assignment());
kafkaConsumer.pause(partitionList);

while(//waiting for the process to complete){
    Thread.sleep(10000);
    kafkaConsumer.poll(0);
}
kafkaConsumer.resume(partitionList);
</code>```

Questions

Does pause send heartbeat to kafka automatically or should I still need to poll at regular intervals to send the heart beat?

Is mine the best approach ? or is there a better way of doing it?

答:
Since Kafka 0.10.1, consumers do have a background thread for sending heartbeats: https://cwiki.apache.org/confluence/display/KAFKA/KIP-62%3A+Allow+consumer+to+send+heartbeats+from+a+background+thread

Thus, you don't need to call poll() to send heartbeat to the brokers. However, there is a second timeout max.poll.interval.ms -- you must call poll() within this time to avoid this second timeout. Default value is 5 minutes. You can just increase this timeout if your wait is even longer than this. If you do so, you also don't need to pause any partitions etc.

If you are using an older version, you approach of pausing, and calling poll() regularly is the only way to send regular heartbeat to avoid the timeout.

Body:
I need to prevent the kafka consumer from timing out while the application waits for a particular process to complete. My approach is to pause the partitions and then resume them once the process is completed.

List<TopicPartition> partitionList = new ArrayList<>();
partitionList.addAll(kafkaConsumer.assignment());
kafkaConsumer.pause(partitionList);

while(//waiting for the process to complete){
    Thread.sleep(10000);
    kafkaConsumer.poll(0);
}
kafkaConsumer.resume(partitionList);

Questions

Does pause send heartbeat to kafka automatically or should I still need to poll at regular intervals to send the heart beat?

Is mine the best approach ? or is there a better way of doing it?


问:
How to configure endpoint in .csdef and .cscfg file?
I need deploy an Azure service. Inside the .csdef file, I need define an input endpoint which I did (following here:https://learn.microsoft.com/en-us/azure/cloud-services/cloud-services-enable-communication-role-instances):

```<code><Endpoints>
  <InputEndpoint name="StandardWeb" protocol="http" port="80" localPort="80" />
</Endpoints>
</code>```

The problem is I need deploy this package to 5 different web service and the "InputEndpoint"s are different for the 5 web service.

My question is do I need have 5 .csdef for the deployment? Is there any way to make use of the .cscfg ?

Thanks

答:
This is not possible. Endpoints are specified in Cloud Service Definition files and not Cloud Service Configuration files because endpoints must be identical for all instances participating in a cloud service.

I need deploy this package to 5 different web service

You will need to modify your Cloud Service for each different Cloud Service. Is there a reason they must be different?

Body:
I need deploy an Azure service. Inside the .csdef file, I need define an input endpoint which I did (following here:https://learn.microsoft.com/en-us/azure/cloud-services/cloud-services-enable-communication-role-instances):

<Endpoints>
  <InputEndpoint name="StandardWeb" protocol="http" port="80" localPort="80" />
</Endpoints>

The problem is I need deploy this package to 5 different web service and the "InputEndpoint"s are different for the 5 web service.

My question is do I need have 5 .csdef for the deployment? Is there any way to make use of the .cscfg ?

Thanks


问:
Testing Java Spark Microservices app that implements SparkApplication interface
I am trying to figure out how to test a web/rest services written in Java Spark and there is not many tutorials on how to do that. It is tricky to find answers due to confusion between Apache Spark and Java Spark.

I came across this resource but, I couldn't get it to work the way I had expected. There is also this resource and examples in Java Spark github but they all probably use embedded server.

Anyway, Assuming that I have the following service

```<code>public class RestService implements SparkApplication {
    @Override
    public void init() {
        get("/", (req, res) -> "Hello World!");
    }
}
</code>```

I would like to test the above to make sure it Hello World! for HTTP GET requests or not. I have the following test:

```<code>public class RestServiceTest {
    //not sure if this is a good practice????
    final static RestService restService = new RestService();

    @BeforeClass
    public static void beforeClass() {
        //I have seen tests that invoked className.main(null)
        //but, I don't know if its good idea to do it here?
        restService.init();
        Spark.awaitInitialization();
    }

    @AfterClass
    public static void afterClass() {
        Spark.stop();
    }

    @Test
    public void testRootRoute() throws IOException {
        TestResponse res = makeRequest("GET", "/");
        assertEquals(200, res.status);
        assertNotNull(res.body);
        assertEquals("Hello World!", res.body);
    }

    private TestResponse makeRequest(String method, String path) throws IOException {
        URL url = new URL("http://localhost:4567" + path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setDoOutput(true);
        connection.connect();
        String body = IOUtils.toString(connection.getInputStream());
        return new TestResponse(connection.getResponseCode(), body);
    }

    private static class TestResponse {
        public final String body;
        public final int status;

        public TestResponse(int status, String body) {
            this.status = status;
            this.body = body;
        }
    }
}
</code>```

Running the above, the test executes successfully aand the output is shown below but, my main concern is whether this is the right method of testing a Java Spark webapp aimed to run not in embedded server (when SparkApplication is implemented and init() is overrided)?

```<code>T E S T S
-------------------------------------------------------
Running com.company.test.RestServiceTest
[Thread-0] INFO org.eclipse.jetty.util.log - Logging initialized @238ms
[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - == Spark has ignited ...
[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >> Listening on 0.0.0.0:4567
[Thread-0] INFO org.eclipse.jetty.server.Server - jetty-9.3.6.v20151106
[Thread-0] INFO org.eclipse.jetty.server.ServerConnector - Started ServerConnector@4be514e0{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
[Thread-0] INFO org.eclipse.jetty.server.Server - Started @330ms
[main] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >>> Spark shutting down ...
[main] INFO org.eclipse.jetty.server.ServerConnector - Stopped ServerConnector@4be514e0{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
[main] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - done
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.291 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
</code>```

答: This might help, and it's from the official spark-java website so it might be considered the right method, or at least the recommended one.

Body:
I am trying to figure out how to test a web/rest services written in Java Spark and there is not many tutorials on how to do that. It is tricky to find answers due to confusion between Apache Spark and Java Spark.

I came across this resource but, I couldn't get it to work the way I had expected. There is also this resource and examples in Java Spark github but they all probably use embedded server.

Anyway, Assuming that I have the following service

public class RestService implements SparkApplication {
    @Override
    public void init() {
        get("/", (req, res) -> "Hello World!");
    }
}

I would like to test the above to make sure it Hello World! for HTTP GET requests or not. I have the following test:

public class RestServiceTest {
    //not sure if this is a good practice????
    final static RestService restService = new RestService();

    @BeforeClass
    public static void beforeClass() {
        //I have seen tests that invoked className.main(null)
        //but, I don't know if its good idea to do it here?
        restService.init();
        Spark.awaitInitialization();
    }

    @AfterClass
    public static void afterClass() {
        Spark.stop();
    }

    @Test
    public void testRootRoute() throws IOException {
        TestResponse res = makeRequest("GET", "/");
        assertEquals(200, res.status);
        assertNotNull(res.body);
        assertEquals("Hello World!", res.body);
    }

    private TestResponse makeRequest(String method, String path) throws IOException {
        URL url = new URL("http://localhost:4567" + path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setDoOutput(true);
        connection.connect();
        String body = IOUtils.toString(connection.getInputStream());
        return new TestResponse(connection.getResponseCode(), body);
    }

    private static class TestResponse {
        public final String body;
        public final int status;

        public TestResponse(int status, String body) {
            this.status = status;
            this.body = body;
        }
    }
}

Running the above, the test executes successfully aand the output is shown below but, my main concern is whether this is the right method of testing a Java Spark webapp aimed to run not in embedded server (when SparkApplication is implemented and init() is overrided)?

T E S T S
-------------------------------------------------------
Running com.company.test.RestServiceTest
[Thread-0] INFO org.eclipse.jetty.util.log - Logging initialized @238ms
[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - == Spark has ignited ...
[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >> Listening on 0.0.0.0:4567
[Thread-0] INFO org.eclipse.jetty.server.Server - jetty-9.3.6.v20151106
[Thread-0] INFO org.eclipse.jetty.server.ServerConnector - Started ServerConnector@4be514e0{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
[Thread-0] INFO org.eclipse.jetty.server.Server - Started @330ms
[main] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >>> Spark shutting down ...
[main] INFO org.eclipse.jetty.server.ServerConnector - Stopped ServerConnector@4be514e0{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
[main] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - done
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.291 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0


问:
Ajax Form doesn't remain on page
Been beating my mind at this but its now time for me to ask for help (ask i got work tomorrow and dont want to be on this all night)

My form is inside a modal and this is my script

```<code>$(function() {
    $("#applyForm").on('submit' , function(e) {
        $.ajax({
            type: 'POST',
            url: $("#applyForm").attr("action"),
            data: $('#applyForm').serialize(),
            success: function(data){
              alert('successfully submitted')},
            error: function(data){
              alert('something went wrong')
          }

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

It all works, It fires up the script and submits to the backend with a success message but as soon as you close the popup sucess message it redirects to the action "apply-now" page.

How can i prevent this without it breaking the submit, As i've tried return false and preventDefault.

Heres the form

```<code><form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="hidden" value="1">
<input name="listing_id" type="hidden" value="{$listing_id}">

MY FORM DATA

<button type="submit" id="submit" class="btn btn-warning">Apply now</button>
</code>```

Any help would really be appreciated !

Thanks

J

答:
The form is being submitted twice. Once with the form action and the other time with the ajax call. If you prefer to have only the ajax call sent, returning false outside the ajax function should do the trick. When to use PreventDefault( ) vs Return false?</p>

```<code>$(function () {
    $("#applyForm").on('submit', function (e) {
        //e.preventDefault();
        $.ajax({
            type: 'POST',
            url: $("#applyForm").attr("action"),
            data: $('#applyForm').serialize(),
            success: function (data) {
                alert('successfully submitted')
            },
            error: function (data) {
                alert('something went wrong')
            }

        });
        return false;
    });
});
</code>```

Title: Ajax Form doesn't remain on page

Body:
Been beating my mind at this but its now time for me to ask for help (ask i got work tomorrow and dont want to be on this all night)

My form is inside a modal and this is my script

$(function() {
    $("#applyForm").on('submit' , function(e) {
        $.ajax({
            type: 'POST',
            url: $("#applyForm").attr("action"),
            data: $('#applyForm').serialize(),
            success: function(data){
              alert('successfully submitted')},
            error: function(data){
              alert('something went wrong')
          }

     });
});
});

It all works, It fires up the script and submits to the backend with a success message but as soon as you close the popup sucess message it redirects to the action "apply-now" page.

How can i prevent this without it breaking the submit, As i've tried return false and preventDefault.

Heres the form

<form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="hidden" value="1">
<input name="listing_id" type="hidden" value="{$listing_id}">

MY FORM DATA

<button type="submit" id="submit" class="btn btn-warning">Apply now</button>

Any help would really be appreciated !

Thanks

J

Body:
The form is being submitted twice. Once with the form action and the other time with the ajax call. If you prefer to have only the ajax call sent, returning false outside the ajax function should do the trick. When to use PreventDefault( ) vs Return false?

$(function () {
    $("#applyForm").on('submit', function (e) {
        //e.preventDefault();
        $.ajax({
            type: 'POST',
            url: $("#applyForm").attr("action"),
            data: $('#applyForm').serialize(),
            success: function (data) {
                alert('successfully submitted')
            },
            error: function (data) {
                alert('something went wrong')
            }

        });
        return false;
    });
});


问:
Stop MKMapView from reloading
I have a MKMapView with scrolling and userInteraction disabled within a UITableViewCell. The desired effect (effectively a static image of the map in a certain position) works really well but when the MKMapView drifts on and off screen (scrolling) it reloads the map, which occasionally causes the app to crash. I have loaded the custom UITableViewCell in like any other UITableViewCell in cellForRowAtIndexPath:

```<code>if(indexPath.section == 0 && indexPath.row == 0)
{
    MapTableViewCell *cell = (MapTableViewCell *)[tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"%@Map", cellIdentifier]];

    if(cell == nil)
    {
        cell = [[[MapTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
    }

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MapTableViewCell" owner:self options:nil];

    for(id currentObject in topLevelObjects)
    {
        if([currentObject isKindOfClass:[UITableViewCell class]])
        {
            cell = (MapTableViewCell *)currentObject;
            break;
        }
    }

    return cell;
}
</code>```

I've found out that with this current method, if you let the map image load before moving the UITableView then it's OK. But if you move it off the screen before it's finished loading then it will crash! :(

I will just point out that I do not want to be able to control the map in any way or show any annotations on it. I did try to screenshot a map view, hide it from screen and display that screenshot as a UIImageView in the UITableViewCell but this wasn't fast enough!

EDIT: Updated code. This is the full code for this method. Is my custom TableViewCell alloc incorrect here?

答:
Thanks to tc for the answer (the comment above).

What was required was for me to release the MKMapView in the custom UITableViewCell dealloc method.

Title: Stop MKMapView from reloading

Body:
I have a MKMapView with scrolling and userInteraction disabled within a UITableViewCell. The desired effect (effectively a static image of the map in a certain position) works really well but when the MKMapView drifts on and off screen (scrolling) it reloads the map, which occasionally causes the app to crash. I have loaded the custom UITableViewCell in like any other UITableViewCell in cellForRowAtIndexPath:

if(indexPath.section == 0 && indexPath.row == 0)
{
    MapTableViewCell *cell = (MapTableViewCell *)[tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"%@Map", cellIdentifier]];

    if(cell == nil)
    {
        cell = [[[MapTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
    }

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MapTableViewCell" owner:self options:nil];

    for(id currentObject in topLevelObjects)
    {
        if([currentObject isKindOfClass:[UITableViewCell class]])
        {
            cell = (MapTableViewCell *)currentObject;
            break;
        }
    }

    return cell;
}

I've found out that with this current method, if you let the map image load before moving the UITableView then it's OK. But if you move it off the screen before it's finished loading then it will crash! :(

I will just point out that I do not want to be able to control the map in any way or show any annotations on it. I did try to screenshot a map view, hide it from screen and display that screenshot as a UIImageView in the UITableViewCell but this wasn't fast enough!

EDIT: Updated code. This is the full code for this method. Is my custom TableViewCell alloc incorrect here?


问:
ValueError: Invalid reduction dimension 1 for input with 1 dimensions
The tf.reduce_mean() function sums the elements of an array in such a way that the index referred to in the axis argument.

In the following code:

```<code>import tensorflow as tf

x = tf.Variable([1, 2, 3])
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)
</code>```

So for the line

```<code>print(sess.run(tf.reduce_sum(x)))
</code>```

The output is: 6

In order to generate the same output, I need to sum all the elements in a way to reduce the number of columns. So I need to set axis = 1 right?

```<code>print(sess.run(tf.reduce_sum(x, 1)))
</code>```

But I get an error:

ValueError: Invalid reduction dimension 1 for input with 1 dimensions

But if I set axis = 0, I get 6. Why is this?

答:
The error you get is ValueError: Invalid reduction dimension 1 for input with 1 dimensions. This pretty much means that if you can't reduce the dimension of a 1-dimensional tensor.

For an N x M tensor, setting axis = 0 will return an 1xM tensor, and setting axis = 1 will return a Nx1 tensor. Consider the following example from the tensorflow documentation:

```<code># 'x' is [[1, 1, 1]
#         [1, 1, 1]]
tf.reduce_sum(x) ==> 6
tf.reduce_sum(x, 0) ==> [2, 2, 2]
tf.reduce_sum(x, 1) ==> [3, 3]
</code>```

Body:
The tf.reduce_mean() function sums the elements of an array in such a way that the index referred to in the axis argument.

In the following code:

import tensorflow as tf

x = tf.Variable([1, 2, 3])
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

So for the line

print(sess.run(tf.reduce_sum(x)))

The output is: 6

In order to generate the same output, I need to sum all the elements in a way to reduce the number of columns. So I need to set axis = 1 right?

print(sess.run(tf.reduce_sum(x, 1)))

But I get an error:

ValueError: Invalid reduction dimension 1 for input with 1 dimensions

But if I set axis = 0, I get 6. Why is this?

Body:
The error you get is ValueError: Invalid reduction dimension 1 for input with 1 dimensions. This pretty much means that if you can't reduce the dimension of a 1-dimensional tensor.

For an N x M tensor, setting axis = 0 will return an 1xM tensor, and setting axis = 1 will return a Nx1 tensor. Consider the following example from the tensorflow documentation:

# 'x' is [[1, 1, 1]
#         [1, 1, 1]]
tf.reduce_sum(x) ==> 6
tf.reduce_sum(x, 0) ==> [2, 2, 2]
tf.reduce_sum(x, 1) ==> [3, 3]


问:
TagBuilder InnerHtml in ASP.NET 5 MVC 6
It seems to me that there are major breaking changes in TagBuilder as of beta7 with no mention about them in the announcements repo.

Specifically .ToString no longer renders the tagbuilder, it just returns the name of the type.
previously we could do things like this inside our HtmlHelper extensions to build up nested html elements:

```<code>var li = new TagBuilder("li");
li.AddCssClass("inactive");
var span = new TagBuilder("span");
span.SetInnerText(somestring);
li.InnerHtml = span.ToString();
</code>```

.InnerHtml now no longer accepts string because it is now IHtmlContent

but since .ToString() doesn't render the tag this doesn't work either:

```<code>li.InnerHtml = new HtmlString(span.ToString())
</code>```

it merely renders as "Microsoft.AspNet.Mvc.Rendering.TagBuilder", the name of the type.

I don't see any new methods on TagBuilder to provide the needed functionality.
What am I missing? How can I build complex nested html with TagBuilder now?

答:
Building on @Mihai's answer to show the actual code for the StringWriter approach:</p>

```<code>// Create tag builder
var builder = new TagBuilder("img");
//...
// Render tag approach also changed in .NetCore
builder.TagRenderMode = TagRenderMode.SelfClosing;

//Create the StringWriter and make TagBuilder "WriteTo" it
var stringWriter = new System.IO.StringWriter();
builder.WriteTo(stringWriter, HtmlEncoder.Default);
var tagBuilderIsFinallyAStringNow = stringWriter.ToString();
</code>```

Title: TagBuilder InnerHtml in ASP.NET 5 MVC 6

Body:
It seems to me that there are major breaking changes in TagBuilder as of beta7 with no mention about them in the announcements repo.

Specifically .ToString no longer renders the tagbuilder, it just returns the name of the type.
previously we could do things like this inside our HtmlHelper extensions to build up nested html elements:

var li = new TagBuilder("li");
li.AddCssClass("inactive");
var span = new TagBuilder("span");
span.SetInnerText(somestring);
li.InnerHtml = span.ToString();

.InnerHtml now no longer accepts string because it is now IHtmlContent

but since .ToString() doesn't render the tag this doesn't work either:

li.InnerHtml = new HtmlString(span.ToString())

it merely renders as "Microsoft.AspNet.Mvc.Rendering.TagBuilder", the name of the type.

I don't see any new methods on TagBuilder to provide the needed functionality.
What am I missing? How can I build complex nested html with TagBuilder now?

Body:
Building on @Mihai's answer to show the actual code for the StringWriter approach:

// Create tag builder
var builder = new TagBuilder("img");
//...
// Render tag approach also changed in .NetCore
builder.TagRenderMode = TagRenderMode.SelfClosing;

//Create the StringWriter and make TagBuilder "WriteTo" it
var stringWriter = new System.IO.StringWriter();
builder.WriteTo(stringWriter, HtmlEncoder.Default);
var tagBuilderIsFinallyAStringNow = stringWriter.ToString();


问:
CVS remove sticky tag from directory without update other files
I have a tree structure in CVS where I have to add a few new files
the old files have been checked-out with a tag

so when I try to add a new file:

```<code>C:\MyFolder> cvs add MyNewFile.txt
cvs add: cannot add file on non-branch tag MyTag
</code>```

答:
Why don't you just check out your branch, add the files, then return to the sticky tag? That really is the most sensible thing to do.

If you insist on doing it your way, you could try just editing that directory's CVS/Tag file to remove the sticky tag. Add your files, then change the CVS/Tag file back. (You'll have to make sure you're in the directory in question when doing the CVS operations and specify the exact files, not recursive operation.)

Body:
I have a tree structure in CVS where I have to add a few new files
the old files have been checked-out with a tag

so when I try to add a new file:

C:\MyFolder> cvs add MyNewFile.txt
cvs add: cannot add file on non-branch tag MyTag


问:
Trouble opening Ncurses Examples in OS X
I recently downloaded ncurses from  here and have compiled it using ./configure and make

As it is recommended in the README, I compiled the example programs that come bundled with the package. The programs compiled without any issue, but every time I run the programs I get the following errors:

Terminal type "xterm-256color"
terminals database is inaccessible
Changing the terminal's type using TERM=xterm and export TERM don't seem to solve this issue, and I'm just stuck. Will ncurses work if I included them in my C/C++ programs, or should I make sure the examples work?

Thanks in advance

答:
Probably you did not install the terminal database, or did not tell the programs where to find it.

OSX comes with ncurses 5.7 (old, but not the problem here), with the terminal database in /usr/share/terminfo.  However by default the configure script assumes you want to install in /usr/local.  You can tell the programs where there's a terminal database by setting the TERMINFO environment variable, or (better), setting TERMINFO_DIRS to list both locations (with the newer one first of course).

For a start, something like

```<code>export TERMINFO=/usr/share/terminfo
</code>```

should be enough to make the examples run.

Further reading:

TERMINFO

TERMINFO_DIRS

Body:
Probably you did not install the terminal database, or did not tell the programs where to find it.

OSX comes with ncurses 5.7 (old, but not the problem here), with the terminal database in /usr/share/terminfo.  However by default the configure script assumes you want to install in /usr/local.  You can tell the programs where there's a terminal database by setting the TERMINFO environment variable, or (better), setting TERMINFO_DIRS to list both locations (with the newer one first of course).

For a start, something like

export TERMINFO=/usr/share/terminfo

should be enough to make the examples run.

Further reading:

TERMINFO

TERMINFO_DIRS