text:
Q: unchecking HTML checkbox using perl Mojolicious How can I uncheck a checkbox by default using perl Mojolicious?
what I currently have checks the box by default and sets the value to 1:
%= check_box employed => 1

A: The code you show does not check the checkbox by default.
check_box 'employed' => 1 renders a checkbox with name set to employed and value set to 1. Whether it is rendered in checked state depends on the employed param.
Perhaps you are seeing that Mojolicious picks up the employed param from the request and uses its value to render the checkbox accordingly (which is default behavior).
If you don't want that, you can reset the param to a false value to always render the box unchecked:
use Mojolicious::Lite -signatures;
use Data::Dumper;

any '/testform' => sub ($c) {
    print Dumper($c->param('option'));
    # reset (render unchecked):
    $c->param(option=> 0);
    $c->render(template => 'testform');
};
app->start;

__DATA__
@@ testform.html.ep

%= form_for testform => begin
  %= check_box 'option'=> 1
  %= submit_button
% end


text:
Q: Delphi Dynamically create a tlable - where to put it on the form I want to create a label dynamically. I followed: how to dynamically create a component in delphi such as TLabel or TEdit ...etc
I have decleared by label like this:
 listofnames[i]:=TLabel.create(quiz2);
 listofnames[i].parent:=quiz2;
 listofnames[i].caption:=quiz.getsubjectname(i);
 listofnames[i].height:=25;
 listofnames[i].Width:=85;
 listofnames[i].left:=8;
 listofnames[i].top:=135+i*30;
 listofnames[i].OnClick:=labelclicked;

and in my form class at the top of the unit I have this:
 type
  Tlblarr=array of TLabel;
  TQuiz2 = class(TForm)
  //published section
    Q2LTitle: TLabel;
    Q2LIntro1: TLabel;
    Q2LMon: TLabel;
    Q2LTue: TLabel;
    Q2LWed: TLabel;
    Q2LFri: TLabel;
    Q2LThurs: TLabel;
    Q2LSun: TLabel;
    Q2LSat: TLabel;
    Q2ButStart: TButton;
    Q2LSubList: TLabel;
    Q2ButFin: TButton;
   //all above are other things on my form
    listofnames:Tlblarr;
  //array of dynamicly create labels
    procedure Q2ButStartClick(Sender: TObject);
    procedure labelclicked(Sender:TObject);
    procedure timeslotclicked(Sender:TObject);
    procedure Q2ButFinClick(Sender: TObject);
    procedure FormActivate(Sender: TObject);
  private
    clickedfirst:string;
    numberofsub:integer;
    numberofextra:integer;
   public
  end;

I am getting the following error:

Published field listofnames not a class or interface type

So I am presuming it is not meant to be published? However if I move it to the public or private section I get a different error:

Exception class EClassNotFound with message 'Class TLabel not found'

The example I was going off didn't mention it, so I presume it is something common sense I don't know yet. I have looked over the internet for the cause of the two errors and most people's problems are different than mine or the solution won't work - putting the label in the published spot seems to be the most common. Both errors occur in the same way: it compiles and at run immediately the exception draws up. I believe this is because the line Application.CreateForm(TQuiz2,Quiz2). This is in the Project1 section - a section I've never coded in or touched, it didn't even appear until I debugged the program.
Could someone indicate wherever the label array is definitely meant to go in published and where I can find more on how to debug this error. I have looked at http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/Classes_EClassNotFound.html and http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/cm_cannot_publish_xml.html and I am still failing to understand.

A: For runtime constructed field objects, they go in private or protected (or very rarely public) section. This depends on how you want them to be visible to other or descending forms (forms can be inherited like other classes). Put it under private unless you have a good reason to put it somewhere else.
The declarations between the classname and private are for the design time fields, so it is looking in your .dfm file for the properties of those objects.
As an aside, it is convention in Delphi to start a field variable with F, so FListOfNames: Tlblarr; FClickedOnFirst etc

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write sql query to get the below result I have a table with below data.

And the expected result will be below data.

Here step1 completion date is arrival date of step2 and the step2 completion date is arrival date of step3.
How to write SQL query to get this result.

A: This Script gives your expected Result
;With Cte(
id,StepName,ArrivalDate,duedate
)
AS
(
SELECT 1,'Step1','25/12/2017','1/1/2018' UNION ALL
SELECT 2,'Step2','26/12/2017','1/1/2018' UNION ALL
SELECT 3,'Step3','27/12/2017','1/1/2018'
)
SELECT
     id
     ,StepName
     ,ArrivalDate
     ,duedate
     ,ISNULL(LEAD(ArrivalDate,1)OVER(ORDER BY ArrivalDate),'') AS CompletionDate
FROM CTE

Result
id  StepName    ArrivalDate duedate    CompletionDate
-----------------------------------------------------
1   Step1       25/12/2017  1/1/2018    26/12/2017
2   Step2       26/12/2017  1/1/2018    27/12/2017
3   Step3       27/12/2017  1/1/2018

A: This should serve your purpose, completion date as startdate from next id
SELECT x.id
    ,x.stepname
    ,x.arrival_date
    ,x.due_date
    ,isnull(y.arrival_date, '') Completion_date
FROM x
LEFT JOIN (
    SELECT id
        ,step1
        ,step2
        ,arrival_date
    FROM x
    ) y ON x.id = y.id + 1

A: Give a row number based on ascending order of id column.(If id column has any gaps). Then use a LEFT JOIN / RIGHT JOIN with rn = rn + 1.
Query
;with cte as(
    select [rn] = row_number() over(
        order by [id]
    ), *
    from [your_table_name]
)
select t1.[stepName], t1.[ArrivalDate], t1.[dueDate],
coalesce(t2.[dueDate], '') as [completiondate]
from cte t1
left join cte t2
on t1.[rn] + 1 = t2.[rn];

A: some_logical_grouping_of_data shoud define group of data which can be used for.
Select ID, stepname, arrival_date, duedate,
LEAD ( arrival_date) OVER ( partition by "some_logical_grouping_of_data" order by ID) as completion_date
from table;

A: It's a bad idea to join data based on String suffixes. I assume that step1 always has ID 1, step13 always has ID 13 and so on. Then you can do something like
SELECT t1.ID, t1.Stepname, t1.arrival_date, t2.arrival_date as completion_date
    FROM tablename t1
    LEFT JOIN tablename t2 on t1.ID + 1 = t2.ID;


text:
Q: error while loading shared libraries libboost_thread.so.1.54.0 For anyone having this issue. I was trying to run Long-term Recurrent Convolutional Networks by Jeff Donahue.
https://github.com/LisaAnne/lisa-caffe-public
$ soubriquet@ubuntu:/usr/local/caffe/examples/LRCN_activity_recognition$ ./run_lstm_RGB.sh
$ ../../build/tools/caffe: error while loading shared libraries: libboost_thread.so.1.54.0: cannot open shared object file: No such file or directory Done.

A: The following fixed my issue:
$ sudo apt-get remove libboost*
$ sudo apt-get purge libboost*
$ sudo apt-get install libboost1.54-all-dev


text:
Q: ¿Cómo puedo hacer que un método brujo devuelva el resultado de una ventana de confirmación realizada con SweetAlert2? Estamos probando un método similar a window.confirm(), pero administrado con SweetAlert2
He intentado esto:
function confirmAlert(txt) {
     return new Promise((resolve, reject) => {
        Swal.fire({
            text: txt,
            showCancelButton: true
        }).then((result) => {
            resolve(result.isConfirmed);
        })
     })
}

Pero ejecutando el código la ventana se cierra rápidamente sin pulsar ningún botón.
¿Puede alguien ayudarme por favor?


