问:
$.Ajax POST, accessing return data
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.

On my .cs file I have the following Webmethod

```<code>[WebMethod]
   public static string IsJobEditable(int jobid)
   {
       try
       {
           string isEditable = "false";

           JobsBLL jbl = new JobsBLL();

           int jobStatusId = jbl.GetJobStatusId(jobid);

           if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
           {
               isEditable = "true";
           }

           return isEditable;

       }
       catch (Exception ex)
       {

           throw ex;
       }
   }
</code>```

This function in this case will ALWAYS return TRUE as a string.

On Aspx page I have the following

```<code>$(function () {

           $.ajax({

               type: "POST",
               url: "Coordination.aspx/IsJobEditable",
               data: "{jobid:" + jobid + "}",
               contentType: "application/json; charset=utf-8",
               dataType: "text",
               success: function (result) {

                   alert(result);

                   // This is written out in the alert {"d":"true"}
                   // I want this in a variable as a string
                   // so I can do a check on it before I do some other actions
                   // The format is not a String so i cannot split on it to
                   // retrieve the "true" part.

               },
               error: function (err, result) { alert(err); }

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

As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.

So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).

答:
You can easily retrieve the "true" part like this:

```<code>alert(result.d);
</code>```

The reason the object is wrapped in the "d" json object is security. You can read about it for example here.

Title: $.Ajax POST, accessing return data

Body:
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.

On my .cs file I have the following Webmethod

[WebMethod]
   public static string IsJobEditable(int jobid)
   {
       try
       {
           string isEditable = "false";

           JobsBLL jbl = new JobsBLL();

           int jobStatusId = jbl.GetJobStatusId(jobid);

           if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
           {
               isEditable = "true";
           }

           return isEditable;

       }
       catch (Exception ex)
       {

           throw ex;
       }
   }

This function in this case will ALWAYS return TRUE as a string.

On Aspx page I have the following

$(function () {

           $.ajax({

               type: "POST",
               url: "Coordination.aspx/IsJobEditable",
               data: "{jobid:" + jobid + "}",
               contentType: "application/json; charset=utf-8",
               dataType: "text",
               success: function (result) {

                   alert(result);

                   // This is written out in the alert {"d":"true"}
                   // I want this in a variable as a string
                   // so I can do a check on it before I do some other actions
                   // The format is not a String so i cannot split on it to
                   // retrieve the "true" part.

               },
               error: function (err, result) { alert(err); }

           });
       });

As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.

So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).

Body:
You can easily retrieve the "true" part like this:

alert(result.d);

The reason the object is wrapped in the "d" json object is security. You can read about it for example here.


来源: stackexchange

问:
How to properly structure a mysql table with similar data
I'm having trouble coming up with a good way to define my subscriptions system. I want users to be able to subscribe to other users, posts, and tags. My initial thought was to have a subscriptions table with the following schema

```<code>id int NOT NULL AUTO_INCREMENT
user_id int NOT NULL
subscription_id int NOT NULL
subscription_type int NOT NULL
subscribe_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
unsubscribe_date timestamp NULL DEFAULT NULL
notification_frequency int NOT NULL DEFAULT 1440 //number of minutes in  day
</code>```

The subscription_type would be 0 for users, and 1 for posts and 2 for tags and the subscription_id would be the id of the row of that element, sometimes a user_id, sometimes a post_id, sometimes a tag_id.

There has got to be a better way, and the only other ways I can think of seem worse. Like making multiple subscription tables, one for each subscription_type. Or Implementing uuid fields across all users/posts/tags in my system.

There has got to be a way I can indicate there are multiple subscription types, without needing this extra column with arbitrary integer values for each type of subscription.

答:
Nope.

3 tables, or

3 SELECTs in a UNION, with or without uuids, or

3 CASE elements, each with a subquery

...

And...

Long, messy SQL, or

Long, messy application code, or

Some of each.

ContentLicense: CC BY-SA 3.0

Body:
I'm having trouble coming up with a good way to define my subscriptions system. I want users to be able to subscribe to other users, posts, and tags. My initial thought was to have a subscriptions table with the following schema

id int NOT NULL AUTO_INCREMENT
user_id int NOT NULL
subscription_id int NOT NULL
subscription_type int NOT NULL
subscribe_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
unsubscribe_date timestamp NULL DEFAULT NULL
notification_frequency int NOT NULL DEFAULT 1440 //number of minutes in  day

The subscription_type would be 0 for users, and 1 for posts and 2 for tags and the subscription_id would be the id of the row of that element, sometimes a user_id, sometimes a post_id, sometimes a tag_id.

There has got to be a better way, and the only other ways I can think of seem worse. Like making multiple subscription tables, one for each subscription_type. Or Implementing uuid fields across all users/posts/tags in my system.

There has got to be a way I can indicate there are multiple subscription types, without needing this extra column with arbitrary integer values for each type of subscription.


问:
Not Able to Run H2o Function
I was able to install h2o fine (in R) but get the following error when I run h2o.init()

h2o.init()

H2O is not running yet, starting it now...

Error in value[3L] :
  You have a 32-bit version of Java. H2O works best with 64-bit Java.
Please download the latest Java SE JDK 7 from the following URL:
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html

I updated java SE JDK version to 7 (and got the 64 bit) and am still receiving this error. Why is this?

答:
The problem you have both 32 and 64 bit of Java and then when H2O starts, it still use 32bit Java.

First solution is to remove 32bit java so only 64bit Java is there and you are good to go.

If you have to keep both 32 and 64 bit Java then you would need to setup JAVA_HOME environment variable pointing to your 64bit Java path and then start H2O. This way H2O will get 64bit Java runtime to start and you will not see the problem.

When you set JAVA_HOME make sue you set it correctly and it is pointing to 64bit Java.

Title: Not Able to Run H2o Function


问:
How to properly config a sub domain site on Forge?
I have read various questions related to this but can't seem to find an appropriate answer.

I have a Forge server that has one site on it.  The site is checked to handle wildcard sub domains.  The domain I am working with is a 3rd party domain that I have requested a sub domain CNAME record be created and pointed to the Forge IP.  This has been done and I can confirm the sub domain does point to the IP.

However, the sub domain throws a ERR_NAME_NOT_RESOLVED error.

My nginx config contains this;

```<code>server {
listen 80;
server_name *.domain.com;
root /home/forge/domain.com/public;
</code>```

Still no luck.  What am I missing here?

答:
If I understood correctly a subdomain is pointed to your server, eg test.domain.com. In such case, your code is wrong, it would work for a whole domain. For subdomain try this:

```<code>server_name sub.domain.com;
</code>```

Or this

```<code>server_name *.sub.domain.com;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have read various questions related to this but can't seem to find an appropriate answer.

I have a Forge server that has one site on it.  The site is checked to handle wildcard sub domains.  The domain I am working with is a 3rd party domain that I have requested a sub domain CNAME record be created and pointed to the Forge IP.  This has been done and I can confirm the sub domain does point to the IP.

However, the sub domain throws a ERR_NAME_NOT_RESOLVED error.

My nginx config contains this;

server {
listen 80;
server_name *.domain.com;
root /home/forge/domain.com/public;

Still no luck.  What am I missing here?

Body:
If I understood correctly a subdomain is pointed to your server, eg test.domain.com. In such case, your code is wrong, it would work for a whole domain. For subdomain try this:

server_name sub.domain.com;

Or this

server_name *.sub.domain.com;


问:
Angular Directive - ngRepeat Adding Removing from Array
I need to iterate over an object property which is an array of objects, in order to render input fields. I need to be able to dynamically add/remove objects from the array and display the corresponding elements. I'm able to add/remove objects from the array but the view is not updated. I've tried using $timeout but it's not updating the view. How can I render the correct elements based on which objects were added/removed from the array.

main template

```<code><tbody carrier></tbody>
</code>```

carrier.directive.js

```<code>angular.module('carrierModule')
.directive('carrier', carrier);
carrier.$inject = [
  '$translate',
  '$httpParamSerializer',
  '$timeout'
];
function carrier($translate, $httpParamSerializer, $timeout) {
  return {
    restrict: 'A',
    scope: {

    },
    templateUrl: 'app/carrier/carrier.tpl.html',
    link: function(scope, element, attr) {
      scope.timeRangeOptions = [
        {name: "All days of the week", value: 1},
        {name: "Discounted time per day", value: 2},
        {name: "Any time", value: 3}
      ];
      scope.carriers = {
        "Verizon": {times: [{start: "10:00", end: "12:00"}], selectedDiscountedTimeRange: scope.timeRangeOptions[0]},
        "T-Mobile": {times: [{start: "10:00", end: "12:00"}], selectedDiscountedTimeRange: scope.timeRangeOptions[0]},
        "Spring": {times: [{start: "10:00", end: "12:00"}], selectedDiscountedTimeRange: scope.timeRangeOptions[0]},
        "Orange": {times: [{start: "10:00", end: "12:00"}], selectedDiscountedTimeRange: scope.timeRangeOptions[0]}
      };
      scope.carrierOrder = ["Orange", "Spring", "T-Mobile", "Verizon"];
      scope.selectedDiscountedTimeRange = scope.timeRangeOptions[0];
      scope.addTimeFields = function(carrier) {
        $timeout(function() {
          scope.carriers[carrier].times.push({start: "10:00", end: "12:00"});
        });
      };

    }
    // link
  }
}
</code>```

carrier.tpl.html

```<code><tr ng-repeat="(carrier, value) in carriers track by $index">
  <td>
    <div class="form-inline">
      <carrier-time carriers="carriers" carrier-name="carrier" ng-repeat="time in carriers[carrier] track by $index"></carrier-time>
      <i class="fa fa-clock-o add-time-btn" aria-hidden="true" ng-click="addTimeFields(carrier)"></i>
    </div>
  </td>
</tr>
</code>```

carrier-time.directive.js

```<code>angular.module('carrierModule')
.directive('carrierTime', carrierTime);
carrierTime.$inject = [
  '$translate',
  '$httpParamSerializer',
  '$timeout'
];
function carrierTime($translate, $httpParamSerializer, $timeout) {
  return {
    restrict: 'E',
    scope: {
      carriers: '=',
      carrierName: '='
    },
    templateUrl: 'app/carrier/carrier-time.tpl.html',
    link: function(scope, element, attr) {
      scope.removeTimeFields = function(carrier) {
        $timeout(function() {
          scope.carriers[carrier].times.pop();
        });

      };
    }
    // link
  }
}

***carrier-time.tpl.html***

  <div class="form-group" ng-mouseenter="showRemoveTimeFields = !showRemoveTimeFields">
    <input class="form-control start" type="time"><span> - </span><input class="form-control end" type="time">
  </div>
  <i ng-if="showRemoveTimeFields" class="fa fa-times-circle remove-time" aria-hidden="true" ng-click="removeTimeFields(carrierName)"></i>
</code>```

答: The problem was that I wasn't looping over the correct property. My ng-repeat was missing the 'times' property i.e., ng-repeat="time in carriers[carrier].times</p>

Body:
I need to iterate over an object property which is an array of objects, in order to render input fields. I need to be able to dynamically add/remove objects from the array and display the corresponding elements. I'm able to add/remove objects from the array but the view is not updated. I've tried using $timeout but it's not updating the view. How can I render the correct elements based on which objects were added/removed from the array.

main template

carrier.directive.js

angular.module('carrierModule')
.directive('carrier', carrier);
carrier.$inject = [
  '$translate',
  '$httpParamSerializer',
  '$timeout'
];
function carrier($translate, $httpParamSerializer, $timeout) {
  return {
    restrict: 'A',
    scope: {

    },
    templateUrl: 'app/carrier/carrier.tpl.html',
    link: function(scope, element, attr) {
      scope.timeRangeOptions = [
        {name: "All days of the week", value: 1},
        {name: "Discounted time per day", value: 2},
        {name: "Any time", value: 3}
      ];
      scope.carriers = {
        "Verizon": {times: [{start: "10:00", end: "12:00"}], selectedDiscountedTimeRange: scope.timeRangeOptions[0]},
        "T-Mobile": {times: [{start: "10:00", end: "12:00"}], selectedDiscountedTimeRange: scope.timeRangeOptions[0]},
        "Spring": {times: [{start: "10:00", end: "12:00"}], selectedDiscountedTimeRange: scope.timeRangeOptions[0]},
        "Orange": {times: [{start: "10:00", end: "12:00"}], selectedDiscountedTimeRange: scope.timeRangeOptions[0]}
      };
      scope.carrierOrder = ["Orange", "Spring", "T-Mobile", "Verizon"];
      scope.selectedDiscountedTimeRange = scope.timeRangeOptions[0];
      scope.addTimeFields = function(carrier) {
        $timeout(function() {
          scope.carriers[carrier].times.push({start: "10:00", end: "12:00"});
        });
      };

    }
    // link
  }
}

carrier.tpl.html

      <carrier-time carriers="carriers" carrier-name="carrier" ng-repeat="time in carriers[carrier] track by $index"></carrier-time>

carrier-time.directive.js

angular.module('carrierModule')
.directive('carrierTime', carrierTime);
carrierTime.$inject = [
  '$translate',
  '$httpParamSerializer',
  '$timeout'
];
function carrierTime($translate, $httpParamSerializer, $timeout) {
  return {
    restrict: 'E',
    scope: {
      carriers: '=',
      carrierName: '='
    },
    templateUrl: 'app/carrier/carrier-time.tpl.html',
    link: function(scope, element, attr) {
      scope.removeTimeFields = function(carrier) {
        $timeout(function() {
          scope.carriers[carrier].times.pop();
        });

      };
    }
    // link
  }
}

***carrier-time.tpl.html***

    <input class="form-control start" type="time"> - <input class="form-control end" type="time">


问:
Get controller name from $scope
Is there a way to get the controller name from the current $scope in AngularJS?</p>

答: just this.constructor.name anywhere that the scope of that class is available once instantiated.

Title: Get controller name from $scope


问:
Getting 'too many parameters passed' to stored procedure on ASPX page
I'm having trouble figuring this error out. I have a grid on an ASPX page that displays data from a stored procedure in an SQL Server 2008 database. When the page loads, I get the following error:

```<code>"Procedure or function <sp_name> has too many arguments specified."
</code>```

Here is the code for the grid and the datasource:

```<code><asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
        AllowSorting="True">
        <Columns>
            <asp:BoundField DataField="MerchantID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="MerchantID" />
            <asp:BoundField DataField="MerchantName" HeaderText="Merchant" SortExpression="MerchantName" />
            <asp:BoundField DataField="RapidTuitionID" HeaderText="RapidTuition ID" SortExpression="RapidTuitionID" />
            <asp:BoundField DataField="DateCreated" HeaderText="Enrolled" SortExpression="DateCreated" />
            <asp:TemplateField HeaderText="Commands">
                <ItemTemplate>
                    <asp:LinkButton ID="ImpersonateUserLinkButton" runat="server" OnClick="Command_Click"
                        CommandName="impersonate" CommandArgument='<%# Eval("MerchantID") %>' CssClass="table_command">Impersonate</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            No data to display.
        </EmptyDataTemplate>
        <PagerStyle CssClass="pager" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
        SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StartDate" Name="StartDate"
                DefaultValue="1/1/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$EndDate" Name="EndDate"
                DefaultValue="12/31/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusActive" DefaultValue="true"
                Name="StatusActive" PropertyName="Checked" Type="Boolean" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusDeactive" DefaultValue="true"
                Name="StatusDeactive" PropertyName="Checked" Type="Boolean" />
        </SelectParameters>
    </asp:SqlDataSource>
</code>```

Here's the code from the stored procedure:

```<code>ALTER PROCEDURE [dbo].[sp_GatewayMerchants]
    -- Add the parameters for the stored procedure here
    @StartDate DateTime,
    @EndDate DateTime,
    @StatusActive bit,
    @StatusDeactive bit
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT
        m.MerchantID AS [ID],
        m.MerchantName,
        CASE m.StatusFlag WHEN 1 THEN 'Active' ELSE 'Deactive' END AS [Status],
        m.RapidTuitionID,
        m.DateCreated
    FROM
        Merchant m
    WHERE
        (CONVERT(varchar,m.DateCreated,112) BETWEEN CONVERT(varchar,CONVERT(DATETIME,@StartDate,101),112) AND CONVERT(varchar,CONVERT(DATETIME,@EndDate,101),112))
        AND
        (
            (@StatusActive = 1 AND m.StatusFlag = 1)
            OR
            (@StatusDeactive = 1 AND m.StatusFlag = 0)
        )
    ORDER BY
        m.MerchantName
END
</code>```

The datasource is passing 4 parameters, and the stored procedure is accepting 4, but when the page displays I get the error mentioned above. Am I missing something here?

EDIT: Here's the code behind for the template column. But I'm not sure how this could be causing extra parameters to the SP.

```<code>        protected void Command_Click(object sender, EventArgs e)
    {
        var merchantID = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        switch (((LinkButton)sender).CommandName)
        {
            case "impersonate":
                var gs = GatewaySession.Parse(Page.User.Identity.Name);
                gs.Role = GatewaySession.RoleEnum.Merchant;
                gs.MerchantID = merchantID;
                gs.CustomerID = -1;

                FormsAuthentication.SetAuthCookie(gs.ToString(), false);

                Page.Session["MerchantID"] = gs.MerchantID;

                Response.Redirect("/Merchant/Default.aspx");
                break;
        }
    }
</code>```

If I remove the ASP:LINKBUTTON the code works. So why would a LINKBUTTON be causing this?

答:
From your code it looks like you're passing 4 parameters, but let's make sure that's what's happening during design AND run time.

Design Time

In the Design view of your page, select your GridView and expand the extended menu by clicking the [>] and choose to refresh the schema. This may clear your item templates but that should be ok since you have your code saved elsewhere (i.e. here).

Run Time

Hook onto the SqlDataSource.Selecting event and check your command parameters in debug mode.

ASPX

```<code><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
    SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure"
    OnSelecting=SqlDataSource1_Selecting>
    ...
</code>```

CS

```<code>protected void SqlDataSource1_Selecting(object sender, System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs e) {
    // check e.Command.Parameters
}
</code>```

EDIT

Another thing you can try is set the DataKeyNames property of the Data

```<code><asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
    DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
    AllowSorting="True" DataKeyNames="MerchantID">
</code>```

EDIT 2

More things to try:

When you're "refreshing" your page,
make sure to not use F5 or hit the
Refresh button. Go to your browser's
address field and hit Enter as to
not have IsPostBack = true

Remove OnClick, CommandName, and
CommandArguemnt from the
LinkButton's declaration

ContentLicense: CC BY-SA 2.5

Body:
I'm having trouble figuring this error out. I have a grid on an ASPX page that displays data from a stored procedure in an SQL Server 2008 database. When the page loads, I get the following error:

"Procedure or function <sp_name> has too many arguments specified."

Here is the code for the grid and the datasource:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
        AllowSorting="True">
        <Columns>
            <asp:BoundField DataField="MerchantID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="MerchantID" />
            <asp:BoundField DataField="MerchantName" HeaderText="Merchant" SortExpression="MerchantName" />
            <asp:BoundField DataField="RapidTuitionID" HeaderText="RapidTuition ID" SortExpression="RapidTuitionID" />
            <asp:BoundField DataField="DateCreated" HeaderText="Enrolled" SortExpression="DateCreated" />
            <asp:TemplateField HeaderText="Commands">
                <ItemTemplate>
                    <asp:LinkButton ID="ImpersonateUserLinkButton" runat="server" OnClick="Command_Click"
                        CommandName="impersonate" CommandArgument='<%# Eval("MerchantID") %>' CssClass="table_command">Impersonate</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            No data to display.
        </EmptyDataTemplate>
        <PagerStyle CssClass="pager" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
        SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StartDate" Name="StartDate"
                DefaultValue="1/1/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$EndDate" Name="EndDate"
                DefaultValue="12/31/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusActive" DefaultValue="true"
                Name="StatusActive" PropertyName="Checked" Type="Boolean" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusDeactive" DefaultValue="true"
                Name="StatusDeactive" PropertyName="Checked" Type="Boolean" />
        </SelectParameters>
    </asp:SqlDataSource>

Here's the code from the stored procedure:

ALTER PROCEDURE [dbo].[sp_GatewayMerchants]
    -- Add the parameters for the stored procedure here
    @StartDate DateTime,
    @EndDate DateTime,
    @StatusActive bit,
    @StatusDeactive bit
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT
        m.MerchantID AS [ID],
        m.MerchantName,
        CASE m.StatusFlag WHEN 1 THEN 'Active' ELSE 'Deactive' END AS [Status],
        m.RapidTuitionID,
        m.DateCreated
    FROM
        Merchant m
    WHERE
        (CONVERT(varchar,m.DateCreated,112) BETWEEN CONVERT(varchar,CONVERT(DATETIME,@StartDate,101),112) AND CONVERT(varchar,CONVERT(DATETIME,@EndDate,101),112))
        AND
        (
            (@StatusActive = 1 AND m.StatusFlag = 1)
            OR
            (@StatusDeactive = 1 AND m.StatusFlag = 0)
        )
    ORDER BY
        m.MerchantName
END

The datasource is passing 4 parameters, and the stored procedure is accepting 4, but when the page displays I get the error mentioned above. Am I missing something here?

EDIT: Here's the code behind for the template column. But I'm not sure how this could be causing extra parameters to the SP.

        protected void Command_Click(object sender, EventArgs e)
    {
        var merchantID = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        switch (((LinkButton)sender).CommandName)
        {
            case "impersonate":
                var gs = GatewaySession.Parse(Page.User.Identity.Name);
                gs.Role = GatewaySession.RoleEnum.Merchant;
                gs.MerchantID = merchantID;
                gs.CustomerID = -1;

                FormsAuthentication.SetAuthCookie(gs.ToString(), false);

                Page.Session["MerchantID"] = gs.MerchantID;

                Response.Redirect("/Merchant/Default.aspx");
                break;
        }
    }

If I remove the ASP:LINKBUTTON the code works. So why would a LINKBUTTON be causing this?

Body:
From your code it looks like you're passing 4 parameters, but let's make sure that's what's happening during design AND run time.

Design Time

In the Design view of your page, select your GridView and expand the extended menu by clicking the [>] and choose to refresh the schema. This may clear your item templates but that should be ok since you have your code saved elsewhere (i.e. here).

Run Time

Hook onto the SqlDataSource.Selecting event and check your command parameters in debug mode.

ASPX

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
    SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure"
    OnSelecting=SqlDataSource1_Selecting>
    ...

CS

protected void SqlDataSource1_Selecting(object sender, System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs e) {
    // check e.Command.Parameters
}

EDIT

Another thing you can try is set the DataKeyNames property of the Data

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
    DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
    AllowSorting="True" DataKeyNames="MerchantID">

EDIT 2

More things to try:

When you're "refreshing" your page,
make sure to not use F5 or hit the
Refresh button. Go to your browser's
address field and hit Enter as to
not have IsPostBack = true

Remove OnClick, CommandName, and
CommandArguemnt from the
LinkButton's declaration


问:
"Invalid shape for y" for Keras LSTM w/ return_sequences=True (and sklearn API)
I have a sequence I am trying to classify, using a Keras LSTM with return_sequences=True. I have 'data' and 'labels' datasets both of which are the same shape - 2D matrices with rows by location and columns by time interval (cell values are my 'signal' feature). So an RNN w/ return_sequences=True seems like an intuitive approach.

After reshaping my data (X) and labels (Y) to 3D tensors of shape (rows, cols, 1), I call model.fit(X, Y) but get the following error:

ValueError('Invalid shape for y')

It points me to the code for class KerasClassifier()'s fit method which checks that len(y.shape)==2.

Ok so maybe I was supposed to reshape my 2D 'X' to a 3D Tensor of shape (rows, cols, 1) but leave my labels as 2D for sklearn interface? But then when I try that I get another Keras error:

ValueError: Error when checking model target: expected lstm_17 to have
  3 dimensions, but got array with shape (500, 2880)

...So how does one fit a Sklearn-style Keras RNN to return sequences? Different parts of Keras seem to demand that my target be both 2D and 3D. Or (more likely) I'm misunderstanding something.

...
Here's a reproduceable code example:

```<code>from keras.layers import LSTM
from keras.wrappers.scikit_learn import KerasClassifier

# Raw Data/Targets
X = np.array([1,2,3,4,5,6,7,8,9,10,11,12]).reshape(3,4)
Y = np.array([1,0,1,1,0,1,0,1,0,1,0,1]).reshape(3,4)

# Convert X to 3D tensor per Keras doc for recurrent layers
X = X.reshape(X.shape[0], X.shape[1], 1)

# .fit() at bottom will throw an error whether or not this line is used to reshape Y
to reshape Y
Y = Y.reshape(Y.shape[0], Y.shape[1], 1)

# Define function to return compiled Keras Model (to pass to Sklearn API)
def keras_rnn(timesteps, num_features):
    '''Function to return compiled Keras Classifier to pass to sklearn wrapper'''

    model = Sequential()
    model.add(LSTM(8, return_sequences=True, input_shape=(timesteps, num_features)))
    model.add(LSTM(1, return_sequences=True, activation = 'sigmoid'))

    model.compile(optimizer = 'RMSprop', loss = 'categorical_crossentropy')
    return model

# Convert compiled Keras model to Scikit-learn-style classifier (compatible w/ sklearn model-tuning methods)
rnn_sklearn = KerasClassifier(build_fn=keras_rnn,
                        timesteps=4,
                        num_features=1)

# Fit RNN Model to Data, Target
rnn_sklearn.fit(X, Y)
</code>```

ValueError: Invalid shape for y

答:
This code work with Keras 2.0.2:</p>

```<code>import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Flatten
from keras.wrappers.scikit_learn import KerasClassifier

# Raw Data/Targets
X = np.array([1,2,3,4,5,6,7,8,9,10,11,12]).reshape(3,4)
Y = np.array([1,0,1,1,0,1,0,1,0,1,0,1]).reshape(3,4)

# Convert X to 3D tensor per Keras doc for recurrent layers
X = X.reshape(X.shape[0], X.shape[1], 1)

# .fit() at bottom will throw an error whether or not this line is used to reshape Y to reshape Y
Y = Y.reshape(Y.shape[0], Y.shape[1], 1)

# Define function to return compiled Keras Model (to pass to Sklearn API)
def keras_rnn(timesteps, num_features):
    '''Function to return compiled Keras Classifier to pass to sklearn wrapper'''

    model = Sequential()
    model.add(LSTM(8, return_sequences=True, input_shape=(timesteps, num_features)))
    model.add(LSTM(1, return_sequences=True, activation = 'sigmoid'))

    model.compile(optimizer = 'RMSprop', loss = 'binary_crossentropy')
    return model

# Convert compiled Keras model to Scikit-learn-style classifier (compatible w/ sklearn model-tuning methods)
rnn_sklearn = KerasClassifier(build_fn=keras_rnn,
                        timesteps=4,
                        num_features=1)

# Fit RNN Model to Data, Target
rnn_sklearn.fit(X, Y)
</code>```

Body:
I have a sequence I am trying to classify, using a Keras LSTM with return_sequences=True. I have 'data' and 'labels' datasets both of which are the same shape - 2D matrices with rows by location and columns by time interval (cell values are my 'signal' feature). So an RNN w/ return_sequences=True seems like an intuitive approach.

After reshaping my data (X) and labels (Y) to 3D tensors of shape (rows, cols, 1), I call model.fit(X, Y) but get the following error:

ValueError('Invalid shape for y')

It points me to the code for class KerasClassifier()'s fit method which checks that len(y.shape)==2.

Ok so maybe I was supposed to reshape my 2D 'X' to a 3D Tensor of shape (rows, cols, 1) but leave my labels as 2D for sklearn interface? But then when I try that I get another Keras error:

ValueError: Error when checking model target: expected lstm_17 to have
  3 dimensions, but got array with shape (500, 2880)

...So how does one fit a Sklearn-style Keras RNN to return sequences? Different parts of Keras seem to demand that my target be both 2D and 3D. Or (more likely) I'm misunderstanding something.

...
Here's a reproduceable code example:

from keras.layers import LSTM
from keras.wrappers.scikit_learn import KerasClassifier

# Raw Data/Targets
X = np.array([1,2,3,4,5,6,7,8,9,10,11,12]).reshape(3,4)
Y = np.array([1,0,1,1,0,1,0,1,0,1,0,1]).reshape(3,4)

# Convert X to 3D tensor per Keras doc for recurrent layers
X = X.reshape(X.shape[0], X.shape[1], 1)

# .fit() at bottom will throw an error whether or not this line is used to reshape Y
to reshape Y
Y = Y.reshape(Y.shape[0], Y.shape[1], 1)

# Define function to return compiled Keras Model (to pass to Sklearn API)
def keras_rnn(timesteps, num_features):
    '''Function to return compiled Keras Classifier to pass to sklearn wrapper'''

    model = Sequential()
    model.add(LSTM(8, return_sequences=True, input_shape=(timesteps, num_features)))
    model.add(LSTM(1, return_sequences=True, activation = 'sigmoid'))

    model.compile(optimizer = 'RMSprop', loss = 'categorical_crossentropy')
    return model

# Convert compiled Keras model to Scikit-learn-style classifier (compatible w/ sklearn model-tuning methods)
rnn_sklearn = KerasClassifier(build_fn=keras_rnn,
                        timesteps=4,
                        num_features=1)

# Fit RNN Model to Data, Target
rnn_sklearn.fit(X, Y)

ValueError: Invalid shape for y

Body:
This code work with Keras 2.0.2:

import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Flatten
from keras.wrappers.scikit_learn import KerasClassifier

# Raw Data/Targets
X = np.array([1,2,3,4,5,6,7,8,9,10,11,12]).reshape(3,4)
Y = np.array([1,0,1,1,0,1,0,1,0,1,0,1]).reshape(3,4)

# Convert X to 3D tensor per Keras doc for recurrent layers
X = X.reshape(X.shape[0], X.shape[1], 1)

# .fit() at bottom will throw an error whether or not this line is used to reshape Y to reshape Y
Y = Y.reshape(Y.shape[0], Y.shape[1], 1)

# Define function to return compiled Keras Model (to pass to Sklearn API)
def keras_rnn(timesteps, num_features):
    '''Function to return compiled Keras Classifier to pass to sklearn wrapper'''

    model = Sequential()
    model.add(LSTM(8, return_sequences=True, input_shape=(timesteps, num_features)))
    model.add(LSTM(1, return_sequences=True, activation = 'sigmoid'))

    model.compile(optimizer = 'RMSprop', loss = 'binary_crossentropy')
    return model

# Convert compiled Keras model to Scikit-learn-style classifier (compatible w/ sklearn model-tuning methods)
rnn_sklearn = KerasClassifier(build_fn=keras_rnn,
                        timesteps=4,
                        num_features=1)

# Fit RNN Model to Data, Target
rnn_sklearn.fit(X, Y)


问:
Error trying to read properties file from WEB-INF directory in Spring
In my Java service, i'm trying to read the properties file as below

```<code>@Configuration
@ComponentScan(basePackages = { "com.site.xxx.*" })
@PropertySource("classpath:application.properties")
@Service("someService")
public class SomeService {
    @Autowired
    private Environment env;
    ...
}
</code>```

And then in one of my methods, I do

```<code>String closeDate = env.getProperty("close.date");
</code>```

There are 2 problems here either of which I could work with as a solution.

1> This works in a way that it does read the file if my application.properties file is in the classpath. I put it under src/main/resources and it reads the file BUT after I deploy the change, if I change the date inside this property file, it still shows me the first date which was entered when the code was compiled. So the reading part works but it doesn't change when I change the file contents.

2> If I change the contents of the following line

```<code>@PropertySource("classpath:WEB-INF/application.properties")
</code>```

and if I place the file under my WEB-INF directory, even though the file is present, it says File Not Found.

I would very much prefer #2 to work but if there is no way that it can work (which I don't think), I can work with #1 as long as it behaves like a property file.

答:
Spring loads the property files during the container startup, so whenever you change the property inside application.properties, you need to restart your server. So, that might be a reason your option(1) is not working.

If you wanted to work with option(2), you can configure the PropertySource with file: (not classpath:) as shown below and you need to set myproject.home (or any other name of your choice) as the environment (OS) or system variable.

```<code>@PropertySource("file:${myproject.home}/WEB-INF/application.properties")
</code>```

Do property file changes usually warrant a server restart?

Yes, they need a container restart.

Body:
In my Java service, i'm trying to read the properties file as below

@Configuration
@ComponentScan(basePackages = { "com.site.xxx.*" })
@PropertySource("classpath:application.properties")
@Service("someService")
public class SomeService {
    @Autowired
    private Environment env;
    ...
}

And then in one of my methods, I do

String closeDate = env.getProperty("close.date");

There are 2 problems here either of which I could work with as a solution.

1> This works in a way that it does read the file if my application.properties file is in the classpath. I put it under src/main/resources and it reads the file BUT after I deploy the change, if I change the date inside this property file, it still shows me the first date which was entered when the code was compiled. So the reading part works but it doesn't change when I change the file contents.

2> If I change the contents of the following line

@PropertySource("classpath:WEB-INF/application.properties")

and if I place the file under my WEB-INF directory, even though the file is present, it says File Not Found.

I would very much prefer #2 to work but if there is no way that it can work (which I don't think), I can work with #1 as long as it behaves like a property file.

Body:
Spring loads the property files during the container startup, so whenever you change the property inside application.properties, you need to restart your server. So, that might be a reason your option(1) is not working.

If you wanted to work with option(2), you can configure the PropertySource with file: (not classpath:) as shown below and you need to set myproject.home (or any other name of your choice) as the environment (OS) or system variable.

@PropertySource("file:${myproject.home}/WEB-INF/application.properties")

Do property file changes usually warrant a server restart?

Yes, they need a container restart.


问:
I want to get user information with the json web token assigned to the user
I am trying to create a policy that allows only an Admin to view a page. I  have shown the policy below, but it's not returning the right user.</p>

```<code>module.exports = function (req, res, next) {

  User.findOne({ id: token.id }, function (err, user) {
    console.log(user);
    if (err) throw (err);
    if (user.permission === "admin") {
      return next();

    }

    return res.send("You Must be an ADMIN to perform this task");
  });

};
</code>```

答:
You need to verify and parse the passed token with jwt methods and then find the user by id extracted from the token:

```<code>exports.me = function(req,res){
    if (req.headers && req.headers.authorization) {
        var authorization = headers.authorization,
            decoded;
        try {
            decoded = jwt.verify(authorization, secret.secretToken);
        } catch (e) {
            return res.status(401).send('unauthorized');
        }
        var userId = decoded.id;
        // Fetch the user by id
        User.findOne({_id: userId}).then(function(user){
            // Do something with the user
            return res.send(200);
        });
    }
    return res.send(500);
}
</code>```

source : NodeJs - Retrieve user infor from JWT token?

Body:
I am trying to create a policy that allows only an Admin to view a page. I  have shown the policy below, but it's not returning the right user.

module.exports = function (req, res, next) {

  User.findOne({ id: token.id }, function (err, user) {
    console.log(user);
    if (err) throw (err);
    if (user.permission === "admin") {
      return next();

    }

    return res.send("You Must be an ADMIN to perform this task");
  });

};

Body:
You need to verify and parse the passed token with jwt methods and then find the user by id extracted from the token:

exports.me = function(req,res){
    if (req.headers && req.headers.authorization) {
        var authorization = headers.authorization,
            decoded;
        try {
            decoded = jwt.verify(authorization, secret.secretToken);
        } catch (e) {
            return res.status(401).send('unauthorized');
        }
        var userId = decoded.id;
        // Fetch the user by id
        User.findOne({_id: userId}).then(function(user){
            // Do something with the user
            return res.send(200);
        });
    }
    return res.send(500);
}

source : NodeJs - Retrieve user infor from JWT token?


问:
Windows Forms: ToolStripDropDown - Remove or Paint border
I have a ToolStripDropDown control labeled 'options' here:

I want to either remove the border or paint it a certain color to make it flush. Do I need a new renderer or something to do this? I've been unable to find an example online.

答:
Yes, you have to make your own renderer:

```<code>public class BorderlessRenderer : ToolStripProfessionalRenderer {

  public BorderlessRenderer () {
    RoundedEdges = false;
  }

  protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
    //base.OnRenderToolStripBorder(e);
  }
}
</code>```

Then apply it to your ToolStrip control:

```<code>toolStrip1.Renderer = new BorderlessRenderer();
</code>```

Body:
Yes, you have to make your own renderer:

public class BorderlessRenderer : ToolStripProfessionalRenderer {

  public BorderlessRenderer () {
    RoundedEdges = false;
  }

  protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
    //base.OnRenderToolStripBorder(e);
  }
}

Then apply it to your ToolStrip control:

toolStrip1.Renderer = new BorderlessRenderer();


问:
How to save an object in a file using nodejs
My code is this:

```<code>fs.writeFile("file.bin", this, 'binary', function(err){
  if(err) console.log(err);
  else console.log("file saved");
});
</code>```

This is inside a function with a bunch of attributes.
If I do console.log(this), it shows the object but when I save it, the file has only this:

```<code>[object Object]
</code>```

Since I didn't get the answer I wanted, I want to clarify a bit what I want.
I want my object to be stored as an object but not as a json file or txt file. If I have a mp3 stream for example, I want this stream to be stored as a mp3 file not a json file. Someone knows how to do this?

答:
From the Node documentation for FileSystem, the second parameter needs to be a string, buffer or UintArray.
To persist the object to the file, convert the object to a string using JSON.stringify(obj) and call the fs.writeFile() API.

Here is the code snippet for the same:

```<code>fs.writeFile("file.bin", JSON.stringify(obj), 'binary', (err)=>{
   if(err) console.log(err)
   else console.log('File saved')
})
</code>```

Another way is to use a buffer in place of the string.

```<code>var buffer = Buffer.from(JSON.stringify(obj))
fs.writeFile("file.bin", buffer, 'binary', (err)=>{
   if(err) console.log(err)
   else console.log('File saved')
})
</code>```

Body:
My code is this:

fs.writeFile("file.bin", this, 'binary', function(err){
  if(err) console.log(err);
  else console.log("file saved");
});

This is inside a function with a bunch of attributes.
If I do console.log(this), it shows the object but when I save it, the file has only this:

[object Object]

Since I didn't get the answer I wanted, I want to clarify a bit what I want.
I want my object to be stored as an object but not as a json file or txt file. If I have a mp3 stream for example, I want this stream to be stored as a mp3 file not a json file. Someone knows how to do this?

Body:
From the Node documentation for FileSystem, the second parameter needs to be a string, buffer or UintArray.
To persist the object to the file, convert the object to a string using JSON.stringify(obj) and call the fs.writeFile() API.

Here is the code snippet for the same:

fs.writeFile("file.bin", JSON.stringify(obj), 'binary', (err)=>{
   if(err) console.log(err)
   else console.log('File saved')
})

Another way is to use a buffer in place of the string.

var buffer = Buffer.from(JSON.stringify(obj))
fs.writeFile("file.bin", buffer, 'binary', (err)=>{
   if(err) console.log(err)
   else console.log('File saved')
})


问:
How to ask perforce for a list of changes with both description and files
I want to get a list of changes for a perforce branch like:

p4 -t -L //mydepot/library1/v1.0/...@2017/03/27,@now

That is, a list of all changes this week with description. But I also want a list of the files, as in
files in one changelist:

p4 files @=123456

This seems like it needs script, but anyone know of a perforce method?
If the returned changeset collection is large, will the server be adversely impacted by querying every changeset afterwards?

答:
```<code>p4 -Ztag -F "describe -s %change%" changes //mydepot/library1/v1.0/...@2017/03/27,@now | p4 -x - run
</code>```

The answer to the performance question depends on how many is "large" (how many changes/files are we talking about) and your server hardware.

My guess is that with a "normal" server and "normal" usage you'll be fine but if we're talking about a few billion changes with a few billion files each, yeah, those commands will take a while.  If we're more in the hundreds or thousands range, meh.

Body:
p4 -Ztag -F "describe -s %change%" changes //mydepot/library1/v1.0/...@2017/03/27,@now | p4 -x - run

The answer to the performance question depends on how many is "large" (how many changes/files are we talking about) and your server hardware.

My guess is that with a "normal" server and "normal" usage you'll be fine but if we're talking about a few billion changes with a few billion files each, yeah, those commands will take a while.  If we're more in the hundreds or thousands range, meh.


问:
How to refer to specific item in JSON android?
I'm following a tutorial on JSON in android. I've managed to output JSON from the file into ListView. However, I don't quite understand how referring to specific item works.
Here is json file:

```<code>    {
  "contacts": [
    {
      "id": "c200",
      "name": "Ravi Tamada",
      "email": "ravi@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender" : "male",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    },
    {
      "id": "c201",
      "name": "Figaro",
      "email": "figaro@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender" : "male",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    },
    {
      "id": "c202",
      "name": "Johnny Depp",
      "email": "johnny_depp@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender" : "female",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    }
  ]
}
</code>```

First thing: How can I output items for example with "gender = male" only?
Second thing: Whenever I press for example on Ravi Tamada in my ListView, how can I make it load up it's mobile only? in other words, how can I set the link between the item I press and the information that should be displayed, while taking into account its relation to the pressed item?

This is how I retrive items from json:

```<code> switch (view.getId()){

            case R.id.button1:
                loadmyjson();
                try {
                    JSONObject jsonObj = new JSONObject(jsonString);

                    JSONArray letters = jsonObj.getJSONArray("contacts");
                    for (int i = 0; i < letters.length(); i++){
                        JSONObject first = letters.getJSONObject(i);
                        String gender = first.getString("gender");
                        Log.e("and that means", " " + gender);

                        if (first.getString("name") == "Figaro"){
                            where.add(gender);

                        }

                         }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e("and that means", " " + where);

                break;

        }
</code>```

The problem is that this if statement is always false.

答: Instead first.getString("name") == "Figaro" try first.getString("name").equals("Figaro")

Body:
I'm following a tutorial on JSON in android. I've managed to output JSON from the file into ListView. However, I don't quite understand how referring to specific item works.
Here is json file:

    {
  "contacts": [
    {
      "id": "c200",
      "name": "Ravi Tamada",
      "email": "ravi@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender" : "male",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    },
    {
      "id": "c201",
      "name": "Figaro",
      "email": "figaro@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender" : "male",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    },
    {
      "id": "c202",
      "name": "Johnny Depp",
      "email": "johnny_depp@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender" : "female",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    }
  ]
}

First thing: How can I output items for example with "gender = male" only?
Second thing: Whenever I press for example on Ravi Tamada in my ListView, how can I make it load up it's mobile only? in other words, how can I set the link between the item I press and the information that should be displayed, while taking into account its relation to the pressed item?

This is how I retrive items from json:

 switch (view.getId()){

            case R.id.button1:
                loadmyjson();
                try {
                    JSONObject jsonObj = new JSONObject(jsonString);

                    JSONArray letters = jsonObj.getJSONArray("contacts");
                    for (int i = 0; i < letters.length(); i++){
                        JSONObject first = letters.getJSONObject(i);
                        String gender = first.getString("gender");
                        Log.e("and that means", " " + gender);

                        if (first.getString("name") == "Figaro"){
                            where.add(gender);

                        }

                         }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e("and that means", " " + where);

                break;

        }

The problem is that this if statement is always false.


问:
Algorithm for automatic channel detection
I'm currently working on a spare-time project to perform automatic modulation classification (AMC) on radio signals (more precisely, I'm interested in L-band satellite channels), using SDR. I would like it to be able to discover channels in the power spectrum, along with their frequencies and bandwidths, so I can direct the application of AMC on the output of this step.

My first (naive) approach was rather simple: after every N samples (say 1024) apply a window function, perform the FFT on the last N, compute an estimation of the power spectrum and apply some exponential smoothing to reduce the noise. Then, in the smoothed power spectrum, find the maximum and minimum signal levels, calculate some threshold value based on a weighted mean of both levels and use this threshold to determine which frequency bins belong to a channel.

This works well in my unit tests (one QPSK channel + gaussian noise). However, in real-life scenarios I either get a few channels or a lot of false-positives. Of course I can fix this by fine-tuning the weights in the threshold calculation, but then it wouldn't be automatic anymore.

I've been doing some research on Google but maybe I'm not using the right search keywords, or there is no real interest on this subject (which would be strange, as frequency scanners must perform this task somehow).

How could I find the appropriate values for the mean weights? Maybe there is a better approach than calculating a threshold for the whole spectrum?

答:
After considering Marcus Müller's suggestion, I developed an algorithm that still relies on a global energy threshold but also on an estimation of the noise floor. It can be improved in many ways, but as its simplest realization already provides acceptable results with real-world captures (again, L-band captures at 250 ksps) I believe it could be a good ground for other people to start with.

The central idea of the algorithm is to calculate the energy threshold based on a continuous estimation of the noise power, updating it with every update of the spectrogram. This estimation keeps track of the maximum and minimum levels attained by each FFT bin after during all FFT runs, using them to estimate the PSD in that bin and discard outliers (i.e. channels, spurs...). The algorithm is to be executed every fixed number of samples. More formally:

Parameters of the algorithm:

```<code>int N        /* spectrogram length (FFT bins) */
complex x[N] /* last N samples */
float alpha  /* spectrogram smoothing factor between 0 (infinite smoothing,
                spectrogram will never be updated) and 1 (no smoothing at all) */
float beta   /* level decay factor between 0 (levels will never decay) and 1
                (levels will be equal to the spectrogram). */
float gamma  /* smooth factor applied to updates of the current noise estimation
                between 0 (no updates allowed) and 1 /* no smoothing */
float SNR    /* detection threshold above noise, in dB */
</code>```

Recommended values for alpha, beta and gamma are 1e-2, 1e-3 and .5 respectively.

Variables:

```<code>complex dft[N]  /* Fourier transform of the last N samples */
float spect[N]  /* smoothed spectrogram */
float spmin[N]  /* lower levels for spectrogram bins */
float spmax[N]  /* upper levels for spectrogram bins */
int runs        /* FFT run counter (initially zero) */
float N0        /* Current noise level estimation */
float new_N0    /* New noise level estimation */
float min_pwr   /* Minimum power density found */
int min_pwr_bin /* FFT bin where min_pwr is */
int valid       /* Number of valid bins for noise estimation */
int min_runs    /* Minimum number of runs required to detect channels */
</code>```

Algorithm:

```<code>min_runs = max(2. / alpha, 1. / beta)
dft = FFT(x);
++runs;
if (runs == 1) then /* First FFT run */
    spect = dft * conj(dft) /* |FFT(x)|^2 */
    spmin = spect /* Copy spect to spmin */
    spmax = spect /* Copy spect to spmax */
    N0    = min(spect); /* First noise estimation */
else
    /* Smooth spectrogram w.r.t the previous run */
    spect += alpha * (dft * conj(dft) - spect)

    /* Update levels. This has to be performed element-wise  */
    new_N0 = 0
    valid = 0
    min_pwr = INFINITY
    min_pwr_bin = -1
    for (int i = 0; i < N; ++i)
        /* Update current lower levels or raise them */
        if (spect[i] < spmin[i]) then
            spmin[i] = spect[i]
        else
            spmin[i] += beta * (spect[i] - spmin[i]);
        end

        /* Update current upper levels or decrease them */
        if (spect[i] > spmax[i]) then
            spmax[i] = spect[i]
        else
            spmax[i] += beta * (spect[i] - spmax[i]);
        end

        if (runs > min_runs) then
            /* Use previous N0 estimation to detect outliers */
            if (spmin[i] < N0 or N0 < spmax[i]) then
                new_N0 += spect[i]
                ++valid
            end

            /* Update current minimum power */
            if (spect[i] < min_pwr) then
                min_pwr = spect[i]
                min_pwr_bin = i
            end
        end
    end

    /*
     * Check whether levels have stabilized and update noise
     * estimation accordingly
     */
    if (runs > min_runs) then
        /*
         * This is a key step: if the number of valid bins is
         * 0 this means that our previous estimation was
         * absolutely wrong. We reset it with a cruder estimation
         * based on where the minimum value of the current
         * spectrogram was found
         */

        if (valid == 0) then
            N0 = .5 * (spmin[min_pwr_bin] + spmax[min_pwr_bin])
        else
            N0 += gamma * (new_N0 / valid - N0)
        end

        /*
         * Detect channels based on this threshold (trivial,
         * not detailed)
         */

        detect_channels(spect, 10^(SNR / 10) * N0)
    end
end
</code>```

Even though this algorithm makes the strong assumption that the noise floor is flat (which is false in most cases as in real-world radios, tuner output passes through a low-pass filter whose response is not flat), it works even if this condition doesn't hold. These are some of the algorithm results for different values of alpha, N = 4096 and SNR = 3 dB. Noise estimation is marked in yellow, channel threshold in green, upper levels in red, spectrogram in white and lower levels in cyan. I also provide an evolution of the N0 estimation after every FFT run:

Results for alpha = 1e-1:

Results for alpha = 1e-2. Note how the number of valid bins has been reduced as the spectrogram got clearer:

Results for alpha = 1e-3. In this case, the levels are so tight and the noise floor so obviously non-flat that there are novalid bins from one FFT run to another. In this case we fall back to the crude estimation of looking for the bin with the lowest power density:

The min_runs calculation is critical. To prevent the noise level to updrift (this is, to follow a channel and not the noise floor) we must wait at least 2. / alpha FFT runs before trusting the signal levels. This value was found experimentally: in my previous implementations, I was intuitively using 1. / alpha which failed miserably for alpha = 1e-3:

I haven't tested this yet on other scenarios (like burst transmissions) where this algorithm may not perform as well as with continuous channels because of the persistence of min/max levels, and it may fail to detect burst transmissions as outliers. However, given the kind of channels I'm working with, this is not a priority for now.

Body:
After considering Marcus Müller's suggestion, I developed an algorithm that still relies on a global energy threshold but also on an estimation of the noise floor. It can be improved in many ways, but as its simplest realization already provides acceptable results with real-world captures (again, L-band captures at 250 ksps) I believe it could be a good ground for other people to start with.

The central idea of the algorithm is to calculate the energy threshold based on a continuous estimation of the noise power, updating it with every update of the spectrogram. This estimation keeps track of the maximum and minimum levels attained by each FFT bin after during all FFT runs, using them to estimate the PSD in that bin and discard outliers (i.e. channels, spurs...). The algorithm is to be executed every fixed number of samples. More formally:

Parameters of the algorithm:

int N        /* spectrogram length (FFT bins) */
complex x[N] /* last N samples */
float alpha  /* spectrogram smoothing factor between 0 (infinite smoothing,
                spectrogram will never be updated) and 1 (no smoothing at all) */
float beta   /* level decay factor between 0 (levels will never decay) and 1
                (levels will be equal to the spectrogram). */
float gamma  /* smooth factor applied to updates of the current noise estimation
                between 0 (no updates allowed) and 1 /* no smoothing */
float SNR    /* detection threshold above noise, in dB */

Recommended values for alpha, beta and gamma are 1e-2, 1e-3 and .5 respectively.

Variables:

complex dft[N]  /* Fourier transform of the last N samples */
float spect[N]  /* smoothed spectrogram */
float spmin[N]  /* lower levels for spectrogram bins */
float spmax[N]  /* upper levels for spectrogram bins */
int runs        /* FFT run counter (initially zero) */
float N0        /* Current noise level estimation */
float new_N0    /* New noise level estimation */
float min_pwr   /* Minimum power density found */
int min_pwr_bin /* FFT bin where min_pwr is */
int valid       /* Number of valid bins for noise estimation */
int min_runs    /* Minimum number of runs required to detect channels */

Algorithm:

min_runs = max(2. / alpha, 1. / beta)
dft = FFT(x);
++runs;
if (runs == 1) then /* First FFT run */
    spect = dft * conj(dft) /* |FFT(x)|^2 */
    spmin = spect /* Copy spect to spmin */
    spmax = spect /* Copy spect to spmax */
    N0    = min(spect); /* First noise estimation */
else
    /* Smooth spectrogram w.r.t the previous run */
    spect += alpha * (dft * conj(dft) - spect)

    /* Update levels. This has to be performed element-wise  */
    new_N0 = 0
    valid = 0
    min_pwr = INFINITY
    min_pwr_bin = -1
    for (int i = 0; i < N; ++i)
        /* Update current lower levels or raise them */
        if (spect[i] < spmin[i]) then
            spmin[i] = spect[i]
        else
            spmin[i] += beta * (spect[i] - spmin[i]);
        end

        /* Update current upper levels or decrease them */
        if (spect[i] > spmax[i]) then
            spmax[i] = spect[i]
        else
            spmax[i] += beta * (spect[i] - spmax[i]);
        end

        if (runs > min_runs) then
            /* Use previous N0 estimation to detect outliers */
            if (spmin[i] < N0 or N0 < spmax[i]) then
                new_N0 += spect[i]
                ++valid
            end

            /* Update current minimum power */
            if (spect[i] < min_pwr) then
                min_pwr = spect[i]
                min_pwr_bin = i
            end
        end
    end

    /*
     * Check whether levels have stabilized and update noise
     * estimation accordingly
     */
    if (runs > min_runs) then
        /*
         * This is a key step: if the number of valid bins is
         * 0 this means that our previous estimation was
         * absolutely wrong. We reset it with a cruder estimation
         * based on where the minimum value of the current
         * spectrogram was found
         */

        if (valid == 0) then
            N0 = .5 * (spmin[min_pwr_bin] + spmax[min_pwr_bin])
        else
            N0 += gamma * (new_N0 / valid - N0)
        end

        /*
         * Detect channels based on this threshold (trivial,
         * not detailed)
         */

        detect_channels(spect, 10^(SNR / 10) * N0)
    end
end

Even though this algorithm makes the strong assumption that the noise floor is flat (which is false in most cases as in real-world radios, tuner output passes through a low-pass filter whose response is not flat), it works even if this condition doesn't hold. These are some of the algorithm results for different values of alpha, N = 4096 and SNR = 3 dB. Noise estimation is marked in yellow, channel threshold in green, upper levels in red, spectrogram in white and lower levels in cyan. I also provide an evolution of the N0 estimation after every FFT run:

Results for alpha = 1e-1:

Results for alpha = 1e-2. Note how the number of valid bins has been reduced as the spectrogram got clearer:

Results for alpha = 1e-3. In this case, the levels are so tight and the noise floor so obviously non-flat that there are novalid bins from one FFT run to another. In this case we fall back to the crude estimation of looking for the bin with the lowest power density:

The min_runs calculation is critical. To prevent the noise level to updrift (this is, to follow a channel and not the noise floor) we must wait at least 2. / alpha FFT runs before trusting the signal levels. This value was found experimentally: in my previous implementations, I was intuitively using 1. / alpha which failed miserably for alpha = 1e-3:

I haven't tested this yet on other scenarios (like burst transmissions) where this algorithm may not perform as well as with continuous channels because of the persistence of min/max levels, and it may fail to detect burst transmissions as outliers. However, given the kind of channels I'm working with, this is not a priority for now.


问:
iOS mobile safari - the bottom bar covers my footer
iOS mobile safari has the address and bottom nav bar that come into view when you scroll upwards, and hide/minimize when you scroll down. I have a footer in my UI that gets hidden by the bottom nav bar, and I'm not sure what the best way to go about fixing this is. I could use javascript to detect the browser I'm using and then edit the css accordingly, but I wanted to know if there was a better, CSS only solution.

EDIT:
I found a few examples of sites that do what I need, but I can't seem to duplicate their behavior.

http://fetedelabiere.promo-agency.com/mobile/instant-verif-age

http://www.mountaindew.com/

http://fornacestudio.com/mobileapp/#projects

答:
One solution could be to give a little more of padding-bottom to your main container in order to leave some space to the iPhone bottom bar.

Just use this code to target the mobiles with Safari:

```<code>@media screen and (max-width: 767px) {
    _::-webkit-full-page-media, _:future, :root .safari_only {
        padding-bottom: 65px; //resize
    }
}
</code>```

And don't forget to add the .safari_only class to the element you want to target (should be your main container), example:

```<code><div class='safari_only'> This div will have a padding-bottom:65px in a mobile with Safari  </div>
</code>```

One detail: this is gonna affect also the Safari browser on Android devices, but fortunately not many users use Safari on an Android device, anyway if you need it you can use another css rule for overwriting that rule on Android.

Body:
One solution could be to give a little more of padding-bottom to your main container in order to leave some space to the iPhone bottom bar.

Just use this code to target the mobiles with Safari:

@media screen and (max-width: 767px) {
    _::-webkit-full-page-media, _:future, :root .safari_only {
        padding-bottom: 65px; //resize
    }
}

And don't forget to add the .safari_only class to the element you want to target (should be your main container), example:

<div class='safari_only'> This div will have a padding-bottom:65px in a mobile with Safari  </div>

One detail: this is gonna affect also the Safari browser on Android devices, but fortunately not many users use Safari on an Android device, anyway if you need it you can use another css rule for overwriting that rule on Android.


问:
Azure Storage Account files not accessible by app
Adding a network drive e.g. net use T: \.file.core.windows.net\ etc., or through the power shell command, on an Azure Windows VM works and files are accessible in power shell, drag and drop, etc., but application running on the VM (even under same user) cannot read files. "Could not open file ... DirectoryNotFoundException - Could not find a part of the path ...". What is going on? And it works locally on my development machine.</p>

答:
How are you mounting the Azure File share and with what account? Probably what's causing you problems is that the credentials only count for that specific context, with context being the credentials being used and how they are authenticated.

For example, if you mount an Azure File Share from within a command line window in non-administrative mode, then the account you use will be able to access that file share in non-administrative mode. If you log in as a different user, you will no longer have access to the file share, because it's not the same user you used before. If you open a command line window in administrative mode and try to access the file share, you won't be able to, because admin-mode and non-admin mode are two different contexts.

You have to mount the drive with the account that is going to use it. I tried to mount and use a file share in a windows service a couple of years ago, and found that I couldn't set up the credentials under the account used by the windows service, even if I tried running the windows service under a specific account and not a system account, because apparently running as a service is yet another context.

If you can't mount the drive with the same context as whatever is using it, you can mount the drive programmatically. There is sample code for this in one of the Azure Storage team's original blog entries about persisting connections to Azure File shares. This is how I finally got my windows service to run successfully.


问:
Why do Guava classes provide so many factory methods instead of just one that takes varargs?

Possible Duplicate:

  Why does Guava's ImmutableList have so many overloaded of() methods?

Looking at Guava's ImmutableList (and some other classes), you'll find plenty of overloaded of convenience methods ("Returns an immutable list containing the given elements, in order.") that take a different number of parameters:

```<code>...
public static <E> ImmutableList<E> of(E e1, E e2, E e3)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
...
</code>```

All the way to this one:

```<code>public static <E> ImmutableList<E> of(E e1,
                                      E e2,
                                      E e3,
                                      E e4,
                                      E e5,
                                      E e6,
                                      E e7,
                                      E e8,
                                      E e9,
                                      E e10,
                                      E e11,
                                      E e12,
                                      E... others)
</code>```

Some colleagues of mine consider this silly, wondering why there's isn't just one method: of(E... elements).  They suspect it's an ill-guided performance "optimisation" that falls into the category "do you think you're smarter than compiler", or something like that.

My hunch is that Kevin Bourrillion et al. put these methods in there for a real reason. Can anyone explain (or speculate) what that reason might be?

答: I think it's to avoid unchecked generic array creation warning when E is a generic type.

Body:
Possible Duplicate:

  Why does Guava's ImmutableList have so many overloaded of() methods?

Looking at Guava's ImmutableList (and some other classes), you'll find plenty of overloaded of convenience methods ("Returns an immutable list containing the given elements, in order.") that take a different number of parameters:

...
public static <E> ImmutableList<E> of(E e1, E e2, E e3)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
...

All the way to this one:

public static <E> ImmutableList<E> of(E e1,
                                      E e2,
                                      E e3,
                                      E e4,
                                      E e5,
                                      E e6,
                                      E e7,
                                      E e8,
                                      E e9,
                                      E e10,
                                      E e11,
                                      E e12,
                                      E... others)

Some colleagues of mine consider this silly, wondering why there's isn't just one method: of(E... elements).  They suspect it's an ill-guided performance "optimisation" that falls into the category "do you think you're smarter than compiler", or something like that.

My hunch is that Kevin Bourrillion et al. put these methods in there for a real reason. Can anyone explain (or speculate) what that reason might be?


问:
How to execute Vim substitute command without effect the current searching pattern?
I want to jump to the lines containing certain pattern and determine whether or not to apply :s command.

But after applying :s command, the '/' register was replaced by the pattern in the :s command,
and it wasn't very convenient to jump with original pattern.

So, does it have a comfortable way to achieve this task?

Thanks!

答:
Vim (version 8+) provides the :keeppatterns command which prevents the search register from being altered by your command. Example:

```<code>:keeppatterns %s/foo/bar/g
</code>```

For more help see :h :keeppatterns.

Body:
Vim (version 8+) provides the :keeppatterns command which prevents the search register from being altered by your command. Example:

:keeppatterns %s/foo/bar/g

For more help see :h :keeppatterns.


问:
React: Is it possible to prevent state update after unmount, via setting this.setState to empty function?
I am facing the problem that a network callback is trying to setState() of an unmounted component and receive the default console warning about this no-op.

It wasn't possible for me to track why the unmount happens but I found a solution suggesting to set the function to nothing in componentWillUnmount(). It didn't work and I tested to set this.setState to nothing. See below.

The error disappears but I want to ask whether that is a valid solution. Here the code:

```<code>  componentDidMount() {
    this.fetchLogItems(10, 'recentChanges');
  }

  componentWillUnmount() {
    this.setState = () => {};
  }

  fetchLogItems = (limit, stateRef) => {
    let tmpObj = {};
    base.fetch('_changelogs', {
      context: this,
      then(data) {
        tmpObj[stateRef] = {...data}
        tmpObj.loading = false;
        this.setState({...tmpObj})
      },
      catch(err){console.error(err)}
    });
  };
</code>```

答:
Two options:

be sure that whatever helpers that you are using also allow for the use of "destructors" (cancellations, and I definitely prefer the use of "cancellations")

if not, then you may introduce a "flag" to your class

If your library allows for some "cancellation", "destruction", or "cleanup", then you may simply do:

```<code>componentWillUnmount() {
  base.cancelFetch(); // or something similar.
}
</code>```

Otherwise, you may be able to introduce a class property to your component. Perhaps name it isUnmounted. In componentWillUnmount, set this.isUmounted to true. Wrap the this.setState call in an if-statement that checks if isUnmounted is false, and if it is, then you may call this.setState. This is actually a very common pattern.

It may "feel" ugly, but, by defacto, this pattern seems to be idiomatic among React developers. If not, at least it is a pragmatic solution to problems similar to yours.

```<code>constructor() {
  // HERE
  this.isUmounted = false;
}

componentDidMount() {
  this.fetchLogItems(10, 'recentChanges');
}

componentWillUnmount() {
  // HERE
  this.isUmounted = true;
}

fetchLogItems = (limit, stateRef) => {
  let tmpObj = {};
  base.fetch('_changelogs', {
    context: this,
    then(data) {
      tmpObj[stateRef] = {...data}
      tmpObj.loading = false;
      // WRAP THE `this.setState` here.
      if (!this.isUnmounted) {
        this.setState({...tmpObj})
      }
    },
    catch(err){console.error(err)}
  });
};
</code>```

However, I prefer the use of libraries and helpers that support cancellation. It's definitely guarantees some level of cleanup. Without cancellation, we risk introducing memory leaks.

Body:
I am facing the problem that a network callback is trying to setState() of an unmounted component and receive the default console warning about this no-op.

It wasn't possible for me to track why the unmount happens but I found a solution suggesting to set the function to nothing in componentWillUnmount(). It didn't work and I tested to set this.setState to nothing. See below.

The error disappears but I want to ask whether that is a valid solution. Here the code:

  componentDidMount() {
    this.fetchLogItems(10, 'recentChanges');
  }

  componentWillUnmount() {
    this.setState = () => {};
  }

  fetchLogItems = (limit, stateRef) => {
    let tmpObj = {};
    base.fetch('_changelogs', {
      context: this,
      then(data) {
        tmpObj[stateRef] = {...data}
        tmpObj.loading = false;
        this.setState({...tmpObj})
      },
      catch(err){console.error(err)}
    });
  };

Body:
Two options:

be sure that whatever helpers that you are using also allow for the use of "destructors" (cancellations, and I definitely prefer the use of "cancellations")

if not, then you may introduce a "flag" to your class

If your library allows for some "cancellation", "destruction", or "cleanup", then you may simply do:

componentWillUnmount() {
  base.cancelFetch(); // or something similar.
}

Otherwise, you may be able to introduce a class property to your component. Perhaps name it isUnmounted. In componentWillUnmount, set this.isUmounted to true. Wrap the this.setState call in an if-statement that checks if isUnmounted is false, and if it is, then you may call this.setState. This is actually a very common pattern.

It may "feel" ugly, but, by defacto, this pattern seems to be idiomatic among React developers. If not, at least it is a pragmatic solution to problems similar to yours.

constructor() {
  // HERE
  this.isUmounted = false;
}

componentDidMount() {
  this.fetchLogItems(10, 'recentChanges');
}

componentWillUnmount() {
  // HERE
  this.isUmounted = true;
}

fetchLogItems = (limit, stateRef) => {
  let tmpObj = {};
  base.fetch('_changelogs', {
    context: this,
    then(data) {
      tmpObj[stateRef] = {...data}
      tmpObj.loading = false;
      // WRAP THE `this.setState` here.
      if (!this.isUnmounted) {
        this.setState({...tmpObj})
      }
    },
    catch(err){console.error(err)}
  });
};

However, I prefer the use of libraries and helpers that support cancellation. It's definitely guarantees some level of cleanup. Without cancellation, we risk introducing memory leaks.


问:
Subview is the wrong size
Unfortunately I'm stuck with a xib that I'm loading into scrollview and it's not behaving as I'm expecting it to.

Unless I set self.view.frame.size.height and self.view.frame.size.width, the subview is the wrong size(much too small).

Here are the values that seem to work (Horizontal mode):

iPhone SE:
w: 1136
h: 608
navbar: 32

iPhone 7:
w: 1334
h: 718
navbar: 32

iPhone 7 Plus:
w: 1366
h: 784
navbar: 44

iPad 9.7":
w: 1366
h: 980
navbar: 44

Rather than hardcoding the values, I would much rather use a way to derive those at run time. I've tried using UIScreen.main.bounds.width/height and UIScreen.main.nativeBounds.width/height but while the nativeBound works for some, the normal one seems to work for others etc.

Main ViewController Code

```<code>    let screenSize = UIScreen.main.bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height
    let screenHeightWithoutBar = screenHeight - self.navigationController!.navigationBar.frame.height

    var TopicsArray = [String](arrayLiteral: "Topic1","Topic2","Topic3","Topic4","Topic5")
    var TopicItemArray = [TopicItemViewController]()

    for i in 0..<TopicsArray.count {

        let TopicItemVC :TopicItemViewController =  TopicItemViewController(nibName: "TopicItemViewController", bundle: nil);

        TopicItemVC.toPassTopicName = TopicsArray[i]

        self.addChildViewController(TopicItemVC);
        self.scrollView!.addSubview(TopicItemVC.view);
        TopicItemVC.didMove(toParentViewController: self);

        TopicItemArray.append(TopicItemVC)
    }

    var topicCounter = 1
    for topicView in TopicItemArray {

        if(topicCounter<TopicItemArray.count){
            var topicFrame :CGRect = screenSize;

            topicFrame.origin.x = CGFloat(topicCounter) * screenWidth;

            TopicItemArray[topicCounter].view.frame = topicFrame;
        }

        topicCounter += 1
    }

    let scrollWidth: CGFloat  = CGFloat(TopicItemArray.count) * screenWidth
    let scrollHeight: CGFloat  = screenHeightWithoutBar

    self.scrollView!.contentSize = CGSize(width: scrollWidth, height: scrollHeight);
</code>```

TopicItemViewController code

```<code>    class TopicItemViewController: UIViewController {

     override func viewDidLoad() {
        super.viewDidLoad()
        var screenScale: CGFloat = UIScreen.main.scale
        //iphone 7 plus (nav is 44)
        self.view.frame.size.height = 784
        self.view.frame.size.width = 1366

        //iphone 7   // same as resolution
        //nav is 32
        //self.view.frame.size.height = 718 //718+32 = 750
        //self.view.frame.size.width = 1334
     }
    }
</code>```

答:
So after much googling and messing around, I've solved the problem.

I can indeed get rid of the hard coding as the correct values are picked up when I load it up in viewDidLayoutSubviews instead of viewDidLoad! All the existing constraints started working as they should. In the above example it then let me remove the self.view.frame.size.height and self.view.frame.size.width.

Title: Subview is the wrong size

Body:
Unfortunately I'm stuck with a xib that I'm loading into scrollview and it's not behaving as I'm expecting it to.

Unless I set self.view.frame.size.height and self.view.frame.size.width, the subview is the wrong size(much too small).

Here are the values that seem to work (Horizontal mode):

iPhone SE:
w: 1136
h: 608
navbar: 32

iPhone 7:
w: 1334
h: 718
navbar: 32

iPhone 7 Plus:
w: 1366
h: 784
navbar: 44

iPad 9.7":
w: 1366
h: 980
navbar: 44

Rather than hardcoding the values, I would much rather use a way to derive those at run time. I've tried using UIScreen.main.bounds.width/height and UIScreen.main.nativeBounds.width/height but while the nativeBound works for some, the normal one seems to work for others etc.

Main ViewController Code

    let screenSize = UIScreen.main.bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height
    let screenHeightWithoutBar = screenHeight - self.navigationController!.navigationBar.frame.height

    var TopicsArray = [String](arrayLiteral: "Topic1","Topic2","Topic3","Topic4","Topic5")
    var TopicItemArray = [TopicItemViewController]()

    for i in 0..<TopicsArray.count {

        let TopicItemVC :TopicItemViewController =  TopicItemViewController(nibName: "TopicItemViewController", bundle: nil);

        TopicItemVC.toPassTopicName = TopicsArray[i]

        self.addChildViewController(TopicItemVC);
        self.scrollView!.addSubview(TopicItemVC.view);
        TopicItemVC.didMove(toParentViewController: self);

        TopicItemArray.append(TopicItemVC)
    }

    var topicCounter = 1
    for topicView in TopicItemArray {

        if(topicCounter<TopicItemArray.count){
            var topicFrame :CGRect = screenSize;

            topicFrame.origin.x = CGFloat(topicCounter) * screenWidth;

            TopicItemArray[topicCounter].view.frame = topicFrame;
        }

        topicCounter += 1
    }

    let scrollWidth: CGFloat  = CGFloat(TopicItemArray.count) * screenWidth
    let scrollHeight: CGFloat  = screenHeightWithoutBar

    self.scrollView!.contentSize = CGSize(width: scrollWidth, height: scrollHeight);

TopicItemViewController code

    class TopicItemViewController: UIViewController {

     override func viewDidLoad() {
        super.viewDidLoad()
        var screenScale: CGFloat = UIScreen.main.scale
        //iphone 7 plus (nav is 44)
        self.view.frame.size.height = 784
        self.view.frame.size.width = 1366

        //iphone 7   // same as resolution
        //nav is 32
        //self.view.frame.size.height = 718 //718+32 = 750
        //self.view.frame.size.width = 1334
     }
    }


问:
Using 'Lock' in web applications
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

```<code>lock(HitCounter)
{
   // Bla...
}
</code>```

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?

答:
Couple reasons...

If you're trying to lock a database read/write operation, there's a really high risk of a race condition happening anyway because the database isn't owned by the process doing the lock, so it could be read from/written to by another process -- perhaps even a hypothetical future version of IIS that runs multiple processes per application.

Locks are typically used in client applications for non-UI threads, i.e. background/worker threads. Web applications don't have as much of a use for multithreaded processing unless you're trying to take advantage of multiple cores (in which case locks on request-associated objects would be acceptable), because each request can be assumed to run on its own thread, and the server can't respond until it's processed the entire output (or at least a sequential chunk) anyway.

Title: Using 'Lock' in web applications

Body:
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

lock(HitCounter)
{
   // Bla...
}

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?


问:
About security in PHP-MYSQL
Please apologize my english.

In my website I use this kind of lines to define if the current user is an admin or a normal user:

```<code><? if($_SESSION["nivel"] == 'administrator'){ ?>
</code>```

I wanna know if this $_SESSION variable could be modified from client side by an user and cause me some security problems.

答:
$_SESSION is a superglobal which is only modified on the server.

Therefore the client will never be able to change it.

Src: http://php.net/manual/en/session.security.php

Is it possible to change a $_SESSION variable client-side?

Title: About security in PHP-MYSQL

Body:
Please apologize my english.

In my website I use this kind of lines to define if the current user is an admin or a normal user:

<? if($_SESSION["nivel"] == 'administrator'){ ?>

I wanna know if this $_SESSION variable could be modified from client side by an user and cause me some security problems.


问:
How to show Interstitial ad correctly in this case?
I created a soundboard with a gridview Adapter (so no chance to set the Interstitial Ad on a sound button)
I also have a navigationbar with three tabs, so I decidet to set the Interstitial ad on the second fragment like this:

```<code>public class SecondFragment extends Fragment {
    private InterstitialAd mInterstitialAd;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.second_layout,container,false);

        final AdRequest adRequest = new AdRequest.Builder().build();
        mInterstitialAd = new InterstitialAd(getActivity());
        mInterstitialAd.setAdUnitId("MYID");
        mInterstitialAd.loadAd(adRequest);
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                if(mInterstitialAd.isLoaded()){
                    mInterstitialAd.show();
                }

            }

            @Override
            public void onAdClosed() {
            }
        });

        return rootView;
    }
</code>```

But then the problem was that the Ad pops up with a 3 second delay, thats why I received a mail from AdMob that I have to set the Interstitial ad correctly and not like I did before.

So my question is, what would you do in this case? Where would you set the InterstitialAd?

This is my App, 3 fragments full with sound buttons: https://gyazo.com/1ecd359b38fcfe0606bb3e74b684f16e

答:
From your code you're giving request to load ad then when your ad is loaded then you show that ad.

There's always a delay in loading ads so my suggestion is load your ad previously is background and not show that ad. whenever you want to show ad only check is your interstitial is ready to show, if yes show.

Call createInterstitial() at once in background and after that whenever you want to show interstitial Ad, call showInterstitial().

```<code>public void crateInterstitial(){

    interstitialAd = new InterstitialAd(this.activity);
    interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
    interstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            // not call show interstitial ad from here
        }

        @Override
        public void onAdClosed() {
              loadInterstitial();
         }
      });
    loadInterstitial();
}

public void loadInterstitial(){

     AdRequest interstitialRequest = new AdRequest.Builder().build();
     interstitialAd.loadAd(interstitialRequest);
}

public void showInterstitial(){
     if (interstitialAd.isLoaded())
          interstitialAd.show();
     else
         loadInterstitial();
}
</code>```

Body:
I created a soundboard with a gridview Adapter (so no chance to set the Interstitial Ad on a sound button)
I also have a navigationbar with three tabs, so I decidet to set the Interstitial ad on the second fragment like this:

public class SecondFragment extends Fragment {
    private InterstitialAd mInterstitialAd;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.second_layout,container,false);

        final AdRequest adRequest = new AdRequest.Builder().build();
        mInterstitialAd = new InterstitialAd(getActivity());
        mInterstitialAd.setAdUnitId("MYID");
        mInterstitialAd.loadAd(adRequest);
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                if(mInterstitialAd.isLoaded()){
                    mInterstitialAd.show();
                }

            }

            @Override
            public void onAdClosed() {
            }
        });

        return rootView;
    }

But then the problem was that the Ad pops up with a 3 second delay, thats why I received a mail from AdMob that I have to set the Interstitial ad correctly and not like I did before.

So my question is, what would you do in this case? Where would you set the InterstitialAd?

This is my App, 3 fragments full with sound buttons: https://gyazo.com/1ecd359b38fcfe0606bb3e74b684f16e

Body:
From your code you're giving request to load ad then when your ad is loaded then you show that ad.

There's always a delay in loading ads so my suggestion is load your ad previously is background and not show that ad. whenever you want to show ad only check is your interstitial is ready to show, if yes show.

Call createInterstitial() at once in background and after that whenever you want to show interstitial Ad, call showInterstitial().

public void crateInterstitial(){

    interstitialAd = new InterstitialAd(this.activity);
    interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
    interstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            // not call show interstitial ad from here
        }

        @Override
        public void onAdClosed() {
              loadInterstitial();
         }
      });
    loadInterstitial();
}

public void loadInterstitial(){

     AdRequest interstitialRequest = new AdRequest.Builder().build();
     interstitialAd.loadAd(interstitialRequest);
}

public void showInterstitial(){
     if (interstitialAd.isLoaded())
          interstitialAd.show();
     else
         loadInterstitial();
}