问:
SAS producing strange output, need clarification
I have the below Data set:

```<code>DATA Test1;
INFILE DATALINES DSD MISSOVER;
INPUT A  B  C;
DATALINES;
1, 2, 3
1,  ,
 ,  , 3
 ,   ,
;
RUN;
</code>```

Then I create below 2 datasets:

```<code>DATA Test2;
SET Test1;
i + a + b + c;
RUN;

DATA Test3;
SET Test1;
j + a + b + c + i;
RUN;
</code>```

In Test2, the value of i is always 6 in each observation.

In Test3, the value of J is all 0 and i is a period.

I have tried to think how SAS behaves in this case, but can't get my head around it. Can someone help?

答:
Your data steps are using examples of the sum statement. The form for a sum statement is:

```<code>variable + expression ;
</code>```

which is basically the equivalent of

```<code>retain variable 0;
variable=sum(variable,expression);
</code>```

So in your first example

```<code>i + a + b + c;
</code>```

the expression is (A+B+C). Note that A+B+C will be missing for every observation except the first one because one or more of the variables are missing.  So the 6 from the first observation is retained but nothing is added to it. In the second case you reference a non-existent variable I that will have missing values for all observations. (perhaps you meant for that step to read from the second dataset?)  So then (a+b+c+i) is missing for every observation and thus J keeps its initial value of zero.

If you really wanted I to accumulate all of the non-missing values then you should have used.

```<code>i + sum(a,b,c);
</code>```

Body:
I have the below Data set:

DATA Test1;
INFILE DATALINES DSD MISSOVER;
INPUT A  B  C;
DATALINES;
1, 2, 3
1,  ,
 ,  , 3
 ,   ,
;
RUN;

Then I create below 2 datasets:

DATA Test2;
SET Test1;
i + a + b + c;
RUN;

DATA Test3;
SET Test1;
j + a + b + c + i;
RUN;

In Test2, the value of i is always 6 in each observation.

In Test3, the value of J is all 0 and i is a period.

I have tried to think how SAS behaves in this case, but can't get my head around it. Can someone help?

Body:
Your data steps are using examples of the sum statement. The form for a sum statement is:

variable + expression ;

which is basically the equivalent of

retain variable 0;
variable=sum(variable,expression);

So in your first example

i + a + b + c;

the expression is (A+B+C). Note that A+B+C will be missing for every observation except the first one because one or more of the variables are missing.  So the 6 from the first observation is retained but nothing is added to it. In the second case you reference a non-existent variable I that will have missing values for all observations. (perhaps you meant for that step to read from the second dataset?)  So then (a+b+c+i) is missing for every observation and thus J keeps its initial value of zero.

If you really wanted I to accumulate all of the non-missing values then you should have used.

i + sum(a,b,c);


来源: stackexchange

问:
Can't deploy aspnet with C# & F# to azure - All build submissions in a build must use project instances originating from the same project collection
I'm starting a new web application, I wanted to use aspnetcore and the latest libraries and tools but I also wanted to use a functional, immutable language for the backend (the domain is one of those where OOP is specially painful to use) so we decided to go with F#

The thing is: aspnetcore for F# tooling is not yet on par with C# tooling (visual studio support, debugging, etc), so we decided to build the frontend in C# and the backend in F#. I was able to get it to build and run locally but when I try pushing it to azure I get an error

All build submissions in a build must use project instances originating from the same project collection

This is my environment:

```<code>OS: Windows
IDE: Visual Studio 2017 v15.2
</code>```

Steps:

Open Visual Studio 2017

Create new project (choose ASP.NET Core Web Application (.NET Framework))

Choose "Empty template"

Add new project to solution (choose F# Library)

Add reference from WebProject to Library

Compile & Run -> Everything OK

Publish webproject to azure and get this error:

1>------ Build started: Project: WebApplication23, Configuration: Release Any CPU ------

      1>WebApplication23 -> C:*****\WebApplication23\WebApplication23\bin\Release\net452\win7-x86\WebApplication23.exe

      2>------ Publish started: Project: WebApplication23, Configuration: Release Any CPU ------

      All build submissions in a build must use project instances originating from the same project collection.

      2>Publish failed due to build errors. Check the error list for more details.

  ========== Build: 1 succeeded, 0 failed, 2 up-to-date, 0 skipped ==========

  ========== Publish: 0 succeeded, 1 failed, 0 skipped ==========

If instead of an F# project I create a classic desktop C# library, it deploys successfully

答:
Check your settings under "summary" in the publish tab, and you'll probably notice that the build configuration differs from the other Projects (this seem to override what you set in other places).

/Dagfinn

ContentLicense: CC BY-SA 3.0

Body:
I'm starting a new web application, I wanted to use aspnetcore and the latest libraries and tools but I also wanted to use a functional, immutable language for the backend (the domain is one of those where OOP is specially painful to use) so we decided to go with F#

The thing is: aspnetcore for F# tooling is not yet on par with C# tooling (visual studio support, debugging, etc), so we decided to build the frontend in C# and the backend in F#. I was able to get it to build and run locally but when I try pushing it to azure I get an error

All build submissions in a build must use project instances originating from the same project collection

This is my environment:

OS: Windows
IDE: Visual Studio 2017 v15.2

Steps:

Open Visual Studio 2017

Create new project (choose ASP.NET Core Web Application (.NET Framework))

Choose "Empty template"

Add new project to solution (choose F# Library)

Add reference from WebProject to Library

Compile & Run -> Everything OK

Publish webproject to azure and get this error:

1>------ Build started: Project: WebApplication23, Configuration: Release Any CPU ------

      1>WebApplication23 -> C:*****\WebApplication23\WebApplication23\bin\Release\net452\win7-x86\WebApplication23.exe

      2>------ Publish started: Project: WebApplication23, Configuration: Release Any CPU ------

      All build submissions in a build must use project instances originating from the same project collection.

      2>Publish failed due to build errors. Check the error list for more details.

  ========== Build: 1 succeeded, 0 failed, 2 up-to-date, 0 skipped ==========

  ========== Publish: 0 succeeded, 1 failed, 0 skipped ==========

If instead of an F# project I create a classic desktop C# library, it deploys successfully


问:
Make a Download Button act like an Add To Cart Button
How can I link a simple download button act like a cart button ? If I have to make a user download a 2$ song, instead of directly downloading it, it should add that song to the woo commerce cart page.  </p>

答:
In woocommerce add your product. And in the product edit page there is a checkbox called 'downloadable'. Tick that box.  Then it will become a downloadable product. That item will be added to cart.

Hope this helps.


问:
check if checkbox is checked before submit form in MVC C# and jQuery
at first I had this MVC View that show a list of specific records from database, this is the code and as you can see there is a checkbox column

```<code> <tbody>
                                    @foreach (var item in Model)
                                    {
                                        <tr>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.numero_documento)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_empresa)
                                            </td>
                                            <td>
                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />
                                            </td>
                                        </tr>
                                    }
                                </tbody>
</code>```

and when press the submit button it makes a validation that at least one checkbox has to be checked, like this

```<code>$("#btn-agrupar").click(function (e) {
    if ($("input[type='checkbox']").is(':checked') === true)
        $("#FormAgrupar").submit();
    else {
        if (e.preventDefault) {
            e.preventDefault();
            $("#mostrarmodal").modal("show");
        }
        else {
            e.returnValue = false;
            $("#mostrarmodal").modal("show");
        }
    }
});
</code>```

and used to work but now I do have to added another checkbox column and use jQuery to send to a specific controller the info in the form, this is the code of the view

```<code><tbody>
                                    @foreach (var item in Model)
                                    {
                                        <tr>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.numero_documento)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_empresa)
                                            </td>
                                            <td>
                                                <input type="checkbox" name="delete" value="@item.numero_documento" +"a" />
                                            </td>
                                            <td>
                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />
                                            </td>
                                        </tr>
                                    }
                                </tbody>
</code>```

and this is the code of my jQuery, the problem is that now it doesn´t validate if at least one checkbox is checked for none of the checkbox columns, could you help me and tell me the problem?

```<code> $("#btn-agrupar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("RealizarAgrupacion","Home")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

        $("#btn-eliminar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("Index","Contact")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });
</code>```

this is the code of the buttons in my form

```<code><input type="button" value="Cancelar" id="btn-cancelar" class="btn btn-danger" />
                        <input type="button" value="Eliminar Solicitudes" id="btn-eliminar" class="btn btn-danger" />
                        <input type="button" value="Agrupar Solicitudes" id="btn-agrupar" class="btn btn-primary pull-right" />
</code>```

答:
It looks like you're missing e event param in

```<code>$("#btn-agrupar").click(function () ...
</code>```

should be:

```<code>$("#btn-agrupar").click(function (e) ...
</code>```

Body:
at first I had this MVC View that show a list of specific records from database, this is the code and as you can see there is a checkbox column

                                    @foreach (var item in Model)
                                    {

                                                @Html.DisplayFor(modelItem => item.numero_documento)

                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)

                                                @Html.DisplayFor(modelItem => item.nombre_empresa)

                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />

                                    }

and when press the submit button it makes a validation that at least one checkbox has to be checked, like this

$("#btn-agrupar").click(function (e) {
    if ($("input[type='checkbox']").is(':checked') === true)
        $("#FormAgrupar").submit();
    else {
        if (e.preventDefault) {
            e.preventDefault();
            $("#mostrarmodal").modal("show");
        }
        else {
            e.returnValue = false;
            $("#mostrarmodal").modal("show");
        }
    }
});

and used to work but now I do have to added another checkbox column and use jQuery to send to a specific controller the info in the form, this is the code of the view

                                    @foreach (var item in Model)
                                    {

                                                @Html.DisplayFor(modelItem => item.numero_documento)

                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)

                                                @Html.DisplayFor(modelItem => item.nombre_empresa)

                                                <input type="checkbox" name="delete" value="@item.numero_documento" +"a" />

                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />

                                    }