text:
Q: jQuery Ajax load HTML content with image, how to check whether all images are loaded? I'm doing a script for infinite scroll for my site:
$(window).scroll(function(){
  if($(window).scrollTop() == $(document).height() - $(window).height()){
    ...
    $.ajax({
      ...
      success: function(json) {if(json.success){
        ...
        // here I append an Ajax @response with a new element to my existing HTML
        $("#mindIndexSummaryFirst").append(json.items1);
        $("#mindIndexSummarySecond").append(json.items2);
        $("#mindIndexSummaryThird").append(json.items3);
        // here I try to check whether all images are loaded
        $("#mindIndexSummary img").on('load', function(){
          // and I need to call two functions on loaded element
          // hoverImg() need the loaded image to calculate the height
          $('.pi-hover-img'+json.course).hoverImg();
          $(".popup3").tooltip();
        });
      }
    ...
  });

A loaded HTML element is this:

   Mi interessa
  Description
  Preview
  1€

Gestire un pubblico

I load 5 elements, 15 images, but there is a possibility that fewer elements are loaded.
The problem is that my function was called more than one time (I test this with alert) and I'm not sure secure that the function was called after image load.
If someone had the same situation please suggest me something (P.S I apologize for my bad English).

A: $("#mindIndexSummary img").on('load', function(){ });

Will attach the handler to each of the images that match the query - so each image will fire the function when it is loaded - not once when all are finished loading.
You would have to keep track of the images that have loaded in order to say whether they have all loaded.
Along the lines of:
var noOfImages = $("#mindIndexSummary img").length;
var noLoaded = 0;

$("#mindIndexSummary img").on('load', function(){

    noLoaded++;
    if(noOfImages === noLoaded) {
        handleAllLoaded();
    }

});

A: This is a rough version of a solution I've used in a similar situation. numLoaded is updated each time the load method is executed, which allows you to check if the forecast ( numImage ) is equal to the total amount of images loaded.
var img =  $( '#mindIndexSummary' ).find( 'img' )
  , numImage = img.length;

img.on( 'load', function(){

    var self = $( this )
      , numLoaded  = self.attr( 'data-loaded', true ).length;

    self.attr( 'data-loaded', true );

    if( numImages === numLoaded )

    funcToCall();

});

Also, you can go one step further and set a data attribute on the parent element, which would allow you to trigger/terminate other events based on its value.
var parent = $( '#mindIndexSummary' )
  , img =  $( '#mindIndexSummary' ).find( 'img' )
  , numImage = img.length;

img.on( 'load', function(){

    var self = $( this )
      , numLoaded  = self.attr( 'data-loaded', true ).length;

    parent.attr( 'data-load', 'loading' );
    self.attr( 'data-loaded', true );

    if( numImages === numLoaded )

    parent.attr( 'data-load', 'complete' );
    funcToCall();

});

if( parent.attr('data-load').slice( 0, 7 ) === 'loading' )
do something else

A: Load event on images is a bit unreliable (see Jquery docs at http://api.jquery.com/load-event/).
That said, it's possible to assemble a solution by checking individually for load event on every selected image. Chances are that an image is cached or already loaded at time of execution. In this case the image element should have a ".complete" attribute.
I made a small jQuery plugin that illustrates the approach (there are more complete ones anyway):
(function($) {
    $.fn.imagesLoaded = function(options) {
        var images = this.find("img"),
            loadedImages = [],
            options = options;

        images.each(function(i, image) {
            function loaded() {
                loadedImages.push(this);
                if(options.imageLoaded) {
                    options.imageLoaded(this);
                }
                if(loadedImages.length == images.length) {
                    if(options.complete) {
                        options.complete(loadedImages);
                    }
                }
            }

            if(image.complete || image.complete === undefined) {
                // Image is already loaded
                loaded.call(image);
            } else {
                // Image is not loaded yet, bind event
                $(image).load(loaded);
            }
        });
    }
})(jQuery);

The plugin accepts a hash with two callbacks, one firing each time an image is loaded (the image gets passed as a parameter), the other when all images have loaded (the array of images gets passed as a parameter).
$("#element-containing-images").imagesLoaded({
    imageLoaded: function(image) {
       console.log("Image loaded:", image);
    },
    complete: function(images) {
        console.log("All images loaded:", images);
    }
});

It's not complete with all the quirks, but it should give you a general idea.
I made a small demo available at http://jsfiddle.net/GYJGK/.

A: This is a description of how to create a global variable (an array) that will keep track of each individual image that is loaded. This way you can actively check when all images are loaded using callback functions.
var image_state_array = new Array(false, false, false, false, false, false, false, false, false, false);

Each position in the array will keep track of which image has been loaded. So for example if image 2 in the list of 10 images has been loaded the array would look like this (remember array indexes start at 0):
var image_state_array = new Array(false, false, true, false, false, false, false, false, false, false);

Lets say you have a list of images that you are dynamically reloading based on some user interaction (for instance the user clicks refresh to get a new set of images to choose from). Once all of the images have loaded you want to alert the user that the images have loaded (or call some other sort of function). Start by first setting up an onload event for the image that is about to be loaded.
//get image 0

var image = document.getElementsByClassName("search_images")[0];

//track the image load state

image.onload = function(){
      trackImageLoadState(0); //note that 0 is the image index from the list of elements
}

Next set the source of the image as you usually would. This will trigger the onload even and call the function.
//set the source of the image,

    image.src = desireImagePNG;

The track image load state will add that the image has loaded to the image_state_array, tracking that image0 has loaded. After it records that image0 has loaded, it loops through the image_state_array and counts how many of the returned images have loaded. If the enough images have loaded it executes whatever function you were trying to achieve. In this example I am fading out a loading screen.
    function trackImageLoadState(numImage){
      //debug print
      //console.log("numImage: " + numImage);

      //set the array image value to true of the passed in index
      image_state_array[numImage] = true;

      //debug print
      //console.log("image_state_array[numImage] " + image_state_array[numImage] );

      var loadedImagesCount = 0;

      //loop through the array and count the amount of images that have loaded
      for(var counter2 = 0; counter2 < image_state_array.length; counter2++){
        //debug print
        //console.log("image_state_array[counter] " + image_state_array[counter2] + "counter" + counter2 );

        if(image_state_array[counter2]){
          loadedImagesCount++;
        }
      }

      //debug print
      //console.log("loadedImagesCount: " + loadedImagesCount);

      //if the amount of images required to be loaded has been met, execute function. If you want to know when all images have been loaded, you need to set the if statement condition to the total count of images. For example:
if(loadedImagesCount>10){} if you have 10 images.

  if(loadedImagesCount>5){

    //fade out the loading screen - any other function will work here as well
    fadeOutMainLoadingScreen();

  }

}

Keep in mind that the global variable will have to be reset everytime the action is called again. This can done as shown below:
//reset the global variable array to track the new load of images

for(var i = 0; i < image_state_array.length; i++){
  image_state_array[i] = false;
}

This is an effective way to track which images have loaded via a callback function and a global variable. Please comment as I know it could probably be improved and made more dynamic. Thanks!


text:
Q: How to apply spacing between chart and the label in ngx line chart I have been facing an issue where I have X and Y axis label, when ever I zoom in or zoom out  a page sometimes the label gets overlapped with the X and Y axis data. Refer the below image for reference .

There is no space between the value and label, kindly help me in increasing the space between the value and label.

            <mat-toolbar  class="NavToolClass" style="height:31.5px;border-radius: 2px;">
                 {{val.value}}
            </mat-toolbar>

            <ngx-charts-line-chart style="padding:10px 10px 10px 10px;" (window:resize)="ResizeChart(ContainerRef1.offsetWidth)"
            [results]="val.key"
            [gradient]="verticalBarOptions.gradient"
          [xAxis]="verticalBarOptions.showXAxis"
          [yAxis]="verticalBarOptions.showYAxis"
          [legend]="false"
          [showXAxisLabel]="verticalBarOptions.showXAxisLabel"
          [showYAxisLabel]="verticalBarOptions.showYAxisLabel"
          [xAxisLabel]="verticalBarOptions.xAxisLabel"
          [yAxisLabel]="verticalBarOptions.yAxisLabel"
          [showGridLines]="verticalBarOptions.showGridLines"
          [legend]="verticalBarOptions.showLegend"
          [yScaleMax]="1200"
          [view]="view">
        </ngx-charts-line-chart>

verticalBarOptions = {
showXAxis: true,
showYAxis: true,
gradient: false,
showLegend: false,
showGridLines: true,
showXAxisLabel: true,
xAxisLabel: "Date",
showYAxisLabel: true,
yAxisLabel: "Size (GB)",
animations:true,
barPadding:5,
groupPadding:5

};


text:
Q: Microsoft LogParser CSV output format - suppression of double quoting I am having a problem with MS LogParser v2.2 and cannot seem to track down "the solution".
I am importing a UTF-16 TSV file with headers and am trying to export a subset of these fields this to a CSV file, generally with no processing, but with one instance of concatenating two of the fields with an intervening space (combining a first and last name into a full name).
The problem is that not only are all the fields double quoted irrespective of the oDQuotes argument (which I can happily ignore), but the concatenated field contains the result of that double quoting. I.e. given two fields Fred and Bloggs, the contents of the concatenated field is always
"Fred" "Bloggs"
rather than the less harmful
"Fred Bloggs"
or even
Fred Bloggs
no matter what the value of the oDQuotes parameter (OFF, AUTO or ON). The presence of these double quotes cannot be ignored or easily discarded.
I have tried this both in a batch file and in Windows Script:
e.g. Batch File:
set lp=%ProgramFiles(x86)%\Log Parser 2.2\LogParser.exe
set fields=[Buyer E-mail Address]
set fields=%fields%, [Order ID]
set fields=%fields%, [Shipping Addr 1]
set fields=%fields%, [Shipping Addr 2]
set fields=%fields%, [Shipping City]
set fields=%fields%, [Shipping Postal Code]
set fields=%fields%, [Buyer First Name]
::set fields=%fields%, strcat([Buyer First Name], ' ', [Buyer Last Name]) --- does not work. :-(
set fields=%fields%, strcat([Buyer First Name], strcat(' ', [Buyer Last Name]))
set fields=%fields%, [Buyer Last Name]
set fields=%fields%, [Buyer Company]
set fields=%fields%, [Buyer Day Phone]

set sql=SELECT %fields% into chad_out.csv from %1

"%lp%" -q:ON -i:TSV -icodepage:-1 -nSep:1 -fixedSep:on -o:CSV -oDQuotes:OFF -fileMode:1 "%sql%"

or JScript:
function ProcessFile(filename) {
  DebugEcho(50, "D&D File name is <" + filename + ">");

  var lq = WScript.CreateObject("MSUtil.LogQuery");
  var lqif = WScript.CreateObject("MSUtil.LogQuery.TSVInputFormat");
  var lqof = WScript.CreateObject("MSUtil.LogQuery.CSVOutputFormat");

  // check that we actually have the objects in question
  if (lq && lqif && lqof) {
    DebugEcho(100, "Everything ok");
  } else {
    DebugEcho(0, "Something bad with LogQuery objects - exiting");
    WScript.Quit(1);
  }

  // see command line "> LogParser.exe -h -i:TSV" for details
  lqif.codepage = -1;   // this is for unicode
  lqif.fixedSep = true; // seems to need this
  lqif.nSep = 1;        // seems to need this?

  // see command line "> LogParser.exe -h -o:CSV" for details
  lqof.oDQuotes = "OFF";  // OFF | AUTO | ON - doesn't make any difference!
  lqof.fileMode = 1;  // 0 - append, 1 - overwrite, 2 - ignore

  var fields = [
    "[Buyer E-mail Address]",
    "[Order ID]",
    "[Shipping Addr 1]",
    "[Shipping Addr 2]",
    "[Shipping City]",
    "[Shipping Postal Code]",
    "[Buyer First Name]",
    "strcat([Buyer First Name], strcat(' ', [Buyer Last Name]))", //
    "[Buyer Last Name]",
    "[Buyer Company]",
    "[Buyer Day Phone]"
  ];

  var sql = [
    "SELECT",
    fields.join(", "),
    "INTO", "chad_out.csv",
    "FROM", filename
  ].join(" ");

  DebugEcho(20, "query string:", sql);

  lq.ExecuteBatch(sql, lqif, lqof);
}

I'm afraid I can't actually give any data as it's confidential, but I hope that the illustration I have given is sufficient.
I do have other alternatives (i.e. Python csv) but this requires at least packaging the script into an executable (I do not wish to install Python as generally available software).
Can anyone spot something that I have obviously missed to control the behaviour of quoting or is this a deficiency of an otherwise powerful tool? Googling oDQuotes does not seem to be very productive.

A: It sounds like the quotes are in the input TSV file, aren't they? If that's the case, then the quotes are imported with the field values and you'll need to strip them off with your query (using SUBSTR(MyField, 1, -1)).
TSV does not expect quoted fields and thus it does not remove them.


text:
Q: Angular UI Modal controller is not exposed to directives I need to create a directive that can be used inside Angular UI modal. This directive also need to know about modal's controller in order to use some functions from it. What I have now:
JS:
'use strict';

var DemoApp = angular.module('DemoApp', [ 'ui.bootstrap' ]);

DemoApp.controller('PageController', ['$scope', '$modal', function($scope, $modal){
  $scope.openModal = function(){
    var scope = $scope.$new(true);

    $modal.open({
      'templateUrl' : 'modal.html',
      'controller' : 'ModalController',
      'scope' : scope
    });
  }
}]);

DemoApp.controller('ModalController', ['$scope', '$modalInstance', function($scope, $modalInstance){
  $scope.ok = function() {
    $modalInstance.dismiss();
  };

  $scope.cancel = function() {
    $modalInstance.dismiss();
  };
}]);

DemoApp.directive('expression', function() {
  return {
    restrict : 'A',
    require : ['ngModel', '^ModalController'],
    link : function(scope, element, attrs, controllers) {
      console.log(arguments);
    }
  };
});

Modal template:

Test!

  <input data-ng-model="someValue" expression>{{someValue}}

  <button class="btn btn-primary" data-ng-click="ok()">Ok</button>
  <button class="btn btn-warning" data-ng-click="cancel()">Cancel</button>

And the red button:
<button id="demoButton" class="btn btn-primary" data-ng-click="openModal()">Click me!</button>

But when the modal is created ModalController is not resolved, and I get $compile:ctreq error:
Error: [$compile:ctreq] http://errors.angularjs.org/1.2.17/$compile/ctreq?p0=ModalController&p1=expression
    at Error (native)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:6:450
    at D (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:51:80)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:51:137
    at Array.forEach (native)
    at q (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:7:280)
    at D (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:51:114)
    at N (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:54:128)
    at g (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:47:82)
    at g (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js:47:99) <input data-ng-model="someValue" expression="" class="ng-pristine ng-valid">

I tried to debug the code: getControllers() somewhere around 6433 LOC at angular.js is used to search controller: value = value || $element[retrievalMethod]('$' + require + 'Controller');, so I tried to require Modal instead of ModalController (Controller is appended by Angular), but it didn't help. I cannot understand how $element[retrievalMethod] works (stepped into it, but it is to low-level). So, I'm stuck and appreciate any help.
I've created a Plunk, so you can play and see in console what I mean.

A: Please, checkout updated plunker:

*

*ModalController scope isn't child scope of PageController, so if you need to pass variables to ModalController you should do it through resolving dependencies directly.

*In your directive you can set scope as child of ModalController scope, so you can have access to functions defined there instead of requiring ModalController.


text:
Q: How to map/join two tables and filter by parameters using dapper I want to join two tables that have a relationship with each other,
In the Customer table, there are two columns for deleted and approved. Get the Customer that are approved and not deleted then match the Customer with the Loan table Using CustId (Both Tables has CustId) and Filter by supplied parameters

*

*Deleted=0

*Approved=1

Passed Parameters are(And they can be optional) User can pass only one or two or more than 2
InterestRate
LoanTrfDate
LastPaymentDate
        public async Task<IEnumerable<Loan>> ManageGettingAll(string InterestRate, string LoanTrfDate, string LastPaymentDate)
        {
            IEnumerable<Loan> loans = null;

            //var sql = "Select * from MonthlyInterest where LoanAccountNo=@Id AND Deleted=@Deleted AND CAST(TranDate AS DATE) BETWEEN @StartDate AND @EndDate";
            try{

                using (var conn = new SqlConnection(connectionstring))
                {
                    await conn.OpenAsync();

                    var parameters = new
                    {
                        InterestRate = InterestRate,
                        LoanTrfDate = LoanTrfDate,
                        LastPaymentDate = LastPaymentDate
                    };

                string sql = "Select l.*, c.FirstName_CompanyName from dbo.Loan l left join Customer where and l.Deleted = 0 and and l.Approved = 1 c on  l.CustId=c.CustId Where InterestRate=@InterestRate AND CAST(LoanTrfDate AS DATE)=@LoanTrfDate AND CAST(LastPaymentDate AS DATE)=@LastPaymentDate";

                    loans = await conn.QueryAsync<Loan>(sql, parameters);
                }
            }
            catch (Exception ex)
            {

                throw;
            }

            return loans;
        }

A: to filter by a parameter only if it's not null, you can use the SQL below.
Select l.*, c.FirstName_CompanyName
from dbo.Loan l
left join Customer c on l.CustId=c.CustId
where l.Deleted = 0 and l.Approved = 1
and (@InterestRate is null or InterestRate=@InterestRate)
AND (@LastPaymentDate is null or (CAST(LoanTrfDate AS DATE)=@LoanTrfDate AND CAST(LastPaymentDate AS DATE)=@LastPaymentDate))

to check that at least one parameter was set, you can add this if statement.
if(string.IsNullOrWhiteSpace(LoanTrfDate) && string.IsNullOrWhiteSpace(LastPaymentDate))
{
    throw new Exception("Some clear message here.");
}


text:
Q: combine 3query for s_p select Month(user_lastlogin) as Month,year(user_lastlogin) as Year,
count(*) as 'Total             Reg' from bb_user
group by Month(user_lastlogin),year(user_lastlogin)
order by  Month desc

select count(*) as 'LR Reg' from bb_user
where  user_regtype ='LR'
group by Month(user_lastlogin)
order by  Month desc

select count(*) as 'BBR Reg' from bb_user
where  user_regtype is null OR user_regtype = 'BBR'
group by Month(user_lastlogin)
order by  Month desc

I want to display like
Month/Year/Total Reg/LR Reg/BBR Reg
I am displying result in 3 different query But I want In one Query I want to write stored procedure ....means I want to add 2nd and 3rd query in 1st query .
user_lastlogin = RegistrationDatetime

A: Are you looking for something like this?
SELECT MONTH(user_lastlogin) AS Month,
       YEAR(user_lastlogin) AS Year,
       COUNT(*) AS 'Total Reg',
       SUM(CASE WHEN user_regtype = 'LR' THEN 1 ELSE 0 END) AS 'LR Reg',
       SUM(CASE WHEN IS NULL OR user_regtype = 'BBR' THEN 1 ELSE 0 END) AS 'BBR Reg'
  FROM bb_user
GROUP BY MONTH(user_lastlogin), YEAR(user_lastlogin)
ORDER BY Year DESC, Month DESC

A: Your explanation is very unclear, but i think this is what you want in fact.
select
  Month(user_lastlogin) as Month,
  year(user_lastlogin) as Year,
  count(*) as [Total Reg],
  SUM(CASE WHEN user_regtype ='LR' THEN 1 END) [LR Reg],
  SUM(CASE WHEN user_regtype is null OR user_regtype = 'BBR THEN 1 END) [BBR Reg]
from bb_user
group by
  Month(user_lastlogin),
  year(user_lastlogin)
order by  Month desc


text:
Q: Fail safe iterator - removal during iteration
If fail safe iterator creates a clone of underlying data structure, why 'D' is never printed in program below?

Map<String, String> acMap = new ConcurrentHashMap<String, String>();
acMap.put("A", "Aye");
acMap.put("B", "Bee");
acMap.put("C", "See");
acMap.put("D", "Di");

Iterator<String> itr = acMap.keySet().iterator();
while(itr.hasNext())
{
    acMap.remove("D");
    System.out.println(itr.next());
}

A: As per documentation any operation on map will reflect on keyset and vice versa. And KeySet#iterator() also does not clone the underlying ds.
ConcurrentHashMap#keySet():

Returns a Set view of the keys contained in this map. The set is
  backed by the map, so changes to the map are reflected in the set, and
  vice-versa. The set supports element removal, which removes the
  corresponding mapping from this map, via the Iterator.remove,
  Set.remove, removeAll, retainAll, and clear operations.

Read more documentation
See openjdk Implementation

A: As it says in the Javadoc for keySet():

The iterator ... may (but is not guaranteed to) reflect any modifications subsequent to construction.

Your iterator is reflecting modifications subsequent to construction.


text:
Q: How to change Facebook FanPage "Tab" Icon via Api I know i can have iframe tabs which in fact are apps. And for apps i can set icons.
But, imagine i have a app which is used by many fan pages to make it easier to integrate content.
There must be some dirty trick to set these icons based on the fan-page the app is included. For example http://blog.tabsite.com/post/376/Customize-Your-Fan-Page-Icon-with-TabSite makes exactly that.
Any idea on this ?

A: After a lot of research i have found the way. you have to use the old legacy javascript api with admin.createApplication to create a new application via script, then you can use old rest api (had no luck with the new one) to set the "appProperties" accordingly. like icon, iframe url and so on.

A: it's long time from your discussion and I am sure everyone knows the solution now.. but maybe for new visitors so sad as I was... here is link to new facebook api easily solving this...:
https://developers.facebook.com/docs/reference/api/page/#tabs

A: you can change your tab icon if you are the developer of that certain application that you are using on you tab, you can change that at developer page under your application setting.


text:
Q: What is the official way to Calculate star dates and how can this be done in PHP? This question is written to help me understand how a StarDate is calculated using the method invented by Gene Roddenberry, and how I may implement that method into PHP.
Some methods that I have toyed with (but do not match or come from any official source)
echo date('Ym') . '.' . date('d');  // 1404.13

// 946684800 = 2000-01-01 00:00:00
// End date format, is - 14293.49631
// Accuracy is approximately every 0.33 seconds per tick.
echo floor((((((time() - 946684800)/1000)/60)/5)*0.009513655) * 100000000) / 100000;

I have found several resources online which appear to do calculations, however they are inconsistent.  The Wikipedia entry on this has very little detail on this process.
In the event that the official method is not accurate, I would like some assistance in developing one.  The proposed concept would not stray from the concept of using the century as the first digit, the "season" for the second digit, and use the seconds since that century started as the difference with fractional seconds as the right side decimal portion.
For the official method, I could only find the following links (or similar) aside from wikipedia
http://www.hillschmidt.de/gbr/sternenzeit.htm
http://www.stoacademy.com/tools/stardate.php
http://www.trimboli.name/stardate.html
For the create our own method
A problem I encountered is that a real day according to the earths roation (not solar day), is 24 hours, 56 minutes and 4.1 seconds, and PHP's idea of EPOCH (aka  date('Y', 0); is 1970.
For this to work, the calculations must begin at the year 2000, and take into account the earth's rotation days (so actual day), in seconds/fractions of seconds.
For this method, I would like to know how I can convert the current date, minus 2000 years, and obtain the actual time elapsed according to the time for a full rotation of earth -- not 86,400 seconds/day as that is not accurate.
Thanks in advance.


text:
Q: How do I calculate the correct CGRect origin on a scaled UIView subview? I need to calculate the visible CGRect of a UIView subview, in the coordinates of the original view.  I've got it working if the scale is 1, but if one of the superviews or the view itself is scaled (pinch), the visible CGRect origin is offset slightly.
This works when the scale of the views is 1 or the view is a subview of the root view:
// return the part of the passed view that is visible
// TODO:  figure out why result origin is wrong for scaled subviews
//
- (CGRect)getVisibleRect:(UIView *)view {
    // get the root view controller (and it's view is vc.view)
    UIViewController *vc = UIApplication.sharedApplication.keyWindow.rootViewController;

    // get the view's frame in the root view's coordinate system
    CGRect frame = [vc.view convertRect:view.frame fromView:view.superview];

    // get the intersection of the root view bounds and the passed view frame
    CGRect intersection = CGRectIntersection(vc.view.bounds, frame);

    // adjust the intersection coordinates thru any nested views
    UIView *loopView = view;
    do {
        intersection = [loopView convertRect:intersection fromView:loopView.superview];

        loopView = loopView.superview;
    } while (loopView != vc.view);

    return intersection; // may be same as the original view frame
}

When a subview is scaled, the size of the resultant view is correct, but the origin is offset by a small amount.  It appears that the convertRect does not calculate the origin properly for scaled subviews.
I tried adjusting the origin relative to the X/Y transform scale but I could not get the calculation correct.  Perhaps someone can help?
To save time, here is a complete test ViewController.m, where a box with an X is drawn on the visible part of the views - just create a reset button in the Main.storyboard and connect it to the reset method:
//
//  ViewController.m
//  VisibleViewDemo
//
//  Copyright © 2018 ByteSlinger. All rights reserved.
//

#import "ViewController.h"

CG_INLINE void drawLine(UIView *view,CGPoint point1,CGPoint point2, UIColor *color, NSString *layerName) {
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:point1];
    [path addLineToPoint:point2];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = color.CGColor;
    shapeLayer.lineWidth = 2.0;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.name = layerName;

    [view.layer addSublayer:shapeLayer];
}

CG_INLINE void removeShapeLayers(UIView *view,NSString *layerName) {
    if (view.layer.sublayers.count > 0) {
        for (CALayer *layer in [view.layer.sublayers copy]) {
            if ([layer.name isEqualToString:layerName]) {
                [layer removeFromSuperlayer];
            }
        }
    }
}

CG_INLINE void drawXBox(UIView *view, CGRect rect,UIColor *color) {
    NSString *layerName = @"xbox";

    removeShapeLayers(view, layerName);

    CGPoint topLeft = CGPointMake(rect.origin.x,rect.origin.y);
    CGPoint topRight = CGPointMake(rect.origin.x + rect.size.width,rect.origin.y);
    CGPoint bottomLeft = CGPointMake(rect.origin.x, rect.origin.y + rect.size.height);
    CGPoint bottomRight = CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);

    drawLine(view,topLeft,topRight,color,layerName);
    drawLine(view,topRight,bottomRight,color,layerName);
    drawLine(view,topLeft,bottomLeft,color,layerName);
    drawLine(view,bottomLeft,bottomRight,color,layerName);
    drawLine(view,topLeft,bottomRight,color,layerName);
    drawLine(view,topRight,bottomLeft,color,layerName);
}

@interface ViewController ()

@end

@implementation ViewController

UIView *view1;
UIView *view2;
UIView *view3;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    CGFloat width = [UIScreen mainScreen].bounds.size.width / 2;
    CGFloat height = [UIScreen mainScreen].bounds.size.height / 4;

    view1 = [[UIView alloc] initWithFrame:CGRectMake(width / 2, height / 2, width, height)];
    view1.backgroundColor = UIColor.yellowColor;
    [self.view addSubview:view1];
    [self addGestures:view1];

    view2 = [[UIView alloc] initWithFrame:CGRectMake(width / 2, height / 2 + height + 16, width, height)];
    view2.backgroundColor = UIColor.greenColor;
    [self.view addSubview:view2];
    [self addGestures:view2];

    view3 = [[UIView alloc] initWithFrame:CGRectMake(10, 10, width / 2, height / 2)];
    view3.backgroundColor = [UIColor.blueColor colorWithAlphaComponent:0.5];
    [view1 addSubview:view3];       // this one will behave differently
    [self addGestures:view3];
}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];

    [self checkOnScreen:view1];
    [self checkOnScreen:view2];
    [self checkOnScreen:view3];
}

- (IBAction)reset:(id)sender {
    view1.transform = CGAffineTransformIdentity;
    view2.transform = CGAffineTransformIdentity;
    view3.transform = CGAffineTransformIdentity;

    [self.view setNeedsLayout];
}

- (void)addGestures:(UIView *)view {
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
                                                    initWithTarget:self action:@selector(handlePan:)];
    [view addGestureRecognizer:panGestureRecognizer];

    UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]
                                                        initWithTarget:self action:@selector(handlePinch:)];
    [view addGestureRecognizer:pinchGestureRecognizer];
}

// return the part of the passed view that is visible
- (CGRect)getVisibleRect:(UIView *)view {
    // get the root view controller (and it's view is vc.view)
    UIViewController *vc = UIApplication.sharedApplication.keyWindow.rootViewController;

    // get the view's frame in the root view's coordinate system
    CGRect frame = [vc.view convertRect:view.frame fromView:view.superview];

    // get the intersection of the root view bounds and the passed view frame
    CGRect intersection = CGRectIntersection(vc.view.bounds, frame);

    // adjust the intersection coordinates thru any nested views
    UIView *loopView = view;
    do {
        intersection = [loopView convertRect:intersection fromView:loopView.superview];

        loopView = loopView.superview;
    } while (loopView != vc.view);

    return intersection; // may be same as the original view
}

- (void)checkOnScreen:(UIView *)view {
    CGRect visibleRect = [self getVisibleRect:view];

    if (CGRectEqualToRect(visibleRect, CGRectNull)) {
        visibleRect = CGRectZero;
    }

    drawXBox(view,visibleRect,UIColor.blackColor);
}

//
// Pinch (resize) an image on the ViewController View
//
- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer {
    static CGAffineTransform initialTransform;

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        [self.view bringSubviewToFront:recognizer.view];

        initialTransform = recognizer.view.transform;
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {
    } else {
        recognizer.view.transform = CGAffineTransformScale(initialTransform,recognizer.scale,recognizer.scale);

        [self checkOnScreen:recognizer.view];

        [self.view setNeedsLayout]; // update subviews
    }
}

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
    static CGAffineTransform initialTransform;

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        [self.view bringSubviewToFront:recognizer.view];

        initialTransform = recognizer.view.transform;
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {
    } else {
        //get the translation amount in x,y
        CGPoint translation = [recognizer translationInView:recognizer.view];

        recognizer.view.transform = CGAffineTransformTranslate(initialTransform,translation.x,translation.y);

        [self checkOnScreen:recognizer.view];

        [self.view setNeedsLayout]; // update subviews
    }
}
@end