and this is the code of my jQuery, the problem is that now it doesn´t validate if at least one checkbox is checked for none of the checkbox columns, could you help me and tell me the problem?

 $("#btn-agrupar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("RealizarAgrupacion","Home")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

        $("#btn-eliminar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("Index","Contact")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

this is the code of the buttons in my form

<input type="button" value="Cancelar" id="btn-cancelar" class="btn btn-danger" />
                        <input type="button" value="Eliminar Solicitudes" id="btn-eliminar" class="btn btn-danger" />
                        <input type="button" value="Agrupar Solicitudes" id="btn-agrupar" class="btn btn-primary pull-right" />

Body:
It looks like you're missing e event param in

$("#btn-agrupar").click(function () ...

should be:

$("#btn-agrupar").click(function (e) ...


问:
How do I define the trigger events 'beforesend' in this plugin?
Probably a simple question, but I cannot figure this out.

In this plugin:  https://github.com/brianmario/jquery-infinite-scroll

The readme says it fires 'infinitescroll.beforesend', but how do I assign my own function to this without modifying the plugin?

Matt

答:
Use bind() to attach an event handler (infinitescroll.beforesend is a custom event fired by the plugin):

```<code>$(window).bind('infinitescroll.beforesend', function() {
    // do something
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Use bind() to attach an event handler (infinitescroll.beforesend is a custom event fired by the plugin):

$(window).bind('infinitescroll.beforesend', function() {
    // do something
});


问:
Creating device context in OpenCL for embedded profile
I am able to create context and devices in OpenCL by doing

```<code>     using namespace cl;
     std::vector<Platform> platforms;
     Platform::get(&platforms);
     cl_context_properties properties[] =
                        {CL_PLATFORM_NAME,
                      (cl_context_properties) (platforms.at(0))(),0};
            context = Context(CL_DEVICE_TYPE_ALL, properties);
            devices = context.getInfo<CL_CONTEXT_DEVICES>();
</code>```

It is working well with CPU and GPU devices. If I try the same for FPGA devices I get error in method clCreateContextFromType(). The context constructor is wrapping this method.

How should I create context and devices for OpenCL devices such as  FPGA with embedded profile.

答:
FPGA devices usually require to link additional vendor specific OpenCL driver libraries. What are the libraries to link with is usually specified in the vendor documentation and/or examples.

For Altera that can be found in their documentation: 1.7.6 Managing Host Application

For Xilinx in their examples (by OP): github.com/Xilinx/SDAccel_Examples

Body:
I am able to create context and devices in OpenCL by doing

     using namespace cl;
     std::vector<Platform> platforms;
     Platform::get(&platforms);
     cl_context_properties properties[] =
                        {CL_PLATFORM_NAME,
                      (cl_context_properties) (platforms.at(0))(),0};
            context = Context(CL_DEVICE_TYPE_ALL, properties);
            devices = context.getInfo<CL_CONTEXT_DEVICES>();

It is working well with CPU and GPU devices. If I try the same for FPGA devices I get error in method clCreateContextFromType(). The context constructor is wrapping this method.

How should I create context and devices for OpenCL devices such as  FPGA with embedded profile.


问:
Directives in Angular
I have this directive view here in my code:

```<code><div class="busy-indicator angular-animate" ng-show="busy"></div>
<div class="breadcrumblist" ng-class="atTopLevel ? ['at-top-level'] : null">
    <div class="breadcrumblist-display angular-animate">
        <label id="searchBox">Search</label><input class="c-context-menu-container  t-menu-background  c-context-menu-text" type="text" autocomplete="off" id="IdSearch" ng-model = "searchText.Name">
        <div class="breadcrumblist-parents">
            <div ng-show="::parents && parents.length >= 1"
                 ng-repeat="parentLink in parents"
                 class="breadcrumblist-parent-link t-breadcrumb--parent-bgcolor t-border--bottom-grey48"
                 ng-click="navUpToParent(parentLink)"
                 ng-class="{'selected': isSelected(parentLink.object), 'draggable': isDraggable(parentLink.object)}"
                 data-index="{{$index}}">

        </div>
</code>```

But, the searchBox is appearing for all places on my app but I want to make it appear just for one directive in particular. What should I do? I tought about make a scope variable to just "ng-show" this particular searchbox with a condition, but I don't know exactly how to do that, can you help me?

答:
Until you give more information to your specific problem, here are some possibly relevant things you can do to debug your problem and find a solution

the searchBox is appearing for all places on my app but I want to make it appear just for one directive in particular

The combination of the name of the directive + its restriction might cause the directive to appear in unwanted locations.

More information on restrict if needed.

So for example, if you have a directive called 'breadcrumblistParentLink', which is restricted to C (class) - you might find it in undesired locations since you're also using this class to style some elements on your page.

If that's the case, you might find it helpful restricting directives to attributes and elements and giving some unique names.

I would also like to refer to your question

just "ng-show" this particular searchbox with a condition, but I don't know exactly how to do that

If you want a specific behavior for one instance of a directive, there are multiple ways to do that.

Most common is passing an attribute. For example, this is how you use it

```<code>  <div my-awesome-directive show-searchbox="true"></div>
</code>```

And this is how you'd put show on the directive scope

```<code>angular.module('myApp',[]);

angular.module('myApp').directive('myAwesomeDirective', function(){
  return {
    template: 'this is my template <span ng-show="showSearchBox">This is search box</span>',
    restrict: 'A',
    scope: {
      showSearchBox: '<'
    },
    link: function(scope, element, attrs){
      console.log(scope.showSearchBox);
    }
  }
})
</code>```

You can play around with it here: https://plnkr.co/edit/4MdNeEafbZjq2kEFKYAl?p=preview

You can also look directive at attrs variable (attrs.showSearchBox) and spare the binding in some cases.

For example:

```<code>angular.module('myApp',[]);

angular.module('myApp').directive('myAwesomeDirective', function(){
  return {
    template: 'this is my template <span ng-show="showSearchBox()">This is search box</span>',
    restrict: 'A',
    scope: {

    },
    link: function(scope, element, attrs){
      scope.showSearchBox = function(){
       return attrs.showSearchBox;
      }
    }
  }
})
</code>```

Note I am using a function on the scope.

This function can also refer to the DOM and do something like $(element).is('[show-search-box]') if you are more comfortable with jquery - but it is highly recommended to stick to angular way of doing things.

Title: Directives in Angular

Body:
I have this directive view here in my code:

        Search<input class="c-context-menu-container  t-menu-background  c-context-menu-text" type="text" autocomplete="off" id="IdSearch" ng-model = "searchText.Name">

= 1"
                 ng-repeat="parentLink in parents"
                 class="breadcrumblist-parent-link t-breadcrumb--parent-bgcolor t-border--bottom-grey48"
                 ng-click="navUpToParent(parentLink)"
                 ng-class="{'selected': isSelected(parentLink.object), 'draggable': isDraggable(parentLink.object)}"
                 data-index="{{$index}}">

But, the searchBox is appearing for all places on my app but I want to make it appear just for one directive in particular. What should I do? I tought about make a scope variable to just "ng-show" this particular searchbox with a condition, but I don't know exactly how to do that, can you help me?

Body:
Until you give more information to your specific problem, here are some possibly relevant things you can do to debug your problem and find a solution

the searchBox is appearing for all places on my app but I want to make it appear just for one directive in particular

The combination of the name of the directive + its restriction might cause the directive to appear in unwanted locations.

More information on restrict if needed.

So for example, if you have a directive called 'breadcrumblistParentLink', which is restricted to C (class) - you might find it in undesired locations since you're also using this class to style some elements on your page.

If that's the case, you might find it helpful restricting directives to attributes and elements and giving some unique names.

I would also like to refer to your question

just "ng-show" this particular searchbox with a condition, but I don't know exactly how to do that

If you want a specific behavior for one instance of a directive, there are multiple ways to do that.

Most common is passing an attribute. For example, this is how you use it

  <div my-awesome-directive show-searchbox="true"></div>

And this is how you'd put show on the directive scope

angular.module('myApp',[]);

angular.module('myApp').directive('myAwesomeDirective', function(){
  return {
    template: 'this is my template <span ng-show="showSearchBox">This is search box</span>',
    restrict: 'A',
    scope: {
      showSearchBox: '<'
    },
    link: function(scope, element, attrs){
      console.log(scope.showSearchBox);
    }
  }
})

You can play around with it here: https://plnkr.co/edit/4MdNeEafbZjq2kEFKYAl?p=preview

You can also look directive at attrs variable (attrs.showSearchBox) and spare the binding in some cases.

For example:

angular.module('myApp',[]);

angular.module('myApp').directive('myAwesomeDirective', function(){
  return {
    template: 'this is my template <span ng-show="showSearchBox()">This is search box</span>',
    restrict: 'A',
    scope: {

    },
    link: function(scope, element, attrs){
      scope.showSearchBox = function(){
       return attrs.showSearchBox;
      }
    }
  }
})

Note I am using a function on the scope.

This function can also refer to the DOM and do something like $(element).is('[show-search-box]') if you are more comfortable with jquery - but it is highly recommended to stick to angular way of doing things.


问:
rails 4 has_many :through default order
I have a project model that has many tasks, through a join model. The order of the tasks are stored on the project_tasks model.

How do I do the equivalent of the below in rails 4?

```<code>has_many :project_tasks
has_many :tasks, :through => :project_tasks, :order => 'project_tasks.position'
</code>```

答:
```<code>has_many :project_tasks, -> { order(:position) }
has_many :tasks, through: :project_tasks
</code>```

I hope this helps now in rails 4 and 5 you have scopes for that sort of thing. PS: Keep in mind now when you call project_tasks it will call this scope if you dont want that make scope on model project_tasks.

Title: rails 4 has_many :through default order

Body:
I have a project model that has many tasks, through a join model. The order of the tasks are stored on the project_tasks model.

How do I do the equivalent of the below in rails 4?

has_many :project_tasks
has_many :tasks, :through => :project_tasks, :order => 'project_tasks.position'

Body:
has_many :project_tasks, -> { order(:position) }
has_many :tasks, through: :project_tasks

I hope this helps now in rails 4 and 5 you have scopes for that sort of thing. PS: Keep in mind now when you call project_tasks it will call this scope if you dont want that make scope on model project_tasks.


问:
Rendering react component after api response
I have a react component that I wish to populate with images using the Dropbox api. The api part works fine, but the component is rendered before the data comes through & so the array is empty. How can I delay the rendering of the component until it has the data it needs?

```<code>var fileList = [];
var images = [];
var imageSource = [];

class Foo extends React.Component {

 render(){
  dbx.filesListFolder({path: ''})
  .then(function(response) {
   fileList=response.entries;
   for(var i=0; i<fileList.length; i++){
    imageSource.push(fileList[0].path_lower);
   }
   console.log(imageSource);
   })

  for(var a=0; a<imageSource.length; a++){
   images.push(<img key={a} className='images'/>);
  }

  return (
   <div className="folioWrapper">
    {images}
   </div>
  );
 }
}
</code>```

Thanks for your help!

答:
First off, you should be using the component's state and not using globally defined variables.

So to avoid showing the component with an empty array of images, you'll need to apply a conditional "loading" class on the component and remove it when the array is no longer empty.

Body:
I have a react component that I wish to populate with images using the Dropbox api. The api part works fine, but the component is rendered before the data comes through & so the array is empty. How can I delay the rendering of the component until it has the data it needs?

var fileList = [];
var images = [];
var imageSource = [];

class Foo extends React.Component {

 render(){
  dbx.filesListFolder({path: ''})
  .then(function(response) {
   fileList=response.entries;
   for(var i=0; i<fileList.length; i++){
    imageSource.push(fileList[0].path_lower);
   }
   console.log(imageSource);
   })

  for(var a=0; a<imageSource.length; a++){
   images.push();
  }

  return (

    {images}

  );
 }
}

Thanks for your help!


问:
recursively delete all JSON keys with null values and delete parent key if all child keys are deleted
I'm trying to recursively delete null values in a JSON object and all Subobjects.  If the subobjects keys are all deleted, then I want that subobject to be deleted as well.

ie.

```<code>x = {
  "applicant": {
    'first_name': null,
    'last_name': null,
    'employment_type': null
  },
  'phone': 1123123,
  'branch': null,
  'industry': {
    'id': 1,
    'name': null
  },
  "status": "333"
}
</code>```

should turn into this:

```<code>x = {
    'phone': 1123123,
    'industry': {
         "id": 1
     },
     "status": "333"
    }
</code>```

Here is the function that I wrote to delete all keys with null values:

```<code>function delKeys(app){
  for(key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
      delKeys(app[key])
    }
    if(app[key] === null){
      delete app[key]
      }
  }
</code>```

But this doesn't delete the parent key with no children:

so instead of the result above, I get this:

```<code>x = {
    "applicant":{},
    "phone":1123123,
    "industry":{
       'id': 1
     }
     "status": "333"
     }
</code>```

As you can see, it doesn't delete the applicant key. How would I check for that within the function? or does it need to be written in a separate function that I call AFTER calling delKeys()?

Also, does anyone see this hitting maximum recursion depth? I've tried with bigger JSON objects and it seems to be hitting max recursion depth. I would really appreciate help with debugging that

thank you.

答:
There's a simple solution with JSON.parse' reviver function. This function is executed for every element, and if it returns undefined the element is deleted from object. You can check if value is empty and return undefined in this function, and avoid any recursive functions:

const a = {"applicant":{"first_name":null,"last_name":null,"employment_type":null},"phone":1123123,"branch":null,"industry":{"id":1,"name":null},"status":"333"};

const res = JSON.parse(JSON.stringify(a), (k, v) => {
  return (v === null // delete null values
    || (Array.isArray(v) && v.length === 0) // delete empty arrays
    || (typeof v === 'object' && Object.keys(v).length === 0)) // delete empty objects
      ? undefined : v // else return the value
});

console.log(res)```

Body:
I'm trying to recursively delete null values in a JSON object and all Subobjects.  If the subobjects keys are all deleted, then I want that subobject to be deleted as well.

ie.

x = {
  "applicant": {
    'first_name': null,
    'last_name': null,
    'employment_type': null
  },
  'phone': 1123123,
  'branch': null,
  'industry': {
    'id': 1,
    'name': null
  },
  "status": "333"
}

should turn into this:

x = {
    'phone': 1123123,
    'industry': {
         "id": 1
     },
     "status": "333"
    }

Here is the function that I wrote to delete all keys with null values:

function delKeys(app){
  for(key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
      delKeys(app[key])
    }
    if(app[key] === null){
      delete app[key]
      }
  }

But this doesn't delete the parent key with no children:

so instead of the result above, I get this:

x = {
    "applicant":{},
    "phone":1123123,
    "industry":{
       'id': 1
     }
     "status": "333"
     }

As you can see, it doesn't delete the applicant key. How would I check for that within the function? or does it need to be written in a separate function that I call AFTER calling delKeys()?

Also, does anyone see this hitting maximum recursion depth? I've tried with bigger JSON objects and it seems to be hitting max recursion depth. I would really appreciate help with debugging that

thank you.


问:
How to find all week numbers that are first week of month in a year python
I want to create a event that falls on Sunday of every first week of months.

This is what I am doing for a particular week number which is first week of june to get date:

```<code>from datetime import datetime
myDate = "2017 22 0"
# here `2017` is year, `22` is week number and `0` =sunday is week day
datetime.strptime(myDate, "%Y %W %w")

#output...
datetime.datetime(2017, 6, 4, 0, 0)
</code>```

So I need a list of all week numbers that are first week of month so I can loop on it and get desire dates.

Adding More information

I want a method which return list of week numbers which are first week of month where first week means week has first sunday.

```<code>def get_week_number(year=2017, day=0):
   #day 0 means sunday
   ...
   ...
   return [1, 5, 9, 13, 18, 22, ...]
</code>```

答:
I've done a loop through the months, then got the first Sunday (starting at month's 1st and moving to the next day until a Sunday is found), then got the week-of-year of the date found:

```<code>from datetime import datetime
from datetime import date

# dayofweek: Sunday=0, Monday=1 and so on
def get_week_number(year=2017, dayofweek=0):
    weeks = []

    for month in range(1, 13):
        # get first Sunday of month
        d = date(year, month, 1)
        while(d.weekday() != dayofweek):
            d = d.replace(day=d.day + 1)

        # isocalendar()[1] is the week-of-year field
        weeks.append(d.isocalendar()[1])

    return weeks

print(get_week_number(2017, 0))
</code>```

The result, though, is different from what you expect:

```<code>[1, 6, 10, 14, 18, 23, 27, 32, 36, 40, 45, 49]
</code>```

I also tried with weeks.append(int(d.strftime("%W"))) but it gives the same results - I'm using Python 3.5.2 and a week is defined as:

The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.

Body:
I want to create a event that falls on Sunday of every first week of months.

This is what I am doing for a particular week number which is first week of june to get date:

from datetime import datetime
myDate = "2017 22 0"
# here `2017` is year, `22` is week number and `0` =sunday is week day
datetime.strptime(myDate, "%Y %W %w")

#output...
datetime.datetime(2017, 6, 4, 0, 0)

So I need a list of all week numbers that are first week of month so I can loop on it and get desire dates.

Adding More information

I want a method which return list of week numbers which are first week of month where first week means week has first sunday.

def get_week_number(year=2017, day=0):
   #day 0 means sunday
   ...
   ...
   return [1, 5, 9, 13, 18, 22, ...]

Body:
I've done a loop through the months, then got the first Sunday (starting at month's 1st and moving to the next day until a Sunday is found), then got the week-of-year of the date found:

from datetime import datetime
from datetime import date

# dayofweek: Sunday=0, Monday=1 and so on
def get_week_number(year=2017, dayofweek=0):
    weeks = []

    for month in range(1, 13):
        # get first Sunday of month
        d = date(year, month, 1)
        while(d.weekday() != dayofweek):
            d = d.replace(day=d.day + 1)

        # isocalendar()[1] is the week-of-year field
        weeks.append(d.isocalendar()[1])

    return weeks

print(get_week_number(2017, 0))

The result, though, is different from what you expect:

[1, 6, 10, 14, 18, 23, 27, 32, 36, 40, 45, 49]

I also tried with weeks.append(int(d.strftime("%W"))) but it gives the same results - I'm using Python 3.5.2 and a week is defined as:

The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.


问:
Error with git commits: 'gpg-agent' is older than us (2.0.30 < 2.1.20)
How would I go about fixing this?</p>

```<code>gpg: WARNING: server 'gpg-agent' is older than us (2.0.30 < 2.1.20)
</code>```

答:
A possible alternate reason, that you are using some shared-home solution (for example, docker) where your multiple virtual environments see the same home directory.

Gpg starts a daemon on its first execution if it doesn't run already, and communicates with it on ~/.gnupg/S.gpg-agent. It is possible, that multiple gpg-agents from different environments see the same socket, and thus they experience incompatibility. The solution: kill the unneeded gpg-agent process.

Body:
How would I go about fixing this?

gpg: WARNING: server 'gpg-agent' is older than us (2.0.30 < 2.1.20)


问:
COM Integration from ALBPM - Cannot find IDispatch for '{00020906-0000-0000-C000-000000000046}'
I am trying to use the Office COM components in order to create Word and Excel documents. Unfortunately I can not achieve this because I am getting an error.

Cannot find IDispatch for
  '{00020906-0000-0000-C000-000000000046}'
  in module
  '{00020905-0000-0000-C000-000000000046}',
  v8.3

I tried reinstalling Office, my application (ALBPM) and my interface (combsvc) but it is not working.

I want to know how can I install IDispatch, or how can I know if it is installed in the correct module. Some times the error says:

Cannot find IDispatch for
  '{000209FF-0000-0000-C000-000000000046}'
  ... instead of
  00020906-0000-0000-C000-000000000046

The code I'm using generate these errors is:

```<code>wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"
// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"
// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"
// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"
wordDoc = open(wordDocs, fileName : contratoTemplate)
bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion
filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename
</code>```

Any information you have about the IDispatch, or these registry entries, well be very appreciated, even if you can tell me where to find more info about this.

Thanks a lot.
Daniel.

答:
Daniel,

I'm taking a stab in the dark here. It looks like you're using BEA systems Aqualogic BPM which I have a feeling is a Java based tool. From digging about it looks like combsvc is actually a COM bridge service to allow ALBPM to speak to COM from Java:

http://edocs.bea.com/albsi/docs60/studio/index.html?t=studio/catalog/catalog_component/COM/c_COM_Bridge.html

I'm thinking this is your point of failure.

About your question on IDispatch, you don't actually install IDispatch. IDispatch is a interface used by COM to expose objects, methods and properties to late bound COM automation clients such as scripting languages (e.g. ASP or VBScript). It's part of the infrastructure of COM, if this was broken you'd see lots more problems with your machine.

I'd probably advise popping a question in here:

http://forums.oracle.com/forums/forum.jspa?forumID=560

OwnerDisplayName: Daniel M

LastEditorDisplayName: warren

Body:
I am trying to use the Office COM components in order to create Word and Excel documents. Unfortunately I can not achieve this because I am getting an error.

Cannot find IDispatch for
  '{00020906-0000-0000-C000-000000000046}'
  in module
  '{00020905-0000-0000-C000-000000000046}',
  v8.3

I tried reinstalling Office, my application (ALBPM) and my interface (combsvc) but it is not working.

I want to know how can I install IDispatch, or how can I know if it is installed in the correct module. Some times the error says:

Cannot find IDispatch for
  '{000209FF-0000-0000-C000-000000000046}'
  ... instead of
  00020906-0000-0000-C000-000000000046

The code I'm using generate these errors is:

wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"
// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"
// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"
// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"
wordDoc = open(wordDocs, fileName : contratoTemplate)
bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion
filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename

Any information you have about the IDispatch, or these registry entries, well be very appreciated, even if you can tell me where to find more info about this.

Thanks a lot.
Daniel.

OwnerDisplayName: Kev


问:
Is it considered accepted using var's as "shortcuts" in c#?
One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:

MyApp.Properties.Settings.Default.Value=1;

That's a ton of unnecessary code. An alternative to this is declaring:

```<code>using MyApp.Properties;
</code>```

-- or --

```<code>using appsettings = MyAppp.Properties.Settings;
</code>```

leading to: appsettings.Default.Value=1 or Settings.Default.Value=1

Abit better, but I'd like it shorter still:

```<code>var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;
</code>```

Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)

答:
In Fact, var is more and more used exactly for that : shortening the code.

Specially in the case of

```<code>MyClass myClass = new MyClass();
</code>```

Which is very clear enough using

```<code>var myClass = new MyClass();
</code>```

And btw, ReSharper helps you enforce that var is used everywhere it can be !

Body:
One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:

MyApp.Properties.Settings.Default.Value=1;

That's a ton of unnecessary code. An alternative to this is declaring:

using MyApp.Properties;

-- or --

using appsettings = MyAppp.Properties.Settings;

leading to: appsettings.Default.Value=1 or Settings.Default.Value=1

Abit better, but I'd like it shorter still:

var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;

Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)

Body:
In Fact, var is more and more used exactly for that : shortening the code.

Specially in the case of

MyClass myClass = new MyClass();

Which is very clear enough using

var myClass = new MyClass();

And btw, ReSharper helps you enforce that var is used everywhere it can be !


问:
Align elements vertically inside a div
I'm trying to align elements vertically inside a div, but I'm stuck with circles.
The red div is 100% width, with my code, but the vertical line does not show, and the circles (that are divs or spans with background images) are not in the middle.

My code:

.welcomeArea{
    margin-top: 70px;
    max-height: 98px;
    height: 98px;
    background-color: #293847;

}

.welcomeAreaContent{
        line-height: 98px;
        color: white;
        margin-left: 5%;
    margin-right: 5%;

}
.welcomeAreaContent > span {
    display:inline-block;
}
.welcomeAreaContent .welcomeName{
    font-weight: bold;
    font-size: 1.7em;
}
.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
   width: 50px;
   height: 50px;
      border-radius: 50%;
    behavior: url(PIE.htc);
   -moz-border-radius: 50px;
   -webkit-border-radius: 50px;
   border-radius: 50px;
   margin-left: 32px;
   display: inline-block;
}
.twittericon{
    background: url('data:image/png;base64,...') no-repeat center;
    background-color: white;
     background-size: cover;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="welcomeArea">
<div class="welcomeAreaContent">
       <div class="welcomeName">
         TEXT TEXT
         <span class ="circle twittericon"></span>
       </div>
        <div class="verticalLine">
</div>
     </div>
  </div></code>```

The result looks like the following which is not good at all:

答:
Try:</p>

```<code>.circle
{
    vertical-align: middle;
}
</code>```

Title: Align elements vertically inside a div

Body:
I'm trying to align elements vertically inside a div, but I'm stuck with circles.
The red div is 100% width, with my code, but the vertical line does not show, and the circles (that are divs or spans with background images) are not in the middle.

My code:

.welcomeArea{
    margin-top: 70px;
    max-height: 98px;
    height: 98px;
    background-color: #293847;

}

.welcomeAreaContent{
        line-height: 98px;
        color: white;
        margin-left: 5%;
    margin-right: 5%;

}
.welcomeAreaContent > span {
    display:inline-block;
}
.welcomeAreaContent .welcomeName{
    font-weight: bold;
    font-size: 1.7em;
}
.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
   width: 50px;
   height: 50px;
      border-radius: 50%;
    behavior: url(PIE.htc);
   -moz-border-radius: 50px;
   -webkit-border-radius: 50px;
   border-radius: 50px;
   margin-left: 32px;
   display: inline-block;
}
.twittericon{
    background: url('data:image/png;base64,...') no-repeat center;
    background-color: white;
     background-size: cover;

}

         TEXT TEXT

The result looks like the following which is not good at all:

Body:
Try:

.circle
{
    vertical-align: middle;
}


问:
Repeater - textbox content to database C#
I'm trying to insert content to my local database from a textbox inside a repeater element, in a post - comment way. So far I've tried looping on all the generated rows to find the specific textbox but I have had no luck, either the insert goes empty, or I get 1 insert per preexisting row, or I get the same value inserted over and over again through different posts.

I finally tried to pass the post id to the itemfinder and it's kind of working, but the "comm_contenido" inserts from the textbox are still going empty to the database.

My question is what it the correct and more direct way to handle these kind of inserts from within a Repeater?.

C#:

```<code>protected void Button1_Command(object sender, CommandEventArgs e)
{

    string postid = e.CommandArgument.ToString();
    string emailcc = Session["EMAIL"].ToString();
    string user_id = Session["ID"].ToString();
    string usrnom = Session["NOMBRE"].ToString();
    string usrfoto = Session["FOTO_URL"].ToString();
    //string COMM_CONTENIDO = lblcomm.Text.ToString();

    var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    TextBox txt2;

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {

                int m = Int32.Parse(postid);
                txt2 = (TextBox)Repeater_UsrPosts.Items[m].FindControl("txtcomentar");
                string txt1 = txt2.Text;

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = (@"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
                + user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
                cmd.Connection = conn;
                conn.Open();
                int rowsAffected = cmd.ExecuteNonQuery();
            }
        }

        //txtpublica.Text = "";
        traerposts();

}
</code>```

ASP:

```<code><asp:Repeater ID="Repeater_UsrPosts" runat="server" >
    <ItemTemplate>

        <!-- Post -->
        <div class="post clearfix">
            <div class="user-block">

                <img alt="" src="<%#Eval("post_user_foto")%>" class="img-circle img-bordered-sm" />

                <span class="username">
                    <a href="#"><%#Eval("post_user_nombre") %></a>
                    <a href="#" class="pull-right btn-box-tool"><i class="fa fa-times"></i></a>
                </span>
                <span class="description"><%#Eval("post_fecha") %></span>
            </div>
            <!-- /.user-block -->

            <p>

                <%#Eval("post_contenido") %>
            </p>

            <ul class="list-inline">
                <li><a href="#" class="link-black text-sm"><i class="fa fa-share margin-r-5"></i>Share</a></li>
                <li><a href="#" class="link-black text-sm"><i class="fa fa-thumbs-o-up margin-r-5"></i>Like</a>
                </li>
                <li class="pull-right">
                    <asp:LinkButton ID="bttnabrircomentarios" runat="server" class="link-black text-sm">
                        <i class="fa fa-comments-o margin-r-5"></i>Comments</asp:LinkButton>
                </li>
            </ul>

            <asp:TextBox ID="txtcomentar" runat="server" class="form-control input-sm" placeholder="Escribe un comentario" EnableViewState="False"></asp:TextBox>

            <%# Eval("post_id") %> -

            <asp:Button ID="Button1" runat="server" Text="Button"
                OnCommand="Button1_Command" CommandName="myCommand"
                CommandArgument='<%# Eval("post_ID") %>' />
            <br />
        </div>
        <!-- /.post -->
    </ItemTemplate>
</asp:Repeater>
</code>```

答:
This were the changes that worked for me to locate the specific textbox and prevent posting unwanted data.

C#:

```<code>protected void Button1_Command(object sender, CommandEventArgs e)
{

    string postid = e.CommandArgument.ToString();
    string emailcc = Session["EMAIL"].ToString();
    string user_id = Session["ID"].ToString();
    string usrnom = Session["NOMBRE"].ToString();
    string usrfoto = Session["FOTO_URL"].ToString();

    var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
</code>```

```<code>    Control s = (Control)sender;
    TextBox tb = (TextBox)s.NamingContainer.FindControl("txtcomentar");
    tb.ReadOnly = true;
</code>```

```<code>    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {

            string txt1 = tb.Text;

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = (@"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
            + user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
            cmd.Connection = conn;
            conn.Open();
            int rowsAffected = cmd.ExecuteNonQuery();
        }
    }
    traerposts();
}
</code>```

And on the ASP I added the property EnableVIewState="true" to the textbox and also to the repeater.

At last, most important, I added if (!Page.IsPostBack) to the onload event.

And with all this together the comments on each post are being inserted correctly.

Body:
I'm trying to insert content to my local database from a textbox inside a repeater element, in a post - comment way. So far I've tried looping on all the generated rows to find the specific textbox but I have had no luck, either the insert goes empty, or I get 1 insert per preexisting row, or I get the same value inserted over and over again through different posts.

I finally tried to pass the post id to the itemfinder and it's kind of working, but the "comm_contenido" inserts from the textbox are still going empty to the database.

My question is what it the correct and more direct way to handle these kind of inserts from within a Repeater?.

C#:

protected void Button1_Command(object sender, CommandEventArgs e)
{

    string postid = e.CommandArgument.ToString();
    string emailcc = Session["EMAIL"].ToString();
    string user_id = Session["ID"].ToString();
    string usrnom = Session["NOMBRE"].ToString();
    string usrfoto = Session["FOTO_URL"].ToString();
    //string COMM_CONTENIDO = lblcomm.Text.ToString();

    var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    TextBox txt2;

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {

                int m = Int32.Parse(postid);
                txt2 = (TextBox)Repeater_UsrPosts.Items[m].FindControl("txtcomentar");
                string txt1 = txt2.Text;

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = (@"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
                + user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
                cmd.Connection = conn;
                conn.Open();
                int rowsAffected = cmd.ExecuteNonQuery();
            }
        }

        //txtpublica.Text = "";
        traerposts();

}

ASP:

<asp:Repeater ID="Repeater_UsrPosts" runat="server" >
    <ItemTemplate>

                <img alt="" src="<%#Eval("post_user_foto")%>" class="img-circle img-bordered-sm" />

                    <%#Eval("post_user_nombre") %>

                <%#Eval("post_fecha") %>

                <%#Eval("post_contenido") %>

Share

Like

                    <asp:LinkButton ID="bttnabrircomentarios" runat="server" class="link-black text-sm">
                        Comments</asp:LinkButton>

            <asp:TextBox ID="txtcomentar" runat="server" class="form-control input-sm" placeholder="Escribe un comentario" EnableViewState="False"></asp:TextBox>

            <%# Eval("post_id") %> -

            <asp:Button ID="Button1" runat="server" Text="Button"
                OnCommand="Button1_Command" CommandName="myCommand"
                CommandArgument='<%# Eval("post_ID") %>' />

    </ItemTemplate>
</asp:Repeater>

Body:
This were the changes that worked for me to locate the specific textbox and prevent posting unwanted data.

C#:

protected void Button1_Command(object sender, CommandEventArgs e)
{

    string postid = e.CommandArgument.ToString();
    string emailcc = Session["EMAIL"].ToString();
    string user_id = Session["ID"].ToString();
    string usrnom = Session["NOMBRE"].ToString();
    string usrfoto = Session["FOTO_URL"].ToString();

    var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

    Control s = (Control)sender;
    TextBox tb = (TextBox)s.NamingContainer.FindControl("txtcomentar");
    tb.ReadOnly = true;

    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {

            string txt1 = tb.Text;

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = (@"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
            + user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
            cmd.Connection = conn;
            conn.Open();
            int rowsAffected = cmd.ExecuteNonQuery();
        }
    }
    traerposts();
}

And on the ASP I added the property EnableVIewState="true" to the textbox and also to the repeater.

At last, most important, I added if (!Page.IsPostBack) to the onload event.

And with all this together the comments on each post are being inserted correctly.


问:
T-SQL / Unexpected NULL handling when ANSI_NULLS is turned OFF
I'm just struggling with the NULL value handling in SQL Server (tested on Version 12.0.5000.0). Basically, my intention is to get all rows that have a column value <> a static value (e.g. 999). I'm NOT searching for an alternative LIKE "use the ISNULL function". The query is generated by a third-party engine and I do not intend write a parser and change the statement.

```<code>-- All examples with ANSI_NULLS OFF
SET ANSI_NULLS OFF;
GO

--------------------------------------------------------------------------------------------------------
-- "Virtual" example / working as expected
--------------------------------------------------------------------------------------------------------
    DECLARE
        @One INT = 1,
        @Null INT = NULL

    SELECT
         IIF(@Null = NULL, 1, 0) '@Null = NULL' -- To test if ANSI_NULL is OFF
        ,IIF(@One <> NULL, 1, 0) '@One <> NULL' -- working with NULL variable
        ,IIF(1 <> NULL, 1, 0) '1 <> NULL'       -- working with NULL value

--------------------------------------------------------------------------------------------------------
-- MSDN Example / NOT working as expected
    -- https://learn.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql
--------------------------------------------------------------------------------------------------------

    -- Create table t1 and insert values.
    CREATE TABLE dbo.t1 (a INT NULL);
    INSERT INTO dbo.t1 values (NULL),(0),(1);
    GO

    -- SET ANSI_NULLS to OFF and test.
    DECLARE @varname int;
    SET @varname = 999;

    SELECT a
    FROM t1
    WHERE a <> @varname;    -- working with NULL variable

    SELECT a
    FROM t1
    WHERE a <> 999;         -- NOT working with NULL value

    -- Drop table t1.
    DROP TABLE dbo.t1;
</code>```

Could anyone explain why the "virtual" example is working in a different way then the MSDN example?

```<code>Virtual example:
+--------------+--------------+-----------+
| @Null = NULL | @One <> NULL | 1 <> NULL |
+--------------+--------------+-----------+
|            1 |            1 |         1 |
+--------------+--------------+-----------+

MSDN example:
-- SELECT 1
+------+
|  a   |
+------+
| NULL |
| 0    |
| 1    |
+------+

-- SELECT 2
+------+
|  a   |
+------+
| 0    |
| 1    |
+------+
</code>```

答:
Looks like query optimizer chooses different comparison operator:

```<code>DECLARE @varname int;
SET @varname = 999;

SELECT a
FROM t1
WHERE a <> @varname;
</code>```

XML execution plan:

```<code><Predicate>
    <ScalarOperator ScalarString="[fiddle_84f7799901e54a779e8bff464a2d01f3].[dbo].[t1].[a] <> [@varname]">
        <Compare CompareOp="IS NOT">
            <ScalarOperator>
                <Identifier>
                    <ColumnReference Database="[fiddle_84f7799901e54a779e8bff464a2d01f3]" Schema="[dbo]" Table="[t1]" Column="a"></ColumnReference>
                </Identifier>
            </ScalarOperator>
            <ScalarOperator>
                <Identifier>
                    <ColumnReference Column="@varname"></ColumnReference>
                </Identifier>
            </ScalarOperator>
        </Compare>
    </ScalarOperator>
</Predicate>
</code>```

Compare CompareOp="IS NOT"

Second query with hardcoded value:

```<code>SELECT a
FROM t1
WHERE a <> 999;

-- same as
DECLARE @varname int = 999;

SELECT a
FROM t1
WHERE a <> (SELECT @varname);
</code>```

XML execution plan:

```<code><Predicate>
    <ScalarOperator ScalarString="[fiddle_ac5121a789da473382366733b51ef441].[dbo].[t1].[a]<>(999)">
        <Compare CompareOp="NE">
            <ScalarOperator>
                <Identifier>
                    <ColumnReference Database="[fiddle_ac5121a789da473382366733b51ef441]" Schema="[dbo]" Table="[t1]" Column="a"></ColumnReference>
                </Identifier>
            </ScalarOperator>
            <ScalarOperator>
                <Const ConstValue="(999)"></Const>
            </ScalarOperator>
        </Compare>
    </ScalarOperator>
</Predicate>
</code>```

Compare CompareOp="NE"

DBFiddle

EDIT:

SET ANSI_NULLS

SET ANSI_NULLS ON affects a comparison only if one of the operands of the comparison is either a variable that is NULL or a literal NULL. If both sides of the comparison are columns or compound expressions, the setting does not affect the comparison.

Body:
I'm just struggling with the NULL value handling in SQL Server (tested on Version 12.0.5000.0). Basically, my intention is to get all rows that have a column value <> a static value (e.g. 999). I'm NOT searching for an alternative LIKE "use the ISNULL function". The query is generated by a third-party engine and I do not intend write a parser and change the statement.

-- All examples with ANSI_NULLS OFF
SET ANSI_NULLS OFF;
GO

--------------------------------------------------------------------------------------------------------
-- "Virtual" example / working as expected
--------------------------------------------------------------------------------------------------------
    DECLARE
        @One INT = 1,
        @Null INT = NULL

    SELECT
         IIF(@Null = NULL, 1, 0) '@Null = NULL' -- To test if ANSI_NULL is OFF
        ,IIF(@One <> NULL, 1, 0) '@One <> NULL' -- working with NULL variable
        ,IIF(1 <> NULL, 1, 0) '1 <> NULL'       -- working with NULL value

--------------------------------------------------------------------------------------------------------
-- MSDN Example / NOT working as expected
    -- https://learn.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql
--------------------------------------------------------------------------------------------------------

    -- Create table t1 and insert values.
    CREATE TABLE dbo.t1 (a INT NULL);
    INSERT INTO dbo.t1 values (NULL),(0),(1);
    GO

    -- SET ANSI_NULLS to OFF and test.
    DECLARE @varname int;
    SET @varname = 999;

    SELECT a
    FROM t1
    WHERE a <> @varname;    -- working with NULL variable

    SELECT a
    FROM t1
    WHERE a <> 999;         -- NOT working with NULL value

    -- Drop table t1.
    DROP TABLE dbo.t1;

Could anyone explain why the "virtual" example is working in a different way then the MSDN example?

Virtual example:
+--------------+--------------+-----------+
| @Null = NULL | @One <> NULL | 1 <> NULL |
+--------------+--------------+-----------+
|            1 |            1 |         1 |
+--------------+--------------+-----------+

MSDN example:
-- SELECT 1
+------+
|  a   |
+------+
| NULL |
| 0    |
| 1    |
+------+

-- SELECT 2
+------+
|  a   |
+------+
| 0    |
| 1    |
+------+

Body:
Looks like query optimizer chooses different comparison operator:

DECLARE @varname int;
SET @varname = 999;

SELECT a
FROM t1
WHERE a <> @varname;

XML execution plan:

<Predicate>
    <ScalarOperator ScalarString="[fiddle_84f7799901e54a779e8bff464a2d01f3].[dbo].[t1].[a] &lt;&gt; [@varname]">
        <Compare CompareOp="IS NOT">
            <ScalarOperator>
                <Identifier>
                    <ColumnReference Database="[fiddle_84f7799901e54a779e8bff464a2d01f3]" Schema="[dbo]" Table="[t1]" Column="a"></ColumnReference>
                </Identifier>
            </ScalarOperator>
            <ScalarOperator>
                <Identifier>
                    <ColumnReference Column="@varname"></ColumnReference>
                </Identifier>
            </ScalarOperator>
        </Compare>
    </ScalarOperator>
</Predicate>

Compare CompareOp="IS NOT"

Second query with hardcoded value:

SELECT a
FROM t1
WHERE a <> 999;

-- same as
DECLARE @varname int = 999;

SELECT a
FROM t1
WHERE a <> (SELECT @varname);

XML execution plan:

<Predicate>
    <ScalarOperator ScalarString="[fiddle_ac5121a789da473382366733b51ef441].[dbo].[t1].[a]&lt;&gt;(999)">
        <Compare CompareOp="NE">
            <ScalarOperator>
                <Identifier>
                    <ColumnReference Database="[fiddle_ac5121a789da473382366733b51ef441]" Schema="[dbo]" Table="[t1]" Column="a"></ColumnReference>
                </Identifier>
            </ScalarOperator>
            <ScalarOperator>
                <Const ConstValue="(999)"></Const>
            </ScalarOperator>
        </Compare>
    </ScalarOperator>
</Predicate>

Compare CompareOp="NE"

DBFiddle

EDIT:

SET ANSI_NULLS

SET ANSI_NULLS ON affects a comparison only if one of the operands of the comparison is either a variable that is NULL or a literal NULL. If both sides of the comparison are columns or compound expressions, the setting does not affect the comparison.


问:
Android Proguard change package name manually
When I was building my application I saw some package name doesn't obfuscate. I think these packages have some @Keep annotation classes.

But I want change package name manually. For example:

proguard-rules.txt

```<code>-applymapping mapping.txt
</code>```

mapping.txt

```<code>com.data.Net -> com.data.Q
</code>```

I tried this but It doesn't work. Isn't it possible?

答:
ProGuard does not have a standard option to rename packages yet keep their simple class names.

You could create a ProGuard mapping file manually, with lines like:

```<code>com.example.MyClass -> a.MyClass:
com.example.MyOtherClass -> a.MyOtherClass:
</code>```

You can then use the option -applymapping mapping.txt

Body:
When I was building my application I saw some package name doesn't obfuscate. I think these packages have some @Keep annotation classes.

But I want change package name manually. For example:

proguard-rules.txt

-applymapping mapping.txt

mapping.txt

com.data.Net -> com.data.Q

I tried this but It doesn't work. Isn't it possible?

Body:
ProGuard does not have a standard option to rename packages yet keep their simple class names.

You could create a ProGuard mapping file manually, with lines like:

com.example.MyClass -> a.MyClass:
com.example.MyOtherClass -> a.MyOtherClass:

You can then use the option -applymapping mapping.txt


问:
Use match from file in string
I have a list of user ids in a file and I'm trying to generate some sql from the file.

```<code>cat users.json | awk '/UID/{print "INSERT IGNORE INTO potential_problem_users VALUES ("$2");" }'
</code>```

But it's not doing what I expected it to do:

```<code>);SERT IGNORE INTO potential_problem_users VALUES ("1"
);SERT IGNORE INTO potential_problem_users VALUES ("2"
</code>```

The query I am trying for is:

```<code>INSERT IGNORE INTO potential_problem_users VALUES ([userID]);
</code>```

example json if it helps:

```<code>{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}
</code>```

Am I using the right tool? If I am, what am I doing wrong?

答:
```<code>awk -F: '/UID/ {print "INSERT IGNORE INTO potential_problem_users VALUES ("gensub(" ","","g",$2)");"}' users.json
</code>```

Use gensub to take the spaces out of second : delimited field. Note also that you don't need to cat the file to awk it.

Title: Use match from file in string

Body:
I have a list of user ids in a file and I'm trying to generate some sql from the file.

cat users.json | awk '/UID/{print "INSERT IGNORE INTO potential_problem_users VALUES ("$2");" }'

But it's not doing what I expected it to do:

);SERT IGNORE INTO potential_problem_users VALUES ("1"
);SERT IGNORE INTO potential_problem_users VALUES ("2"

The query I am trying for is:

INSERT IGNORE INTO potential_problem_users VALUES ([userID]);

example json if it helps:

{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}

Am I using the right tool? If I am, what am I doing wrong?

Body:
awk -F: '/UID/ {print "INSERT IGNORE INTO potential_problem_users VALUES ("gensub(" ","","g",$2)");"}' users.json

Use gensub to take the spaces out of second : delimited field. Note also that you don't need to cat the file to awk it.


问:
Display array in table with 2 columns
I have an array like this:

```<code>Array
(
    [0] => Array
        (
            [Title] => Title 1,
            [Value] => Value 1
        ),

    [1] => Array
        (
            [Title] => Title 2,
            [Value] => Value 2
        ),

    [2] => Array
        (
            [Title] => Title 3,
            [Value] => Value 3
        ),

    [3] => Array
        (
            [Title] => Title 4,
            [Value] => Value 4
        )

);
</code>```

And I would like to create a table like this:

```<code>|---------------------|------------------|
|      Title 1        |     Title 2      |
|---------------------|------------------|
|      Value 1        |     Value 2      |
|---------------------|------------------|
|      Title 3        |     Title 4      |
|---------------------|------------------|
|      Value 3        |     Value 4      |
|---------------------|------------------|
</code>```

I have found some foreach functions, but these all give me the title with the value next to it.. Any way to accomplish the above?

答:
Make use of the modulo operator, which calculates the remainder of the division of two numbers. Modulo operations are often used as solutions for processes which require repetitions with iteration steps bigger than 1 and in situations were chunking big data bundles is needed. Example: when you want to send 100 emails at once, then you loop through them and send them in packages of max. 10 per iteration step.

The principle applied in your case is: Loop through the source array and output a result (two table rows) each second iteration step, beginning with the first array key.

Version 1 - Output directly in HTML:

```<code><?php
/*
 * Original array.
 */
$source = [
    0 => [
        'Title' => 'Title 1',
        'Value' => 'Value 1'
    ],
    1 => [
        'Title' => 'Title 2',
        'Value' => 'Value 2'
    ],
    2 => [
        'Title' => 'Title 3',
        'Value' => 'Value 3'
    ],
    3 => [
        'Title' => 'Title 4',
        'Value' => 'Value 4'
    ],
    4 => [
        'Title' => 'Title 5',
        'Value' => 'Value 5'
    ],
];

echo 'ORIGINAL:```' . print_r($source, true) . '```';

/*
 * Filter array for empty/null values.
 * The result is another array.
 */
$source = array_filter($source, function($el) {
    return !(
            empty($el['Title']) ||
            !isset($el['Title']) ||
            empty($el['Value']) ||
            !isset($el['Value'])
            );
});

echo 'FILTERED:```' . print_r($source, true) . '```';

/*
 * Reset array keys by applying array_values().
 * The result is another array.
 */
$source = array_values($source);

echo 'ARRAY_VALUES:```' . print_r($source, true) . '```';
?>

<table>
    <?php
    foreach ($source as $key => $item) {
        if ($key % 2 == 0) {
            ?>
            <tr>
                <td>
                    <?php
                    if (isset($source[$key]['Title'])) {
                        echo $source[$key]['Title'];
                    }
                    ?>
                </td>
                <td>
                    <?php
                    if (isset($source[$key + 1]['Title'])) {
                        echo $source[$key + 1]['Title'];
                    }
                    ?>
                </td>
            </tr>
            <tr>
                <td>
                    <?php
                    if (isset($source[$key]['Value'])) {
                        echo $source[$key]['Value'];
                    }
                    ?>
                </td>
                <td>
                    <?php
                    if (isset($source[$key + 1]['Value'])) {
                        echo $source[$key + 1]['Value'];
                    }
                    ?>
                </td>
            </tr>
            <?php
        }
    }
    ?>
</table>
</code>```

Version 2 - Output from PHP:

```<code><?php

/*
 * Original array.
 */
$source = [
    0 => [
        'Title' => 'Title 1',
        'Value' => 'Value 1'
    ],
    1 => [
        'Title' => 'Title 2',
        'Value' => 'Value 2'
    ],
    2 => [
        'Title' => 'Title 3',
        'Value' => 'Value 3'
    ],
    3 => [
        'Title' => 'Title 4',
        'Value' => 'Value 4'
    ],
    4 => [
        'Title' => 'Title 5',
        'Value' => 'Value 5'
    ],
];

echo 'ORIGINAL:```' . print_r($source, true) . '```';

/*
 * Filter array for empty/null values.
 * The result is another array.
 */
$source = array_filter($source, function($el) {
    return !(
            empty($el['Title']) ||
            !isset($el['Title']) ||
            empty($el['Value']) ||
            !isset($el['Value'])
            );
});

echo 'FILTERED:```' . print_r($source, true) . '```';

/*
 * Reset array keys by applying array_values().
 * The result is another array.
 */
$source = array_values($source);

echo 'ARRAY_VALUES:```' . print_r($source, true) . '```';

$tableRows = '';
foreach ($source as $key => $item) {
    if ($key % 2 == 0) {
        $tableRows .= sprintf('
                            <tr>
                                <td>
                                    %s
                                </td>
                                <td>
                                    %s
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    %s
                                </td>
                                <td>
                                    %s
                                </td>
                            </tr>
                            '
                , isset($source[$key]['Title']) ? $source[$key]['Title'] : ''
                , isset($source[$key + 1]['Title']) ? $source[$key + 1]['Title'] : ''
                , isset($source[$key]['Value']) ? $source[$key]['Value'] : ''
                , isset($source[$key + 1]['Value']) ? $source[$key + 1]['Value'] : ''
        );
    }
}

echo sprintf('<table>%s</table>', $tableRows);
</code>```

Title: Display array in table with 2 columns

Body:
I have an array like this:

Array
(
    [0] => Array
        (
            [Title] => Title 1,
            [Value] => Value 1
        ),

    [1] => Array
        (
            [Title] => Title 2,
            [Value] => Value 2
        ),

    [2] => Array
        (
            [Title] => Title 3,
            [Value] => Value 3
        ),

    [3] => Array
        (
            [Title] => Title 4,
            [Value] => Value 4
        )

);

And I would like to create a table like this:

|---------------------|------------------|
|      Title 1        |     Title 2      |
|---------------------|------------------|
|      Value 1        |     Value 2      |
|---------------------|------------------|
|      Title 3        |     Title 4      |
|---------------------|------------------|
|      Value 3        |     Value 4      |
|---------------------|------------------|

I have found some foreach functions, but these all give me the title with the value next to it.. Any way to accomplish the above?

Body:
Make use of the modulo operator, which calculates the remainder of the division of two numbers. Modulo operations are often used as solutions for processes which require repetitions with iteration steps bigger than 1 and in situations were chunking big data bundles is needed. Example: when you want to send 100 emails at once, then you loop through them and send them in packages of max. 10 per iteration step.

The principle applied in your case is: Loop through the source array and output a result (two table rows) each second iteration step, beginning with the first array key.

Version 1 - Output directly in HTML:

<?php
/*
 * Original array.
 */
$source = [
    0 => [
        'Title' => 'Title 1',
        'Value' => 'Value 1'
    ],
    1 => [
        'Title' => 'Title 2',
        'Value' => 'Value 2'
    ],
    2 => [
        'Title' => 'Title 3',
        'Value' => 'Value 3'
    ],
    3 => [
        'Title' => 'Title 4',
        'Value' => 'Value 4'
    ],
    4 => [
        'Title' => 'Title 5',
        'Value' => 'Value 5'
    ],
];

echo 'ORIGINAL:<pre>' . print_r($source, true) . '</pre>';

/*
 * Filter array for empty/null values.
 * The result is another array.
 */
$source = array_filter($source, function($el) {
    return !(
            empty($el['Title']) ||
            !isset($el['Title']) ||
            empty($el['Value']) ||
            !isset($el['Value'])
            );
});

echo 'FILTERED:<pre>' . print_r($source, true) . '</pre>';

/*
 * Reset array keys by applying array_values().
 * The result is another array.
 */
$source = array_values($source);

echo 'ARRAY_VALUES:<pre>' . print_r($source, true) . '</pre>';
?>

<table>
    <?php
    foreach ($source as $key => $item) {
        if ($key % 2 == 0) {
            ?>
            <tr>
                <td>
                    <?php
                    if (isset($source[$key]['Title'])) {
                        echo $source[$key]['Title'];
                    }
                    ?>
                </td>
                <td>
                    <?php
                    if (isset($source[$key + 1]['Title'])) {
                        echo $source[$key + 1]['Title'];
                    }
                    ?>
                </td>
            </tr>
            <tr>
                <td>
                    <?php
                    if (isset($source[$key]['Value'])) {
                        echo $source[$key]['Value'];
                    }
                    ?>
                </td>
                <td>
                    <?php
                    if (isset($source[$key + 1]['Value'])) {
                        echo $source[$key + 1]['Value'];
                    }
                    ?>
                </td>
            </tr>
            <?php
        }
    }
    ?>
</table>

Version 2 - Output from PHP:

<?php

/*
 * Original array.
 */
$source = [
    0 => [
        'Title' => 'Title 1',
        'Value' => 'Value 1'
    ],
    1 => [
        'Title' => 'Title 2',
        'Value' => 'Value 2'
    ],
    2 => [
        'Title' => 'Title 3',
        'Value' => 'Value 3'
    ],
    3 => [
        'Title' => 'Title 4',
        'Value' => 'Value 4'
    ],
    4 => [
        'Title' => 'Title 5',
        'Value' => 'Value 5'
    ],
];

echo 'ORIGINAL:<pre>' . print_r($source, true) . '</pre>';

/*
 * Filter array for empty/null values.
 * The result is another array.
 */
$source = array_filter($source, function($el) {
    return !(
            empty($el['Title']) ||
            !isset($el['Title']) ||
            empty($el['Value']) ||
            !isset($el['Value'])
            );
});

echo 'FILTERED:<pre>' . print_r($source, true) . '</pre>';

/*
 * Reset array keys by applying array_values().
 * The result is another array.
 */
$source = array_values($source);

echo 'ARRAY_VALUES:<pre>' . print_r($source, true) . '</pre>';

$tableRows = '';
foreach ($source as $key => $item) {
    if ($key % 2 == 0) {
        $tableRows .= sprintf('
                            <tr>
                                <td>
                                    %s
                                </td>
                                <td>
                                    %s
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    %s
                                </td>
                                <td>
                                    %s
                                </td>
                            </tr>
                            '
                , isset($source[$key]['Title']) ? $source[$key]['Title'] : ''
                , isset($source[$key + 1]['Title']) ? $source[$key + 1]['Title'] : ''
                , isset($source[$key]['Value']) ? $source[$key]['Value'] : ''
                , isset($source[$key + 1]['Value']) ? $source[$key + 1]['Value'] : ''
        );
    }
}

echo sprintf('<table>%s</table>', $tableRows);


问:
My loop isn't drawing anything to the screen
I'm having difficulty with a simple while loop.

```<code>size(500,500);
background(255);
rectMode(CENTER);
noCursor();

int x1 = mouseX;
int y1 = mouseY;
int count = 0;
fill(0);
rect(250,250,50,50); //this is drawn
while (count == 0); {
  fill(0);
  rect(250,250,50,50); //this is not
}
</code>```

Its written in Processing.
Anything I have in the while loop isn't drawn, while anything after it isn't either. Anything before it, not in a loop, is drawn. What am I missing here?

答:
You have a typo in your while loop, you have a ; which is ending the while loop and will not execute it, replace your while-loop with:

```<code>while (count == 0) {
  fill(0);
  rect(250,250,50,50); //this is not
}
</code>```

In Processing you shouldn't create infinite loops like you're doing, there is a draw() function which you can write which will do a similar thing:

```<code>void draw() {
  fill(0);
  rect(250,250,50,50); //this is not
}
</code>```

This needs to be accompanies with a setup() function, the setup function only runs once in the beginning of the program:

```<code>int x1,y1;

void setup(){
  size(500,500);
  background(255);
  rectMode(CENTER);
  x1 = mouseX;
  y1 = mouseY;
  fill(128);
  rect(250,250,50,50); //this is drawn
}
void draw(){
    fill(0);
    rect(250,250,50,50); //this is not
}
</code>```

Maybe you're new to processing but you should consider using this layout as it is the core of the framework.

Body:
I'm having difficulty with a simple while loop.

size(500,500);
background(255);
rectMode(CENTER);
noCursor();

int x1 = mouseX;
int y1 = mouseY;
int count = 0;
fill(0);
rect(250,250,50,50); //this is drawn
while (count == 0); {
  fill(0);
  rect(250,250,50,50); //this is not
}

Its written in Processing.
Anything I have in the while loop isn't drawn, while anything after it isn't either. Anything before it, not in a loop, is drawn. What am I missing here?

Body:
You have a typo in your while loop, you have a ; which is ending the while loop and will not execute it, replace your while-loop with:

while (count == 0) {
  fill(0);
  rect(250,250,50,50); //this is not
}

In Processing you shouldn't create infinite loops like you're doing, there is a draw() function which you can write which will do a similar thing:

void draw() {
  fill(0);
  rect(250,250,50,50); //this is not
}

This needs to be accompanies with a setup() function, the setup function only runs once in the beginning of the program:

int x1,y1;

void setup(){
  size(500,500);
  background(255);
  rectMode(CENTER);
  x1 = mouseX;
  y1 = mouseY;
  fill(128);
  rect(250,250,50,50); //this is drawn
}
void draw(){
    fill(0);
    rect(250,250,50,50); //this is not
}

Maybe you're new to processing but you should consider using this layout as it is the core of the framework.


问:
Mail Stuck in Outbox of Outlook 2013 sent using Redemption
Currently i am in a process of migrating applications to new version, i am  facing a problem in the application. Basically its a VBA Access application which will send reports to users. For the mail delivery part it uses Redemption.dll

Current Versions:

Windows XP

MS Office 2003

Redemption.dll v 4.5.0.812

Migrating To

Windows 7

MS Office 2013

Redemption.dll v 4.5.0.812

Scenario 1: In Win 7 machine using the redemption.dll v 4.5.0.812 when i run the application, the report delivery function runs without errors. But what i noticed is the mails are stuck in Outbox. When i open Outlook 2013 the mails get delivered. So when i keep outlook open and run the function the mails get delivered.

Scenario 2: Now in Win 7 machine using the developer version redemption.dll v 5.14 too the mail get stuck in Outbox.

What could be the reason, is there need to do code changes or is it some setting changes related to Outlook 2013?
Any kind of help would be very useful.... need it badly :-)
If there is a need to do code changes, is it possible keeping the redemption.dll version v 4.5 (as per the requirement)

Let me know if you need more information.

Thanks

答:
From http://www.dimastr.com/redemption/faq.htm#1

When I send a message using Redemption, it simply stays in the Drafts folder

Message submission is a two step process in Extended MAPI:

Calling IMessage::Submit()

Flushing the outgoing message queue.

If you are using an Exchange Server, step #2 is not required since Exchange Message Store is tightly bound with the Exchange Transport provider. If you however are using a POP3/SMTP transport and a PST file as a message store, step #2 is required. To flush the message queues, create an instance of Redemption.MAPIUtils object and call its DeliverNow method (similar to Session.DeliverNow in CDO) after calling SafeMailItem.Send:

```<code>MailItem.Send
Set Utils = CreateObject("Redemption.MAPIUtils")
Utils.DeliverNow
</code>```

There is however one problem if you are using Outlook 2002 or newer with a PST file and POP3/SMTP transport provider or Outlook 2000 installed in the Internet Only Mode: there is no way to flush the queues using Extended MAPI. That part of Outlook is simply broken. Note however that Outlook 2002/2003 (online) with an Exchange Server or Outlook 2000 C/W in any configuration are fine.

If you are using Outlook 2003 or higher with Exchange in a cached mode, it will exhibit the same problem. Uncheck "Use cached mode" in the Exchange Server properties to force online mode - that will ensure that messages are delivered immediately.

As a last resort, you can simulate clicking "Send/Receive" button in Outlook after sending a message:

```<code>MailItem.Send
Set Btn = Application.ActiveExplorer.CommandBars.FindControl(1, 5488)
Btn.Execute
</code>```

Note that in Outlook 2003 that button is now a dropdown, the real Send/Receive is a subitem of the button:

```<code>Set Btn = Application.ActiveExplorer.CommandBars.FindControl(1, 7095)
Btn.Execute
</code>```

Note that the code above assumes that there is an active Explorer; this will not be the case if you start Outlook programmatically (and it was not previously started by a user) and do not display any folders. In this case you can start a sync using the the Namespace.SyncObjects collection.:

```<code> set NS = Application.GetNamespace("MAPI")
 NS.Logon
 Set Sync = NS.SyncObjects.Item(1)
 Sync.Start
</code>```

In Outlook 2010 you can also use Namespace.SendAndReceive method.

Body:
From http://www.dimastr.com/redemption/faq.htm#1

When I send a message using Redemption, it simply stays in the Drafts folder

Message submission is a two step process in Extended MAPI:

Calling IMessage::Submit()

Flushing the outgoing message queue.

If you are using an Exchange Server, step #2 is not required since Exchange Message Store is tightly bound with the Exchange Transport provider. If you however are using a POP3/SMTP transport and a PST file as a message store, step #2 is required. To flush the message queues, create an instance of Redemption.MAPIUtils object and call its DeliverNow method (similar to Session.DeliverNow in CDO) after calling SafeMailItem.Send:

MailItem.Send
Set Utils = CreateObject("Redemption.MAPIUtils")
Utils.DeliverNow

There is however one problem if you are using Outlook 2002 or newer with a PST file and POP3/SMTP transport provider or Outlook 2000 installed in the Internet Only Mode: there is no way to flush the queues using Extended MAPI. That part of Outlook is simply broken. Note however that Outlook 2002/2003 (online) with an Exchange Server or Outlook 2000 C/W in any configuration are fine.

If you are using Outlook 2003 or higher with Exchange in a cached mode, it will exhibit the same problem. Uncheck "Use cached mode" in the Exchange Server properties to force online mode - that will ensure that messages are delivered immediately.

As a last resort, you can simulate clicking "Send/Receive" button in Outlook after sending a message:

MailItem.Send
Set Btn = Application.ActiveExplorer.CommandBars.FindControl(1, 5488)
Btn.Execute

Note that in Outlook 2003 that button is now a dropdown, the real Send/Receive is a subitem of the button:

Set Btn = Application.ActiveExplorer.CommandBars.FindControl(1, 7095)
Btn.Execute

Note that the code above assumes that there is an active Explorer; this will not be the case if you start Outlook programmatically (and it was not previously started by a user) and do not display any folders. In this case you can start a sync using the the Namespace.SyncObjects collection.:

 set NS = Application.GetNamespace("MAPI")
 NS.Logon
 Set Sync = NS.SyncObjects.Item(1)
 Sync.Start

In Outlook 2010 you can also use Namespace.SendAndReceive method.


答:
You could have also updated your gpg tool to a newer version, while you used also your old one. In this case, a parent-less gpg-agent remains in your process tree, with the already false version.

The solution is simply to kill him. Gpg will re-start it, this time a correct one.

Title: Error with git commits: 'gpg-agent' is older than us (2.0.30 < 2.1.20)

Body:
How would I go about fixing this?

gpg: WARNING: server 'gpg-agent' is older than us (2.0.30 < 2.1.20)


问:
Grails additional columns in table or list
I'm trying for several days to receive a list from my Data. The Domain looks like this:

```<code>class Alpha {
    String a
    String b
    etc.
    static hasMany = [beta:Beta]

}

class Beta {
    String a
    Integer foo
    String status
    static belongsTo = [alpha:Alpha]
    static constraints = {
        status(nullable:false, inList:["val1","val2","val3", "val4"])
    }
}
</code>```

I'd like to have in Alpha the sum of all Beta.foo and of all Beta.foo in a certain status. Best would be something like an additional row ( Integer sumVal1 ... ).

I tried named queries:

```<code>static namedQueries = {
        erledigterProbeAufwend {
            createAlias ('Beta', 'b')
            eq ('b.status', 'val1')
            projections {
                groupProperty('b.alpha')
                sum('b.foo', 'sumFooVal1')
            }
        }
}
</code>```

But this just give me one sum at a time.

I'm looking forward to get some help on that.

Greetings
Bas

答:
Create transient variables in your Alpha class and populate them in an onLoad event.</p>

```<code>class Alpha {
    String a
    String b
    etc.
    static transients = ["sumVal1",...]
    static hasMany = [beta:Beta]

    def onLoad = {
       sumVal1 = ....
    }

}
</code>```

Body:
I'm trying for several days to receive a list from my Data. The Domain looks like this:

class Alpha {
    String a
    String b
    etc.
    static hasMany = [beta:Beta]

}

class Beta {
    String a
    Integer foo
    String status
    static belongsTo = [alpha:Alpha]
    static constraints = {
        status(nullable:false, inList:["val1","val2","val3", "val4"])
    }
}

I'd like to have in Alpha the sum of all Beta.foo and of all Beta.foo in a certain status. Best would be something like an additional row ( Integer sumVal1 ... ).

I tried named queries:

static namedQueries = {
        erledigterProbeAufwend {
            createAlias ('Beta', 'b')
            eq ('b.status', 'val1')
            projections {
                groupProperty('b.alpha')
                sum('b.foo', 'sumFooVal1')
            }
        }
}

But this just give me one sum at a time.

I'm looking forward to get some help on that.

Greetings
Bas

Body:
Create transient variables in your Alpha class and populate them in an onLoad event.

class Alpha {
    String a
    String b
    etc.
    static transients = ["sumVal1",...]
    static hasMany = [beta:Beta]

    def onLoad = {
       sumVal1 = ....
    }

}