A: So you need to know the real visible frame of a view that is somehow derived from bounds+center+transform and calculate everything else from that, instead of the ordinary frame value. This means you'll also have to recreate convertRect:fromView: to be based on that. I always sidestepped the problem by using transform only for short animations where such calculations are not necessary. Thinking about coding such a -getVisibleRect: method makes me want to run away screaming ;)
What is a frame?
The frame property is derived from center and bounds.
Example:

*

*center is (60,50)

*bounds is (0,0,100,100)

*=> frame is (10,0,100,100)
Now you change the frame to (10,20,100,100). Because the size of the view did not change, this results only in a change to the center. The new center is now (60,70).
How about transform?
Say you now transform the view, by scaling it to 50%.
=> the view has now half the size than before, while still keeping the same center. It looks like the new frame is (35,45,50,50). However the real result is:

*

*center is still (60,50): this is expected

*bounds is still (0,0,100,100): this should be expected too

*frame is still (10,20,100,100): this is somewhat counterintuitive
frame is a calculated property, and it doesn't care at all about the current transform. This means that the value of the frame is meaningless whenever transform is not the identity transform. This is even documented behaviour. Apple calls the value of frame to be "undefined" in this case.
Consequences
This has the additional consequences that methods such as convertRect:fromView: do not work properly when there are non-standard transforms involved. This is because all these methods rely on either frame or bounds of views, and they break as soon as there are transforms involved.
What can be done?
Say you have three views:

*

*view1 (no transform)

*

*view2 (scale transform 50%)

*

*view3 (no transform)

and you want to know the coordinates of view3 from the point of view of view1.
From the point of view of view2, view3 has frame view3.frame. Easy.
From the point of view of view1, view2 has not frame view2.frame, but the visible frame is a rectangle with size view2.bounds/2 and center view2.center.
To get this right you need some basic linear algebra (with matrix multiplications). (And don't forget the anchorPoint..)
I hope it helps..
What can be done for real?
In your question you said that there is an offset. Maybe you can just calculate the error now? The error should be something like 0.5 * (1-scale) * (bounds.size) . If you can calculate the error, you can subtract it and call it a day :)

A: Thanks to @Michael for putting in so much effort in his answer.  It didn't solve the problem but it made me think some more and try some other things.
And voila, I tried something that I'm certain I had done before, but this time I started with my latest code. It turns out a simple solution did the trick.  The builtin UIView convertRect:fromView and convertRect:toView worked as expected when used together.
I apologize to anyone that has spent time on this.  I'm humbled in my foolishness and how much time I have spent on this.  I must have made a mistake somewhere when I tried this before because it didn't work.  But this works very well now:
// return the part of the passed view that is visible
- (CGRect)getVisibleRect:(UIView *)view {
    // get the root view controller (and it's view is vc.view)
    UIViewController *vc = UIApplication.sharedApplication.keyWindow.rootViewController;

    // get the view's frame in the root view's coordinate system
    CGRect rootRect = [vc.view convertRect:view.frame fromView:view.superview];

    // get the intersection of the root view bounds and the passed view frame
    CGRect rootVisible = CGRectIntersection(vc.view.bounds, rootRect);

    // convert the rect back to the initial view's coordinate system
    CGRect visible = [view convertRect:rootVisible fromView:vc.view];

    return visible; // may be same as the original view frame
}

If someone uses the Viewcontroller.m from my question, just replace the getVisibleRect method with this one and it will work very nicely.
NOTE:  I tried rotating the view and the visible rect is rotated too because I displayed it on the view itself.  I guess I could reverse whatever the view rotation is on the shape layers, but that's for another day!


text:
Q: When do I have to surround with try/catch? I have some piece of code:
public static void a() throws NumberFormatException {
        return;
    }

    public static void b() throws InterruptedException{
        return;
    }

    public static void main(String[] args) {

        a();
        b();

    }

And Eclipse says that I have to surround try/catch to function call b(), but I do not have to do that with a() call. Why? How to make function make to surround with try and catch when is called?

A: Because InterruptedException is a checked exception and NumberFormatException is an unchecked expcetion.
For checked exception, compiler forces you to either surround them with try-catch block or declare them with throws, while for unchecked exceptions try-catch block is not compulsory.
As function a() throws NumberFormatException (unchecked exception) compiler do not force you to surround the function call with try-catch.
As function b() throws InterruptedException (checked exception) compiler forces you to either surround the function call with try-catch or declare them with throws.

A: NumberFormatException is not a checked Exception(i.e because it has java.lang.RuntimeException as its base class), which means that the developer is not forced to handle(its the developer's choice whether to handle it or not) when the developer chooses not to handle the exception and if the exception occurs, it will be handled by the JVM.
Where as InterruptedException (i.e because it has java.lang.Exception as its base class) is a checked exception which means that the developer has to handle it every time either by using a try-catch block or by declaring the exception in the Throws clause.
Take a look at this example.

A: This is because NumberFormatException extends RuntimeException - i.e. it is unchecked exception. While InterruptedException is checked exception - it should be catched in try...catch block, or you should add throws to main() method.

A: because NumberFormatException() is unchecked exception InterruptedException is checked, you have to surroud checked exceptions with try-catch, but you dont have to try-catch checked - every method would have try-catch then.

A: NumberFormatException is a RuntimeException -> unchecked
InterruptedException is a checked Exception
I found the Java Tutorial quite useful to learn about Java and its APIs, and in fact, I still use it from time to time:
http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
http://docs.oracle.com/javase/tutorial/

A: public class InterruptedException
extends Exception
Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception.
but for the first case it will not ask NumberFormatException is an unchecked expcetion.

A: All Exception that extends RuntimeException do not imply an explicit try-catch block. They are called Unchecked. Those exception were theoretically reserved to unrecoverable runtime errors thrown by VM. However they are now commonly used as lot's of people agree to say the Checked exceptions mechanism is a bad design concept.
You will commonly use Unchecked when your program cannot recover from the error and let them propagate to a transverse layer exception handling that will be in charge to properly log and / or display the error to user.
Checked exception are commonly used in cases where the caller will be expected to handle the error, because it is able to recover from it or will trigger specific behavior.

A: The Keyword throws declares that a method may throw that exception. While checked exceptions have to be handled with unchecked exceptions this is optional. In your case a throws a NumberFormatException which is derived from RuntimeException which is according to the definition an unchecked exception, see Section 11.2: Compile-Time Checking of Exceptions:

The unchecked exceptions classes are the class RuntimeException and
  its subclasses, and the class Error and its subclasses. All other
  exception classes are checked exception classes.

And according to the definition the InterruptedException which class b throws is a checked exceptions (must be caught in a try-catch block).

A: There are two ways in Java to handle exceptions -
1. surround try/catch
2. propagate exeption

you use try/catch block if you want to handle this exception locally. Basically, within the try block is a code that has a potential of throwing an exception.
but you use throws SomeException in the method signature if you want this possible exception to be handled by the calling method... this calling method can also propagate this exception further up... should all methods never try/catch this exception, it will be thrown by the Java Virtual Machine at execution time


text:
Q: nginx 1.5+ file upload -- best practices I'm looking to upload files through my nginx server. I'm currently running nginx-1.4.6 and am willing up move to the latest stable nginx-1.5* as necessary.
The community favorite is/was Valery Kholodkov's nginx-upload-module, found here. Regrettably Valery is no longer maintaining this module, details here. As of nginx-1.3.9 the module works partially or not at all.
I've compiled the nginx-upload-module into nginx-1.4.6 and am getting a bug (Client cxn closed) that seems to be fixed in the nginx-1.5.3 changeset. However I've applied the patch and had no luck.
Anatoly's slightly dated post, here, offers multiple solutions, includes four solutions

*

*nginx-upload-module

*nginx-big-upload

*lua-resty-upload

*clientbodyinfileonly
As I dive into the second and fourth solutions (I prefer not to make lua a dependency, but I might) I figured that it's appropriate to ask this community:
What are the current best practices for file uploading with nginx-1.5+?
Let me add that I'm uploading files from a python POST command and trying to test with curl. PHP is not on my tech stack.

A: Maybe you can use perl if you don't like php or lua.
http://nginx.org/en/docs/http/ngx_http_perl_module.html#methods

$r->has_request_body(handler)

But out of the box nginx isn't the tool to save a received post request and store it.
Maybe uWSGI ( https://uwsgi-docs.readthedocs.io/en/latest/ ) is a better way to go with http-socket https://uwsgi-docs.readthedocs.io/en/latest/HTTP.html and a python app.

A: There's a good article about your doubt. https://coderwall.com/p/swgfvw
I tried nginx-upload-module. It's a good solution, but, it seem this doesn't work for new versions.
There's also some modules in Lua that can help you. In my case, i had businness logic then i implemented in my app.
Have in mind, that big problem for upload files is the FILER. This is botleneck: a lot of  load test i had made show me this conclusion.

A: Nginx supports the 'POST' method, where you can use big parameters. The client can use php or jsp to use post method to build the request to the nginx server.

A: I realize this is a very old question, but it's on the first page of google search for "nginx upload module" and it's the first Stack Overflow result, so in case this helps anyone else that comes across this question:
I am using the nginx-upload-module on nginx 1.10.3. As the original question mentions, Valery Kholodkov is no longer maintaining the module. However, there are several different forks and other people have modified it to work with newer nginx versions.
This pull request is what I used in order to compile nginx with the upload module.
https://github.com/vkholodkov/nginx-upload-module/pull/88
The upload module, IMO, is still the best solution out there if you're using nginx and php-fpm. This module allows uploads to be handled completely by nginx until they are complete, and then the job of processing the upload is passed onto PHP. So php-fpm processes won't create a bottleneck when your users are uploading lots of files.

A: Just a quick draft but try this...
Upload.php
if (isset($_FILES['dlc_file']) && !empty($_FILES['dlc_file'])) {
    if (empty($_FILES['dlc_file']['name']) === true) {
        echo = "Please choose a file to upload";
    } else {
        $allowed = array('zip', 'rar', 'gzip', 'tar', '7z', 'png', 'jpg');

        $file_name = $_FILES['dlc_file']['name'];
        $file_extn = strtolower(end(explode('.', $file_name)));
        $file_temp = $_FILES['dlc_file']['tmp_name'];

        if (in_array($file_extn, $allowed) === true) {
            $file_path = 'dlc/' . substr(md5(time()), 0, 10) . '.' . $file_extn;
            move_uploaded_file($file_temp, $file_path);
            echo = "Successfully uploaded $file_name";
        } else {
            $file_types = implode(', ', $allowed);
            echo "File type is not allowed, Allowed file types $file_types";
        }
    }
}

index.php
<form action="upload.php" method="post" enctype="multipart/form-data>
    <input type="file" name="dlc_file">
    <input type="submit" name="submit" value="Upload">
</form>


text:
Q: Crop the image of LaTeX formula How to automatically crop the white space (maximum thickness horizontal/vertical white border) around the formula in image, generated, say, by means of some of online LaTeX formula editors (actually I use EqualX standalone editor)?
For the formula:
n_i =
\begin{vmatrix}
p_1^1  & p_1^2  & \dots  & p_1^{i - 1} & 1      & p_1^{i + 1} & \dots  & p_1^D  \\
p_2^1  & p_2^2  & \dots  & p_2^{i - 1} & 1      & p_2^{i + 1} & \dots  & p_2^D  \\
\vdots & \vdots & \ddots & \vdots      & \vdots & \vdots      & \ddots & \vdots \\
p_D^1  & p_D^2  & \dots  & p_D^{i - 1} & 1      & p_D^{i + 1} & \dots  & p_D^D  \notag
\end{vmatrix}

There is an image created:

I specially add the one-pixel black border at the edge of the image to illustrate, that there is a plenty of extra space, which is possible to cut off.
How to do it automatically (maybe by means of imagemagick utility)? There are a bunch of similar images for one-liner formulas, which I want to inline into html-text.
Are there useful commands, which can I prepend into preamble of document, that allows me to atchieve desired?

A: Use the standalone document class:
MWE
\documentclass[border=2pt]{standalone}
\usepackage{mathtools}
\begin{document}
$
n_i =
\begin{vmatrix}
p_1^1  & p_1^2  & \dots  & p_1^{i - 1} & 1      & p_1^{i + 1} & \dots  & p_1^D  \\
p_2^1  & p_2^2  & \dots  & p_2^{i - 1} & 1      & p_2^{i + 1} & \dots  & p_2^D  \\
\vdots & \vdots & \ddots & \vdots      & \vdots & \vdots      & \ddots & \vdots \\
p_D^1  & p_D^2  & \dots  & p_D^{i - 1} & 1      & p_D^{i + 1} & \dots  & p_D^D  \notag
\end{vmatrix}
$
\end{document}

Output


text:
Q: Monotouch capabilities I am a C# developer who is going to start the development of an iPhone/iPad Application.
My question is very simple: with monotouch, can I do all I can do with standard objectC?

A: Pretty much, yes.  Monotouch updates come out very rapidly after iOS updates, so you have access to new APIs almost immediately.
You can still use third-part objective-c libraries, too: http://monotouch.net/Features#Access_to_third_party_iPhone.2fObjective-C_Libraries
Clearly, this implies that you can still use objective-c in a Monotouch app if you ever find it necessary.


text:
Q: How to avoid overwriting data when creating a list? Selenium Webdriver, Python I want to scrape every page on the following website: https://www.top40.nl/top40/2020/week-34 (for each year and weeknumber) by clicking on the song, then move to 'songinfo' and then scrape all data in the table listed there. For this question, I only scraped the title so far.
This the url I use:
url = 'https://www.top40.nl/top40/'
However, when I print the songs_list, it will only return the last title on the website. As such, I believe I am overwriting.
Hopefully someone can explain me which mistake(s) I am making and if there is any easier way to scrape the table on each page, very happy to hear.
Please find my python code below:
for year in range(2015,2016):
    for week in range(1,2):
        page_url = url+str(year) + '/' + 'week-' + str(week)
        driver.get(page_url)
        lists = driver.find_elements_by_xpath("//a[@data-linktype='title']")

        links = []
        for l in lists:
            print(l.get_attribute('href'))
            links.append(l.get_attribute('href'))

        for link in links:
            driver.get(link)

            driver.find_element_by_xpath("//a[@href='#songinfo']").click()

            songs = driver.find_elements_by_xpath(""".//*[@id="songinfo"]/table/tbody/tr[2]/td""")
            songs_list = []
            for s in songs:
                print(s.get_attribute('innerHTML'))
                songs_list.append(s.get_attribute('innerHTML'))```

A: The line songs_list = [] is inside the for link in links loop, so with each new iteration it gets set to an empty list (and then you append to this new, empty list). Once you end all your loops, you only see the songs_list created.
The simplest fix is to place the songs_list = [] line outside all for loops, ex:
songs_list = []
for year in range(2015,2016):
    for week in range(1,2):
        # etc


text:
Q: Authenticate all API Endpoints in Google App Engine I have the following Google Cloud Endpoints API, and I want it accesible only for authenticated users with certain role.
Few lines of code says much more than a thousand words:
import com.google.appengine.api.users.User;

@Api(
    name = "heroesApi",
    version = "v1",
    clientIds = {...},
    scopes = {...},
    audiences = {...},
    namespace = @ApiNamespace(
        ownerDomain = "my.domain.com",
        ownerName = "my.domain.com",
        packagePath=""
    )
)

public class HeroesApi {

    // THIS IS THE FUNCTION THAT I DON´T KNOW WHERE TO PUT
    /**
     * Validates that the user is logged in with a specific role
     * @param user
     * @throws UnauthorizedException
     * @throws ForbiddenException
     */
    private void validateUser(User user) throws UnauthorizedException, ForbiddenException {
        IUserController userController = ControllerFactory.get.userController();
        if (user == null) {
            throw new ForbiddenException("You must be logged in, my friend.");
        } else if (!userController.isLoggedAsSuperHero(user)) {
            throw new UnauthorizedException("You must be logged in as a Superhero.");
        }
    }

    // API METHODS

    @ApiMethod(path = "something", httpMethod = ApiMethod.HttpMethod.PUT)
    public DoneTask doSomething(Some thing, User superhero) throws UnauthorizedException, ForbiddenException {

        // this is what I want to avoid on each function
        this.validateUser(superhero);

        // Now I'll do something special
        IUserController userController = ControllerFactory.get.userController();
        return userController.doSome(thing);

    }

   // MORE GORGEOUS METHODS JUST FOR SUPERHEROES, SO I HAVE TO PERFORM THE VALIDATION...

}

I have though about adding a filter through the web.xml file for all request to /api/heroesApi/*, but the problem there is how to catch the Google Appengine Api User.
Isn´t there something provided by Google to do this?
Any suggestion to avoid the repeated call to validateUser(User) is welcome

A: Google Cloud Endpoints doesn't supper roles by default , so your application have to build role concept, and you have to write filter and get current user and check against the roles maintained in your end
To get current user in the filter, try this
https://cloud.google.com/appengine/docs/java/oauth/
I haven't tested this , but am sure you can get the current user using the UserService Api in appengine as long as your system uses google account as authentication.


text:
Q: How to keep Divs in place without absolute position I must be misunderstaning something in CSS as my dropdown box using a library (dat-gui) is doing this:

I have tried switching to position: absolute for the divs beneath the dat-gui container, which breaks the divs beneath it.
Funnily enough, when I use the SO embedded snippet, it actually works. So check out an actual deploy of the site at: https://stack-test.netlify.com/

function UI (parentDiv) {
  // parentDiv.querySelector('#dataset_div').style.display = 'none'
  // parentDiv.querySelector('#channel_div').style.display = 'none'
  // parentDiv.querySelector('#OpenCORLinkButton').style.display = 'none'
  // parentDiv.querySelector('#instructions_div').style.display = 'none'
  var _this = this
  _this.dataType = 'scatter'
  const gui = new dat.GUI({autoPlace: false})
  gui.domElement.id = 'gui'
  gui.close()
  document.getElementsByClassName('dat-gui-container')[0].appendChild(gui.domElement)
  var folder = gui.addFolder('Channels')
  var settings = {}
  var checkboxes = []
  var checkboxElements = []

  this.createDatGuiDropdown = function (channels, onchangeFunc) {
    _this.channels = [...channels]
    if (channels[0].toLowerCase().includes('time')){
      channels.shift()
    }
    checkboxes = []
    for (let i in _this.channels) {
      let name = _this.channels[i]
      let checkbox = {}
      checkbox[name] = false
      checkboxes.push(checkbox)
      var el = folder.add(checkboxes[i], name)
      checkboxElements.push(el)
      el.__checkbox.onclick = onchangeFunc
    }
    folder.open()

  }
}

var ui = new UI('unused')
ui.createDatGuiDropdown(['one', 'two'], function(){console.log('clicked')})
/*//////////////////////////////////////////////////////////////////
[ dat-gui ]*/

.dat-gui-container{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 95%;
  z-index: 5;
}

/*//////////////////////////////////////////////////////////////////
[ login ]*/

.limiter {
  width: 100%;
  margin: 0 auto;
}

.container-login100 {
  width: 100%;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  padding: 10px;
  position: relative;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;;
}

.wrap-login100 {
  width: 390px;;
  background: #fff;
  border-radius: 10px;
  position: relative;
}

.wrap-data100 {
  width: 90%;
  background: #fff;
  border-radius: 10px;
  position: relative;
}

/*==================================================================
[ Form ]*/

.login100-form {
  width: 100%;
}

.login100-form-title {
  font-family: Ubuntu-Bold;
  font-size: 30px;
  color: #403866;
  line-height: 1.2;
  text-transform: uppercase;
  text-align: center;

  width: 100%;
  display: block;
}

/*==================================================================
[ Restyle Select2 ]*/

.select2-container {
  display: block;
  max-width: 100% !important;
  width: auto !important;
}

.select2-container .select2-selection--single {
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  align-items: center;
  background-color: rgba(171, 171, 189, 0.233);
  border: none;
  height: 40px;
  outline: none;
  position: relative;
  left: -40px;
}

/*------------------------------------------------------------------
[ in select ]*/
.select2-container .select2-selection--single .select2-selection__rendered {
  font-family: Ubuntu-Bold;
  font-size: 18px;
  color: #555555;
  line-height: 1.2;
  padding-left: 0px ;
  background-color: transparent;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
  height: 100%;
  top: 50%;
  transform: translateY(-50%);
  right: 0px;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.select2-selection__arrow b {
  display: none;
  font-family: Material-Design-Iconic-Font !important;
  font-size: 18px;
  color: #555555;
}

.select2-selection__arrow {
  content: '\f312';
  font-family: Material-Design-Iconic-Font !important;
  font-size: 18px;
  color: #555555;
}

/*------------------------------------------------------------------
[ Dropdown option ]*/
.select2-container--open .select2-dropdown {
  z-index: 1251;
  width: calc(100% + 2px);
  border: 0px solid transparent;
  border-radius: 10px;
  overflow: hidden;
  background-color:  rgba(171, 171, 189, 1);
  left: -40px;

  box-shadow: 0 3px 10px 0px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 0 3px 10px 0px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: 0 3px 10px 0px rgba(0, 0, 0, 0.2);
  -o-box-shadow: 0 3px 10px 0px rgba(0, 0, 0, 0.2);
  -ms-box-shadow: 0 3px 10px 0px rgba(0, 0, 0, 0.2);
}

@media (max-width: 576px) {
  .select2-container--open .select2-dropdown {
    left: -12px;
  }
}

.select2-dropdown--above {top: -38px;}
.select2-dropdown--below {top: 10px;}

.select2-container .select2-results__option[aria-selected] {
  padding-top: 10px;
  padding-bottom: 10px;
  padding-left: 24px;
}

@media (max-width: 576px) {
  .select2-container .select2-results__option[aria-selected] {
    padding-left: 12px;
  }
}

.select2-container .select2-results__option[aria-selected="true"] {
  background: #403866;
  color: white;
}

.select2-container .select2-results__option--highlighted[aria-selected] {
  background: #827ffe;
  color: white;
}

.select2-results__options {
  font-family: Ubuntu-Bold;
  font-size: 14px;
  color: #555555;
  line-height: 1.2;
}

.select2-search--dropdown .select2-search__field {
  border: 1px solid #aaa;
  outline: none;
  font-family: Ubuntu-Bold;
  font-size: 15px;
  color: #333333;
  line-height: 1.2;
}

.wrap-input100 .dropDownSelect2 .select2-container--open {
  width: 100% !important;
}

.wrap-input100 .dropDownSelect2 .select2-dropdown {
  width: calc(100% + 2px) !important;
}

<!DOCTYPE html>

 <title>Blackfynn Exporter</title>
 <meta charset="UTF-8">

     <form class="contact100-form validate-form">

       Data Viewer

        <select class="js-select2" name="service" id="select_channel">
         <option>Channel Selection</option>
        </select>

     </form>

A: If you have a look at the snippet you see that .dat-gui-container has position: absolute set. In your case you have to set position absolute to the element that gets animated, thus preventing the rest of the elements from moving around.


text:
Q: Dynamic gridview - how to reference in rowdatabound I am dynamically creating several gridviews depending on data in a DB.
I generate the gridview as follows in a foreach statement:
GridView gdv = new GridView();
gdv.ID = "gdv" + i.ToString();
gdv.SelectedIndexChanged += new EventHandler(gdv_SelectedIndexChanged);
gdv.RowDataBound += gdv_RowDataBound;

RowDataBound looks like the following:
protected void gdv_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(((GridView)sender), "Select$" + e.Row.RowIndex);
   }
}

This all works as expected, however the ((GridView)sender) returns the following value:
'gdv00'

What i need returned for this link to work is the following:
'ctl00$ctl00$MainContent$Main$gdv0'

Pretty sure this has something to do with the master pages? but not sure how to reference this properly in the rowdatabound event?

A: The ID of ctl00$ctl00$MainContent$Main$gdv is the UniqueID property of the grid control (client ID is separated by _).  This is the ID rendered to the browser.  I think the problem here is that the control isn't added to the control tree immediately, which has been a problem for some in the past.  Try doing it this way:
GridView gdv = new GridView();
gdv.ID = "gdv" + i.ToString();
panel.Controls.Add(gdv);

//set grid props

HTH.


text:
Q: NodeJS Service is not reachable on Kubernete (GCP) I have a true roadblock here and I have not found any solutions so far. Ultimately, my deployed NodeJS + Express server is not reachable when deploying to a Kubernete cluster on GCP. I followed the guide & example, nothing seems to work.
The cluster, node and service are running just fine and don't have any issues. Furthermore, it works just fine locally when running it with Docker.
Here's my Node YAML:
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: 2019-08-06T04:13:29Z
  generation: 1
  labels:
    run: nodejsapp
  name: nodejsapp
  namespace: default
  resourceVersion: "23861"
  selfLink: /apis/apps/v1/namespaces/default/deployments/nodejsapp
  uid: 8b6b7ac5-b800-11e9-816e-42010a9600de
spec:
  progressDeadlineSeconds: 2147483647
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      run: nodejsapp
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nodejsapp
    spec:
      containers:
      - image: gcr.io/${project}/nodejsapp:latest
        imagePullPolicy: Always
        name: nodejsapp
        ports:
        - containerPort: 5000
          protocol: TCP
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 1
  conditions:
  - lastTransitionTime: 2019-08-06T04:13:29Z
    lastUpdateTime: 2019-08-06T04:13:29Z
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  observedGeneration: 1
  readyReplicas: 1
  replicas: 1
  updatedReplicas: 1

Service YAML:
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: 2019-08-06T04:13:34Z
  labels:
    run: nodejsapp
  name: nodejsapp
  namespace: default
  resourceVersion: "25444"
  selfLink: /api/v1/namespaces/default/services/nodejsapp
  uid: 8ef81536-b800-11e9-816e-42010a9600de
spec:
  clusterIP: XXX.XXX.XXX.XXX
  externalTrafficPolicy: Cluster
  ports:
  - nodePort: 32393
    port: 80
    protocol: TCP
    targetPort: 5000
  selector:
    run: nodejsapp
  sessionAffinity: None
  type: LoadBalancer
status:
  loadBalancer:
    ingress:
    - ip: XXX.XXX.XXX.XXX

The NodeJS server is configured to run on Port 5000. I tried doing no port-forwarding as well but not a difference in the result.
Any help is much appreciated.
UPDATE:
I used this guide and followed the instructions: https://cloud.google.com/kubernetes-engine/docs/tutorials/hello-app
UPDATE 2:
FINALLY - figured it out. I'm not sure why this is not mentioned anywhere but you have to create an Ingress that routes the traffic to the pod accordingly.
Here's the example config:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    ingress.kubernetes.io/backends: '{"k8s-be-32064--abfe1f07378017e9":"HEALTHY"}'
    ingress.kubernetes.io/forwarding-rule: k8s-fw-default-nodejsapp--abfe1f07378017e9
    ingress.kubernetes.io/target-proxy: k8s-tp-default-nodejsapp--abfe1f07378017e9
    ingress.kubernetes.io/url-map: k8s-um-default-nodejsapp--abfe1f07378017e9
  creationTimestamp: 2019-08-06T18:59:15Z
  generation: 1
  name: nodejsapp
  namespace: default
  resourceVersion: "171168"
  selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/versapay-api
  uid: 491cd248-b87c-11e9-816e-42010a9600de
spec:
  backend:
    serviceName: nodejsapp
    servicePort: 80
status:
  loadBalancer:
    ingress:
    - ip: XXX.XXX.XXX

A: Adding it as an answer as need to include image (But not necessarily an answer):
As shown in the image, besides your backend service, a green tick should be visible

Probable Solution:
In your NodeJsApp, please add the following base URL .i.e.,
When the application is started locally, http://localhost:5000/ should return a 200 status code (With ideally Server is running... or some message)
And also, if path based routing is enabled, another base URL is also required:
http://localhost:5000/<nodeJsAppUrl>/ should also return 200 status code.
Above URLs are required for health check of both LoadBalancer and Backend Service and redeploy the service.
Please let me know if the above solution doesn't fix the said issue.

A: You need an intermediate service to internally expose your deployment.
Right now, you have a set of pods grouped in a deployment and a load balancer exposed in your cluster but you need to link them with an additional service.
You can try using a NodePort like the following:
apiVersion: v1
kind: Service
metadata:
  name: nodejsapp-nodeport
spec:
  selector:
    run: nodejsapp
  ports:
  - name: default
    protocol: TCP
    port: 32393
    targetPort: 5000
  type: NodePort

This NodePort service is in between your Load Balancer and the pods in your deployment, targeting them in port 5000 and exposing port 32393 (as per your settings in the original question, you can change it).
From here, you can redeploy your Load Balancer to target the previous NodePort. This way, you can reach your NodeJS app via port 80 from your load balancer public address.
apiVersion: v1
kind: Service
metadata:
  name: nodejs-lb
spec:
  selector:
    run: nodejsapp
  ports:
  - name: default
    protocol: TCP
    port: 80
    targetPort: 32393
  type: LoadBalancer

The whole scenario would look like this:
publicy exposed address --> LoadBalancer --> | NodePort --> Deployment --> Pods


text:
Q: Getting the innerHTML of $event in AngularJS i have a html
 with an action listener :

{{ x }}

I would like to pass the value of x to the tableClick() function.
I tried the following (i would like foreignID to take the value of x) :
$scope.tableClick = function(event) {
    var foreignID = event.innerHTML;
};

... but it doesn't seems to work (when i try to display the value of foreignID, i get a "undefined").
How can i do that ?

A: You can just pass x to your function like this:

{{ x }}

$scope.tableClick = function(myVar) {
    var foreignID = myVar;
};

There is no need to get it from the html.


text:
Q: How to apply the lumo theme inside a shadow dom of custom components in Vaadin Flow Is there a recommended way or best practice to apply the css rules of "global" default or custom themes to the shadow root of custom components created with a lit template?
There is a workaround with a connectedCallback to manually apply the theme with an imported "applyTheme()" function. Another description of the issue and the workaroundsee here
I have also found a ticket, with some sort of solution, but i just can't figure out how to use this to solve my issue.
That workaround doesn't seem to work when working with the Vaadin Designer plugin in intellij, as it doesn't seem to be able to use the "applyTheme()" function (unresolved import of "import { applyTheme } from frontend/generated/theme"). Also i'd like to avoid this workaround where possible.
If there is another solution than using the mentioned workaround, does it also work with custom themes / changed values of lumo css properties?
Example:
You create a custom component based on a lit template like this:
import '@vaadin/vaadin-ordered-layout/vaadin-horizontal-layout';
import '@vaadin/vaadin-ordered-layout/vaadin-vertical-layout';
import '@vaadin/vaadin-select';
import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import {applyTheme} from "Frontend/generated/theme";

@customElement('stub-view-card')
export class StubViewCard extends LitElement {
  //commented this, so we DO use a shadow root
  /*createRenderRoot() {
    // Do not use a shadow root
    return this;
  }*/

  connectedCallback() {
    super.connectedCallback();
    // Apply the theme manually because of https://github.com/vaadin/flow/issues/11160
    //this is not needed, if no shadow root like above is used
    applyTheme(this.renderRoot);
  }

  render() {
    return html`

      <slot></slot>

 `;
  }
}

how it should look like
how it looks like without the connectedCallback and applyTheme()
I am using Vaadin 23 and a project generated from vaadin starter. My example was created from the "image list"-template.
I really appreciate any help and documentation that you can point me to :)


text:
Q: Parametric bootstrap testing for random effect in GLMM I am trying to learn GLMM using R. From what I have understood parametric bootstrap is a robust method to know the significance of fixed as well as random effects in the model (http://glmm.wikidot.com/faq). The function PBmodcomp of the R package pbkrtest can be used for testing the significance of the fixed effects.
Similarly how to perform parametric bootstrap testing for random effects in the model. particularly when there are multiple random effects (1|f1) + (1|f2) or random effects terms such as (1 + f1 + f2|id) (id is repeated within f1 and f2)?


text:
Q: AFNetworking 2.0 - mutable json My code currently looks like this
NSURL *URL = [NSURL URLWithString:URLForSend];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                     initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
 {
     NSLog(@"%@", responseObject);
     [BoxJsonDataHelper gotNewJson:responseObject];
 } failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
     NSLog(@"Request Failure Because %@",[error userInfo]);
 }];

[operation start];

But when trying to edit dictionaries in object received, I get an error about using methods that belongs to a mutable dictionary rather than a dictionary.
How do I make AFNetworking use nested mutable objects instead?

A: You tell the AFJSONResponseSerializer that it needs to return mutable containers:
operation.responseSerializer =
  [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers]

It is all very well documented: http://cocoadocs.org/docsets/AFNetworking/2.0.0/


text:
Q: Fourier Sine Series for $f(x) = 1 + x$ on the interval $[0,1]$ I was given the problem to find the Fourier Sine Series for $f(x) = 1 + x $ on the unit interval. I took suggested steps from my lecture but I'm not sure if I did it correctly.
According to my lecture the function has to be odd and also periodic. Therefore I extended it according to the notes: $F:[-1,1]$ $$F(x) = \begin{cases} f(x) & \text{if $0\lt x \leq L$} \\0 & \text{if $x =0 \lor x=L$}\\ -f(-x) & \text{if $-L \leq x \lt 0$} \end{cases}$$ with  $F(x+2L) = F(x)$
which is for functions defined on $[0,L]$. Then since $ L = 1$ my function has the form
$$F(x) = \begin{cases} 1+x & \text{if $0\lt x \leq 1$} \\0 & \text{if $x =0 \lor x=1$}\\ x-1 & \text{if $-1 \leq x \lt 0$} \end{cases}$$
And so I should obtain the Fourier Sine Series : $$\sum_{n=1}^\infty b_nsin(n\pi x) $$  with $b_n =2\int_{0}^1(1+x)sin(n\pi x)dx$ but I think $F(x+2) \neq F(x)$.
Any suggestions as to how I go from here?

A: To make $F$ odd and periodic of period $2$ from $f$ defined on $[0,1],$ you can define:
$$F(x)=\begin{cases}0&x\in\mathbb Z\\
f(x-2m)&x\in (2m,2m+1),\,m\in \mathbb Z \\
-f(2m-x)&x\in(2m-1,2m),\, m\in\mathbb Z
\end{cases}$$
In particular, $F(x)=f(x)$ only on $(0,1),$ not when $x=0$ or $x=1.$ These are necessary to make $F$ odd and period $2.$
$F(0)=0$ is obviously necessary because $$F(0)=F(-0)=-F(0).$$
$F(1)=0$ is necessary for $$F(1)=F(-1+2)=F(-1)=-F(1).$$
So periodicity and oddness require $F(m)=0$ for all integers $m.$
However, you can change $F(0)$ and $F(1)$ because it doesn't affect the integrals.
You can avoid all this work if you know that $F$ only has to satisfy oddness and periodicity "almost everywhere." But that requires some measure theory.

Now, that's a lot of work, but we don't need to do anything with it to compute the coefficients. That's because, as you've noted:
$$b_n =\int_{-1}^1 F(x)\sin n\pi x\,dx=2\int_0^1 f(x)\sin n\pi x\,dx$$
For $f(x)=x+1,$ this integral is easy with integration by parts, with $u=x+1, dv=\sin n\pi x\,dx.$


text:
Q: Count positive, negative or zero values numbers for multiple columns in Python Given a dataset as follows:
[{'id': 1, 'ltp': 2, 'change': nan},
 {'id': 2, 'ltp': 5, 'change': 1.5},
 {'id': 3, 'ltp': 3, 'change': -0.4},
 {'id': 4, 'ltp': 0, 'change': 2.0},
 {'id': 5, 'ltp': 5, 'change': -0.444444},
 {'id': 6, 'ltp': 16, 'change': 2.2}]

Or
   id  ltp    change
0   1    2       NaN
1   2    5  1.500000
2   3    3 -0.400000
3   4    0  2.000000
4   5    5 -0.444444
5   6   16  2.200000

I would like to count the number of positive, negative and 0 values for columns ltp and change, the result may like this:
  columns  positive  negative  zero
0     ltp         5         0     1
1  change         3         2     0

How could I do that with Pandas or Numpy? Thanks.
Updated: if I need groupby type and count following the logic above
   id  ltp    change type
0   1    2       NaN    a
1   2    5  1.500000    a
2   3    3 -0.400000    a
3   4    0  2.000000    b
4   5    5 -0.444444    b
5   6   16  2.200000    b

The expected output:
  type columns  positive  negative  zero
0    a     ltp         3         0     0
1    a  change         1         1     0
2    b     ltp         2         0     1
3    b  change         2         1     0

A: Use np.sign with selected columns first, then counts values in value_counts, transpose, replaced missing values and last rename columns names by dictionary with convert index to column columns:
d= {-1:'negative', 1:'positive', 0:'zero'}
df = (np.sign(df[['ltp','change']])
        .apply(pd.value_counts)
        .T
        .fillna(0)
        .astype(int)
        .rename(columns=d)
        .rename_axis('columns')
        .reset_index())
print (df)
  columns  negative  zero  positive
0     ltp         0     1         5
1  change         2     0         3

EDIT: Another solution with type column with DataFrame.melt, mapping column with np.sign and count values by crosstab:
d= {-1:'negative', 1:'positive', 0:'zero'}

df1 = df.melt(id_vars='type', value_vars=['ltp','change'], var_name='columns')
df1['value'] = np.sign(df1['value']).map(d)
df1 = (pd.crosstab([df1['type'],df1['columns']], df1['value'])
         .rename_axis(columns=None)
         .reset_index())

print (df1)
  type columns  negative  positive  zero
0    a  change         1         1     0
1    a     ltp         0         3     0
2    b  change         1         2     0
3    b     ltp         0         2     1


text:
Q: Rearranging dataframes in r I have a dataframe similar to this
df <- data.frame (month = c("01", "02", "03", "04", "01", "03"),
                  Year= c("01", "01", "01", "01", "02", "02"),
                  value= c("12", "20", "34", "18", "22", "27")
                  )

However I want the columns to be the unique months (ranging from 01-12) and the rows to be years respective values. How do I go about doing this?

A: There are two steps to this: You describe a table, you can make a table from a data frame using a formula with the ?xtabs function.  Unfortunately, I can't get it to use the value column as a 'response'.  So I simply replicated each row the number of times given by the value.  Consider:
(tab <- xtabs(~Year+month, df[rep(1:6, times=df$value),]))
#     month
# Year 01 02 03 04
#   01  1  3  6  2
#   02  4  0  5  0

In your question, you refer to months 1-12, but only 4 are listed in the example.  It isn't clear if you want to be able to add extra columns of 0's as well.  You can use ?cbind to add a matrix of 0's, and then create names with ?colnames.  Consider:
(tab <- cbind(tab, matrix(0, nrow=2, ncol=8)))
#    01 02 03 04
# 01  1  3  6  2 0 0 0 0 0 0 0 0
# 02  4  0  5  0 0 0 0 0 0 0 0 0
colnames(tab) <- c(paste0(0,1:9), "10","11","12")
tab
#    01 02 03 04 05 06 07 08 09 10 11 12
# 01  1  3  6  2  0  0  0  0  0  0  0  0
# 02  4  0  5  0  0  0  0  0  0  0  0  0


text:
Q: on view page load execute controller function, angularjs way Inside angularjs view I want to call controller function. This function shuold be called on page load. Should I follow classic syntax like in asp.net mvc razor view forexample (using ajax) or there is some angularjs specific way to do this?

A: Anything done at page load should be done in the controller itself or in a directive definition, not in the view.


text:
Q: Search Term Finder in Array Here is the code:
import java.util.Scanner;

public class Finder {

public static void main(String[] args) {

    Scanner scnr = new Scanner(System.in);

    String [] names = new String[5];
    String searchTerm = "";

    for (int i = 0; i <= names.length - 1; i++) {
        System.out.print("Enter a name: ");
        names[i] = scnr.next();
    }

    System.out.println();
    System.out.print("Enter a name to search for: ");
    searchTerm = scnr.next();

    for (int i = 0; i <= names.length - 1; i++) {
        if (searchTerm.equals(names[i])) {
            System.out.println(searchTerm + " found!!");
        }
        else {
            System.out.println(searchTerm + " not found!!");
        }
    }

}

}

I am working on the if/else statement in the second for loop and when I add the else part of the statement, it returns:
Enter a name: Luke
Enter a name: Kassy
Enter a name: Chloe
Enter a name: Jon
Enter a name: Jake
Enter a name to search for: Chloe
Chloe not found!!
Chloe not found!!
Chloe found!!
Chloe not found!!
Chloe not found!!
I am not sure why it just doesn't say "Chloe found!!" instead of what it says?

A: With your code now, when you're looping to find the element "Chloe" in the names array, you're going through each element and printing a statement out no matter what. "Chloe" is names[2] but your loop checks names[0] and names[1] first. Since they are not "Chloe", it will print "Chloe not found" (the else part of your if statement). Once it gets to names[2], it will then have found "Chloe" and the if part of your if statement will be executed, printing out "Chloe found". However your loop does not stop there, so the loop will look at names[3] and names[4] and print out "Chloe not found" because none of them equals "Chloe". The simple fix is to only print "Chloe not found" when the loop ends without finding "Chloe" and to only print "Chloe found" when in the middle of the loop, "Chloe" is found. There are many ways to do this but one way I propose is using a boolean variable to check after the loop is done to see if "Chloe" was found or not.
boolean termFound = false;
for (int i = 0; i <= names.length - 1; i++) {
        if (searchTerm.equals(names[i])) {
            System.out.println(searchTerm + " found!!");
            termFound = true;
            break;//if term is found, you can break out of the loop early
        }

}
if(!termFound){ //if searchTerm was not found
        System.out.println(sertTerm + " not found!!");
}


text:
Q: Why is read_line(..) much slower than lines()? The code below runs much slower when calling read_line(..) than lines()
You can't run it in the playground but for me this prints the following
lines()     took Duration { secs: 0, nanos: 41660031 }
read_line() took Duration { secs: 2, nanos: 379397138 }

The implementation of Lines does pretty much what I wrote (but more!) why is there such a difference?
use std::net::{TcpListener, TcpStream};
use std::io::{BufRead, BufReader, Write};
use std::thread;

fn main() {

    let listener = TcpListener::bind("127.0.0.1:80")
        .expect("listen failed");
    thread::spawn(move || {
        for stream in listener.incoming() {
            let mut stream = stream.unwrap();
            thread::spawn(move || {
                for x in 1..1000 + 1 {
                    stream.write_all(format!("{}\n", x).as_bytes())
                        .expect("write failed");
                }
            });
        }
    });

    let start_a = std::time::Instant::now();
    {
        let stream_a = TcpStream::connect("127.0.0.1:80")
            .expect("connect_a failed");
        let br = BufReader::new(stream_a);
        for l in br.lines() {
            println!("{}", l.unwrap());
        }
    }
    let end_a = std::time::Instant::now();

    let start_b = std::time::Instant::now();
    {
        let stream_b = TcpStream::connect("127.0.0.1:80")
            .expect("connect_b failed");
        let mut br = BufReader::new(stream_b);
        let mut s = String::with_capacity(10);
        while br.read_line(&mut s).unwrap_or(0) > 0 {
            println!("{}", s);
        }
    }
    let end_b = std::time::Instant::now();

    let dur_a = end_a - start_a;
    let dur_b = end_b - start_b;

    println!("lines()     took {:?}", dur_a);
    println!("read_line() took {:?}", dur_b);

}

same code on the playground

A: Let's take a look at the output of your program:
1
2
...
999
1000
1

1
2

1
2
3

1
2
3
4

1
2
3
4
5

...

Ooops. It's just a simple bug in your code: you never clear() the string. Each read_line() call appends to your string. When I add a s.clear() in your while loop, the timings are more comparable:
lines()     took Duration { secs: 0, nanos: 7323617 }
read_line() took Duration { secs: 0, nanos: 2877078 }

In your buggy program, most of the time was probably wasted reallocating the string and printing it to the terminal.


text:
Q: Positioning Text in an image filled png How does one position the text in a pdf using  UIGraphicsBeginPDFContextToData or  UIGraphicsBeginPDFContextToFile ?
I want to have an image with positioned text and stored as a pdf.
How does one do the positioning and the layout for pdfs.

A: Search for the drawInRect-methods in the documentation. UIImage has one and NSString has some variants of this method, that allow you to select a font, alignment etc. These draw in the created PDF graphics context.
The positioning is done with the origin coordinates of the given CGRect.


text:
Q: Shared memory C++ Read and Write synchronisation Will the shared memory be corrupted if two programs access it simultaneously, one writing into it and the other one reading from it?
I have two programs, one will get some data from servers and web and save parsed data into the shared memory, and i have a read program, that will read until the last saved data set.
For example, if the first program has collected data from 100 servers and is currently in the 101th server, all the data until the 100th server will be read by the reader program. Once 101th is finished, then reader program will read the 101th data set.
Here data set from a server may have multiple data, like disk space, load etc.
So does this kind of access corrupt the data in the shared memory? Or is it ok the way i do it?

A: Is there a reason you're doing this with processes instead of threads? That might make your life harder from a synchronization perspective.
If you were working with threads I would tell you to protect your accesses with a semaphore so that you can guarantee that the reader is not reading the same data set that the writer is writing; I believe that implementations of semaphores and other synchronization primitives exist for inter-process shared memory as well but that's a little less common.
The reason you should definitely be using someone else's synchronization primitives is that on modern hardware, writes can be reordered or delayed e.g. the first program is "currently in the 101st server" but in actuality the writes to the data for the 100th server are not yet written back from the CPU. A semaphore or mutex will include the appropriate memory fencing instructions to flush writes so that memory looks consistent from other threads/processes; you should absolutely use someone else's carefully written implementation rather than write your own synchronization logic.
Also, when you are testing it is very important that you test on a multiprocessor machine, as race conditions between processes are much less likely to appear on a uniprocessor box.

A: What you have described is actually a common computing problem in concurrency called Readers-writers
If you try to read from the memory while other program is writing to it, you will most likely get corrupted data. You should use one of synchronization primitives (locks, semaphores, monitors...) to ensure this situation will never happen.
I recommend you to have a look at The Little Book of Semaphores, especially chapter 4.2 Readers-writers problem.


text:
Q: Move Word Table Row Without Using Clipboard I have a table in Word and I need to move certain rows to the bottom of the table using VBA.
I know I can do this by cutting and pasting (myTable.Rows(2).Select ... Selection.Cut ... etc.) but I don't want to have to use the clipboard.
Although I can manually highlight the row and drag it using the mouse, when I record a macro, the drag is not allowed and there does not seem to be any obvious menu instruction to carry out the equivalent.
The only other thing I can think of doing is (using VBA):

*

*Add a new row at the bottom

*Replicate the data in the new row from the one to be moved

*Delete the original row

A "sexier" solution to this must be out there ;)

A: Here are two things you could explore:
Use FormattedText:
Sub moverow4table1toend()
Dim source As Word.Range
Dim target As Word.Range
Dim t As Word.Table
Set t = ActiveDocument.Tables(1)
Set target = t.Range
target.Collapse wdCollapseEnd
Set source = t.Rows(4).Range
target.FormattedText = source.FormattedText
source.Rows(1).Delete
Set source = Nothing
Set target = Nothing
Set t = Nothing
End Sub

Or perhaps if you are actually doing something more like sorting, you could add a column (assuming you haven't reached the limit, populate it with the destination row numbers, sort the table, and remove the column.


text:
Q: Cloudfront caching with optional query parameters I'm trying to setup cloud front to cache our images, these images can accept a query param called size. The requests look something like these:

*

*/images/cat?size=large

*/images/cat?size=medium

*/images/cat?size=small

*/images/cat
Notice how the size parameter is optional and the server knows that in this case return the large version.
The problem is that setting the Cache Key Settings to use size as a key (like in the screenshot) works fine for the top three versions with the size parameter. But no caching happens at all if that parameter isn't there (which is the one that needs caching the most).
I'm not sure how to set this up to make everything cache properly. I have a hacky idea involving setting up one behaviour for /images/* that caches on size and another behaviour for /images/*.png that doesn't cache on any parameters (2 behaviours because the paths need to be unique). But this solution feels subpar.
Thank you for your help

A: For anyone in the same situation here is what I discovered.
I attempted to do as described in the last paragraph with two overlapping behaviours, one with caching on size and one not. This approach seems to work fine so far. I will edit if I discover any pitfalls.


text:
Q: I Have this error (NameError: name 'raw_input' is not defined) My program keeps showing this error raw_input is not defined whenever I use raw_input:
import urllib
from bs4 import BeautifulSoup
url = raw_input('http://py4e-data.dr-chuck.net/known_by_Eqlaas.html: ')
count = int(raw_input("Enter count: "))
position = int(raw_input("Enter position:"))
for i in range(count):
    html = urllib.urlopen(url).read()
    soup = BeautifulSoup(html)

    tags = soup('a')
    s = []
    t = []
    for tag in tags:
        x = tag.get('href', None)
        s.append(x)
        y = tag.text
        t.append(y)

    print (s[position-1])
    print (t[position-1])
    url = s[position-1]

A: Starting with Python 3, raw_input() was renamed to input().

A: Since you are using python3, you have to replace
count = int(raw_input("Enter count: "))
position = int(raw_input("Enter position:"))

with
count = int(input("Enter count: "))
position = int(input("Enter position:"))