Choosing a VS project type (C++)

Question: I do not use C++ much (I try to stick to the easier stuff like Java and VB.NET), but the lately I have not had a choice.  When I am picking a project type in VS for some C++ source I download, what project type should I pick?  I had just been sticking with Win32 Console Applications, but I just downloaded some code (below) that will not work right even when it compiles with out errors.  I have tried to use a CLR Console Application and an empty project too, and have changed many variables along the way, but I cannot get this code to work.  I noticed that this code does not have "int main()" at its beginning, does that have something to do with it?  Anyways, here is the code, got it from here:
/* Demo of modified Lucas-Kanade optical flow algorithm.
   See the printf below */

#ifdef _CH_
#pragma package <opencv>
#endif

#ifndef _EiC
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <ctype.h>
#endif

#include <windows.h>

#define FULL_IMAGE_AS_OUTPUT_FILE

#define cvMirror cvFlip

//IplImage *image = 0, *grey = 0, *prev_grey = 0, *pyramid = 0, *prev_pyramid = 0, *swap_temp;
IplImage **buf = 0;
IplImage *image1 = 0;
IplImage *imageCopy=0;

IplImage *image = 0;
int win_size = 10;
const int MAX_COUNT = 500;
CvPoint2D32f* points[2] = {0,0}, *swap_points;
char* status = 0;
//int count = 0;
//int need_to_init = 0;
//int night_mode = 0;
int flags = 0;
//int add_remove_pt = 0;
bool bLButtonDown = false;
//bool bstopLoop = false;
CvPoint pt, pt1,pt2;
//IplImage* img1;
FILE* FileDest;

char* strImageDir = "E:\\Projects\\TSCreator\\Images";
char* strItemName = "b";
int  imageCount=0;
int bFirstFace = 1;     // flag for first face
int mode = 1; // Mode 1 - Haar Traing Sample Creation, 2 - HMM sample creation, Mode = 3 - Both Harr and HMM.
//int startImgeNo = 1;
bool isEqualRation = false; //Weidth to height ratio is equal

//Selected Image data
IplImage *selectedImage = 0;
int selectedX = 0, selectedY = 0, currentImageNo = 0, selectedWidth = 0, selectedHeight= 0;
CvRect selectedROI;

void saveFroHarrTraining(IplImage *src, int x, int y, int width, int height, int imageCount);
void saveForHMMTraining(IplImage *src, CvRect roi,int imageCount);

// Code for draw  ROI Cropping Image
void on_mouse( int event, int x, int y, int flags, void* param )
{

char f[200];
CvRect reg;

         if( !image )
            return;

    if( event == CV_EVENT_LBUTTONDOWN )
    {
        bLButtonDown = true;

        pt1.x = x;
        pt1.y = y;

    }
    else if ( event == CV_EVENT_MOUSEMOVE ) //Draw the selected area rectangle
    {
        pt2.x = x;
        pt2.y = y;

        if(bLButtonDown)
        {
            if( !image1 )
        {
            /* allocate all the buffers */
            image1 = cvCreateImage( cvGetSize(image), 8, 3 );
            image1->origin = image->origin;
            points[0] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0]));
            points[1] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0]));
            status = (char*)cvAlloc(MAX_COUNT);
            flags = 0;
        }

        cvCopy( image, image1, 0 );

        //Equal Weight-Height Ratio
            if(isEqualRation)
            {
                pt2.y = pt1.y + (pt2.x-pt1.x);
            }

            //Max Height and Width is the image width and height
            if(pt2.x>image->width)
            {
                pt2.x = image->width;
            }
            if(pt2.y>image->height)
            {
                pt2.y = image->height;
            }

            CvPoint InnerPt1 = pt1;
            CvPoint InnerPt2 = pt2;

            if ( InnerPt1.x > InnerPt2.x)
            {
                int tempX = InnerPt1.x;
                InnerPt1.x = InnerPt2.x;
                InnerPt2.x = tempX;
            }

            if ( pt2.y < InnerPt1.y )
            {
                int tempY = InnerPt1.y;
                InnerPt1.y = InnerPt2.y;
                InnerPt2.y = tempY;

            }

            InnerPt1.y = image->height - InnerPt1.y;
            InnerPt2.y = image->height - InnerPt2.y;

            CvFont font;
            double hScale=1.0;
            double vScale=1.0;
            int    lineWidth=1;
            cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,lineWidth);

            char size [200];
            reg.x = pt1.x;
            reg.y = image->height - pt2.y;
            reg.height = abs (pt2.y - pt1.y);
            reg.width = InnerPt2.x -InnerPt1.x;
            //print width and heght of the selected reagion
            sprintf(size, "(%dx%d)",reg.width, reg.height);
            cvPutText (image1,size,cvPoint(10,10), &font, cvScalar(255,255,0));
            cvRectangle(image1, InnerPt1, InnerPt2, CV_RGB(255,0,0), 1);

            //Mark Selected Reagion
            selectedImage = image;
            selectedX = pt1.x;
            selectedY = pt1.y;
            selectedWidth = reg.width;
            selectedHeight = reg.height;
            selectedROI  = reg;

            //Show the modified image
            cvShowImage("HMM-Harr Positive Image Creator",image1);
        }

    }
    else if ( event == CV_EVENT_LBUTTONUP )
    {
        bLButtonDown = false;

//      pt2.x = x;
//      pt2.y = y;
//
//      if ( pt1.x > pt2.x)
//      {
//          int tempX = pt1.x;
//          pt1.x = pt2.x;
//          pt2.x = tempX;
//      }
//
//      if ( pt2.y < pt1.y )
//      {
//          int tempY = pt1.y;
//          pt1.y = pt2.y;
//          pt2.y = tempY;
//
//      }
//
//reg.x = pt1.x;
//reg.y = image->height - pt2.y;
//
//reg.height = abs (pt2.y - pt1.y);
////reg.width = reg.height/3;
//reg.width = pt2.x -pt1.x;
////reg.height = (2 * reg.width)/3;

#ifdef FULL_IMAGE_AS_OUTPUT_FILE
        CvRect FullImageRect;
        FullImageRect.x = 0;
        FullImageRect.y = 0;
        FullImageRect.width = image->width;
        FullImageRect.height = image->height;

        IplImage *regionFullImage =0;
        regionFullImage = cvCreateImage(cvSize (FullImageRect.width, FullImageRect.height),
                                    image->depth, image->nChannels);

        image->roi = NULL;

        //cvSetImageROI (image, FullImageRect);
        //cvCopy (image, regionFullImage, 0);

#else
         IplImage *region =0;
         region = cvCreateImage(cvSize (reg.width, reg.height),
                                image1->depth, image1->nChannels);

        image->roi = NULL;
        cvSetImageROI (image1, reg);

        cvCopy (image1, region, 0);
#endif
        //cvNamedWindow("Result", CV_WINDOW_AUTOSIZE);

        //selectedImage = image;
        //selectedX = pt1.x;
        //selectedY = pt1.y;
        //selectedWidth = reg.width;
        //selectedHeight = reg.height;
        ////currentImageNo = startImgeNo;
        //selectedROI  = reg;

        /*if(mode == 1)
        {
            saveFroHarrTraining(image,pt1.x,pt1.y,reg.width,reg.height,startImgeNo);
        }
        else if(mode == 2)
        {
            saveForHMMTraining(image,reg,startImgeNo);
        }
        else if(mode ==3)
        {
            saveFroHarrTraining(image,pt1.x,pt1.y,reg.width,reg.height,startImgeNo);
            saveForHMMTraining(image,reg,startImgeNo);
        }
        else
        {
            printf("Invalid mode.");
        }

        startImgeNo++;*/

    }
}

/*
Save popsitive samples for Harr Training.
Also add an entry to the PositiveSample.txt with the location of the item of interest.
*/
void saveFroHarrTraining(IplImage *src, int x, int y, int width, int height, int imageCount)
{
    char f[255] ;
        sprintf(f,"%s\\%s\\harr_%s%d%d.jpg",strImageDir,strItemName,strItemName,imageCount/10, imageCount%10);

        cvNamedWindow("Harr", CV_WINDOW_AUTOSIZE);
        cvShowImage("Harr", src);
        cvSaveImage(f, src);

        printf("output%d%d \t ", imageCount/10, imageCount%10);
        printf("width %d \t", width);
        printf("height %d \t", height);
        printf("x1 %d \t", x);
        printf("y1 %d \t\n", y);

        char f1[255];
        sprintf(f1,"%s\\PositiveSample.txt",strImageDir);
        FileDest = fopen(f1, "a");
        fprintf(FileDest, "%s\\harr_%s%d.jpg 1 %d %d %d %d  \n",strItemName,strItemName, imageCount, x, y, width, height);
        fclose(FileDest);
}

/*
Create Sample Images for HMM recognition algorythm trai ning.
*/
void saveForHMMTraining(IplImage *src, CvRect roi,int imageCount)
{
    char f[255] ;
    printf("x=%d, y=%d, w= %d, h= %d\n",roi.x,roi.y,roi.width,roi.height);
    //Create the file name
    sprintf(f,"%s\\%s\\hmm_%s%d.pgm",strImageDir,strItemName,strItemName, imageCount);

    //Create storage for grayscale image
    IplImage* gray = cvCreateImage(cvSize(roi.width,roi.height), 8, 1);
    //Create storage for croped reagon
    IplImage* regionFullImage = cvCreateImage(cvSize(roi.width,roi.height),8,3);
    //Croped marked region
    cvSetImageROI(src,roi);
    cvCopy(src,regionFullImage);
    cvResetImageROI(src);
    //Flip croped image - otherwise it will saved upside down
    cvConvertImage(regionFullImage, regionFullImage, CV_CVTIMG_FLIP);
    //Convert croped image to gray scale
    cvCvtColor(regionFullImage,gray, CV_BGR2GRAY);
    //Show final grayscale image
    cvNamedWindow("HMM", CV_WINDOW_AUTOSIZE);
    cvShowImage("HMM", gray);
    //Save final grayscale image
    cvSaveImage(f, gray);
}

int maina( int argc, char** argv )
{
    CvCapture* capture = 0;
    //if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))
    //    capture = cvCaptureFromCAM( argc == 2 ? argv[1][0] - '0' : 0 );
    //else if( argc == 2 )
    //    capture = cvCaptureFromAVI( argv[1] );

    char* video;

    if(argc ==7)
    {
        mode = atoi(argv[1]);
        strImageDir = argv[2];
        strItemName = argv[3];
        video = argv[4];
        currentImageNo = atoi(argv[5]);
        int a = atoi(argv[6]);
        if(a==1)
        {
            isEqualRation = true;
        }
        else
        {
            isEqualRation = false;
        }

    }
    else
    {
        printf("\nUsage: TSCreator.exe <Mode> <Sample Image Save Path> <Sample Image Save Directory> <Video File Location> <Start Image No> <Is Equal Ratio>\n");
        printf("Mode = 1 - Haar Traing Sample Creation. \nMode = 2 - HMM sample creation.\nMode = 3 - Both Harr and HMM\n");
        printf("Is Equal Ratio = 0 or 1. 1 - Equal weidth and height, 0 - custom.");
        printf("Note: You have to create the image save directory in correct path first.\n");
        printf("Eg: TSCreator.exe 1 E:\Projects\TSCreator\Images A 11.avi 1 1\n\n");
        return 0;
    }
      capture = cvCaptureFromAVI(video);

    if( !capture )
    {
        fprintf(stderr,"Could not initialize capturing...\n");
        return -1;
    }

    cvNamedWindow("HMM-Harr Positive Image Creator", CV_WINDOW_AUTOSIZE);
    cvSetMouseCallback("HMM-Harr Positive Image Creator", on_mouse, 0);
    //cvShowImage("Test", image1);

    for(;;)
    {
        IplImage* frame = 0;
        int i, k, c;

        frame = cvQueryFrame( capture );
        if( !frame )
            break;

        if( !image )
        {
            /* allocate all the buffers */
            image = cvCreateImage( cvGetSize(frame), 8, 3 );
            image->origin = frame->origin;
            //grey = cvCreateImage( cvGetSize(frame), 8, 1 );
            //prev_grey = cvCreateImage( cvGetSize(frame), 8, 1 );
            //pyramid = cvCreateImage( cvGetSize(frame), 8, 1 );
           // prev_pyramid = cvCreateImage( cvGetSize(frame), 8, 1 );
            points[0] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0]));
            points[1] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0]));
            status = (char*)cvAlloc(MAX_COUNT);
            flags = 0;
        }

        cvCopy( frame, image, 0 );
       // cvCvtColor( image, grey, CV_BGR2GRAY );

        cvShowImage("HMM-Harr Positive Image Creator", image);
        cvSetMouseCallback("HMM-Harr Positive Image Creator", on_mouse, 0);
         c = cvWaitKey(0);
         if((char)c == 's')
         {
            //Save selected reagion as training data
             if(selectedImage)
             {
                 printf("Selected Reagion Saved\n");
                if(mode == 1)
                {
                    saveFroHarrTraining(selectedImage,selectedX,selectedY,selectedWidth,selectedHeight,currentImageNo);
                }
                else if(mode == 2)
                {
                    saveForHMMTraining(selectedImage,selectedROI,currentImageNo);
                }
                else if(mode ==3)
                {
                    saveFroHarrTraining(selectedImage,selectedX,selectedY,selectedWidth,selectedHeight,currentImageNo);
                    saveForHMMTraining(selectedImage,selectedROI,currentImageNo);
                }
                else
                {
                    printf("Invalid mode.");
                }
                currentImageNo++;
             }

         }

    }

    cvReleaseCapture( &capture );
    //cvDestroyWindow("HMM-Harr Positive Image Creator");
    cvDestroyAllWindows();

    return 0;
}

#ifdef _EiC
main(1,"lkdemo.c");
#endif

If I put...
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

... before the previous code (and link it to the correct OpenCV .lib files) it compiles without errors, but does nothing at the command line.  How do I make it work?
Answer: Try using New Project -> Visual C++ -> Win32 -> Win32 Console Application. You can take all the defaults to get a new .cpp file for the project, which will have a _tmain in it. Modify _tmain like this:
int maina( int argc, char** argv ); // add this

int _tmain(int argc, _TCHAR* argv[])
{
    return maina(argc, argv); // call maina from here
}

and then set the project Properties -> Configuration Properties -> General -> Character Set from the default of "Use Unicode Character Set" to "Use Multi-Byte Character Set". (Until you change this, you'll get a compiler error on passing the _TCHAR*[] as a char**.)
Then just add your source file to the project unmodified, and see if you can get it to compile and link. Then run it from a console window without any args to see if you get those five prints worth of "Usage: ..." output.
(As I re-read your question I see you are using Win32 Console Application, so in this case it may just be Unicode vs. Multi-Byte Character Set that is giving you trouble.)
(Taking the defaults for a new project, you'll also need to select the added, existing source file, go to Properties -> Configuration Properties -> C/C++ -> Precompiled Headers -> Create/Use Precompiled Headers and set it to Not Using Precompiled Headers.)
Comment: You sir are the man.  Just a note though, it worked with and without precompiled headers.  Since I am a C++ noob (and a programming noob in general) can you explain a few things to me?  1.) How can I know when to change the character set, precompiled headers, common language runtime support, ect?  2.) Win32 vs CLR, what is the difference and which should I pick by default?  3.)  Do you think the person that developed the source code that I posted intended for a person to have to do this?  I would have assumed such code would be posted SSCCE style...  Thanks again!
Comment: Using Multi-Byte was just a guess. If you see wchar_t instead of char, it's probably using Unicode. Google "_MBCS _UNICODE" to find lots of related info.

You should never need precompiled headers to get it to work -- they are just there to speed up the compiles. I can't think of an example scenario, but they can get out of sync -- when in doubt, rebuild the whole project to regenerate them.

You'll need CLR only if the C++ is using .NET, AFAIK. In that case, the C++/CLI syntax should stand out, e.g. String^ myString.
Answer: When your c++ application starts, it searches for an
int main(int argc, char** argv)

function. However, in windows, this can take the form of
int _tmain(int argc, _TCHAR* argv[])

You can safely assume that both are equivalent, just written differently. When the application starts, it loads your _tmain, then returns 0, so you don't see any output, this is normal.
What you need is to rename int maina(...) to int _tmain(...)

Choosing a VS project type (C++)


Using file_get_contents for multiple sites with same content

Question: I want to grab a code from some websites (all of them have the same content but some of them have downtime).
So i want to make a code that checks the first site and if the code was found show it, if not check the second site etc.
The code that i have is this:
<code>$website1 = file_get_contents("http://exemplesite1.com");
preg_match("' src=\"(.*?)\" type='si", $website1, $body);
$decoded_url = $body[1];

if ( $decoded_url == "" ) {
$website2 = file_get_contents("http://exemplesite2.com");
preg_match("' src=\"(.*?)\" type='si", $website2, $body);
$decoded_url2 = $body[1];
} elseif ...
</code>
Here i'm blocked, i have like 6 sites, i want to do this untill it finds the code i need.
Comment: You need to learn about loops...
Answer: Put the websites in an array, and loop through that. Assuming you only need the first one, you can exit the loop upon finding a match. Something like this:
<code>$websites = ['http://exemplesite1.com', 'http://exemplesite2.com', ...];

foreach($websites as $website) {
    preg_match("' src=\"(.*?)\" type='si", $website, $body);
    $decoded_url = $body[1];

    if (! empty($decoded_url)) //found proper match
    break;
}
</code>


Support for virtual IPMI in a VM?

Question: This might be a silly question, but... Is there any hypervisor or other virtualization solution which supports a "virtual IPMI" for virtual machines? I.e. would allow access to something that looks like power control, a serial-over-LAN console, etc. to a virtual machine.
This is really not the right way for managing virtual machines, I know. I'm looking for this because we make heavy use of IPMI for systems management and it would be interesting/useful to integrate VMs into the same framework, and because it'd be useful to have such an interface when I use VMs as a dev environment for systems management tools.
Comment: It would definitely depend on the virtualization environment you're using.  A partitioning system like FreeBSD's "jails" or Solaris Zones/Containers or Linux vserver would not allow something like this to occur because they don't provide hardware virtualization, but a commercial product like VMWare might.  Ask your vendor, perhaps?
Comment: What's the meaning of `it'd be useful to have such an interface when I use VMs as a dev environment for systems management tools.`?
Answer: I can't find reference to any hypervisor which implements IPMI, but there is some talk about implementing this in libvirt and qemu.
Comment: Thanks, @mgorven. It's good to know someone else is thinking about this, even if it doesn't exist yet...
Answer: These days, such a beast does exist for libvirt, called VirtualBMC.
Answer: I have something like this in place in RHEV 3, where the VM's power management is easily done via a small script, and VNC/Spice and a serial console are available. Not IPMI as such, but the functionality is right there
EDIT: there is a fence-rhev agent available as well, so that would cover the power management part

Support for virtual IPMI in a VM?


Is there a compelling reason to track sites.php with version control?

Question: I'm wondering if sites.php is a file that should be tracked?  I can see it being useful because domains tend not to change for any given site (not true for development, as I usually run a shortname.local site alias for ease).  But then again, if you're not tracking the actual site folder, then the site folder name could vary from installation to installation potentially, making tracking sites.php potentially a useless cause...
I don't know, I guess I'm looking for guidance here.  Typically I do not track the sites folder because it contains generated site files and sensitive database information, so maybe it doesn't make sense to track sites.php?
Looking for some tips from the seasoned pros out there.
Answer: We track it. You can have more than one entry in sites.php that points to the same site, so we have one for the production site and then a few more for development purposes.
The file is not sensitive itself, because if you give someone the ability to read the contents of .php files on your webserver, then you have bigger problems! I'd say try and find reasons NOT to keep it under version control.
I have to say Gisle's suggestion of manually logging changes to files seems to be a bit more effort than I'd normally want to put in, to get round a problem that's not really a problem for me to begin with!
Answer: I do not track the sites folder with version control (more or less for the same reasons you give).  However, I have a manually kept log where I keep track of any permanent configuration changes I do to the site, including the sites folder and sites.php. It is not much extra work to keep such a log, and I've found this log more useful than version control because it only contains essential information while when I relied on an automatically generated log, it exposed a lot of short-lived tests and experiments that I no longer care about.
So I do not see a compelling reason to track sites.php with version control.  What I do track (with git) below the sites folder is of course the custom themes/subthemes and custom modules that I maintain myself.


ASP.Net Datalist with linked DataSourceId does not reload

Question: I have a MultiView control which has a View in which a DataList is filled like this:
<asp:DataList ID="DataList6" runat="server" DataSourceID="SqlDataSource11" Width="100%">
<ItemTemplate>

</ItemTemplate>
</asp:DataList>

The problem is that when I switch to another view of the MultiView control, to edit the content of this DataList and go back after saving the data, the data is not refreshed.
I have checked the database and I am certain that the data has changed.
How should I solve this?
Answer: Try DataList6.DataBind


Table do PrimeNG não aparece

Question: Saudação galera. Estou tentando usar a Table do PrimeNG, mas estou com dificuldades. Segui os passos na Get Started e a Table não aparece no navegador. E para piorar, não consta nenhum erro no console do navegado e nem do código.
package.json

{
  "name": "comercial-ui",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^7.2.15",
    "@angular/cdk": "^7.2.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "font-awesome": "^4.7.0",
    "primeflex": "^1.0.0-rc.1",
    "primeicons": "^1.0.0",
    "primeng": "^8.0.1",
    "rxjs": "~6.3.3",
    "rxjs-compat": "^6.5.2",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.12.0",
    "@angular/cli": "~7.2.1",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }
}

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "comercial-ui": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/comercial-ui",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "node_modules/primeflex/primeflex.css",
              "node_modules/primeicons/primeicons.css",
              "node_modules/primeng/resources/themes/nova-light/theme.css",
              "node_modules/primeng/resources/primeng.min.css",
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "comercial-ui:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "comercial-ui:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "comercial-ui:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "comercial-ui-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "comercial-ui:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "comercial-ui:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "comercial-ui"
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { TableModule } from 'primeng/table';
import { MultiSelectModule } from 'primeng/multiselect';

import { AppComponent } from './app.component';
import { PainelNegociacaoComponent } from './painel-negociacao/painel-negociacao.component';

@NgModule({
  declarations: [
    AppComponent,
    PainelNegociacaoComponent,
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    HttpClientModule,
    TableModule,
    MultiSelectModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

oportunidade.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class OportunidadeService {

  apiUrl = 'http://localhost:8080/oportunidades';

  constructor(private httpClient: HttpClient) { }

  listar(){
    return this.httpClient.get(this.apiUrl);
  }

}

painel.negociacao.component.ts

import { Component, OnInit } from '@angular/core';
import { OportunidadeService } from '../oportunidade.service';

@Component({
  selector: 'app-painel-negociacao',
  templateUrl: './painel-negociacao.component.html',
  styleUrls: ['./painel-negociacao.component.css']
})
export class PainelNegociacaoComponent implements OnInit {

  oportunidades = [];

  constructor(private oportunidadeService: OportunidadeService) { }

  ngOnInit() {
    this.oportunidadeService.listar().subscribe(resposta => this.oportunidades = <any> resposta);
  }

}

painel-negociacao.component.html

    <ng-template pTemplete="header">

            Descrição
            Prospecto
            Valor

    </ng-template>
    <ng-template value="body" let-oportunidade>

            {{oportunidade.descricao}}
            {{oportunidade.nomeProspecto}}
            {{oportunidade.valor}}

    </ng-template>

app.component.html

<app-painel-negociacao></app-painel-negociacao>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

}
Answer: Seu painel-navegacaoComponent.html apresenta alguns erros de digitação:
mude:
<ng-template pTemplete="header">

para:
<ng-template pTemplate="header">

e:
<ng-template value="body" let-oportunidade>

para:
<ng-template pTemplate="body" let-oportunidade>

Comment: João, obrigado!

Table do PrimeNG não aparece


PCA on few variables with high correlation?

Question: This is my first question here, so im sorry if the information seems messy.
I have a dataset with 4 variables and 25 observations. I want to do a regression where Var1 is explained by Var2, Var3 and Var4.
Var2 and Var3 have 0,97 correlation
Var2 and Var4 have 0,48 correlation
Var3 and Var4 have 0,50 correlation
Here I have an issue with multicollinearity between Var2 and Var3. Im considering using PCA to remove this issue, but Im not sure if you can do this with this few variables.
It should be mentioned that in this regression, Var4 has a very high p-value.
Should I use PCA on all three variables, or just on Var2 and Var3 keeping var4 outside?
Could another solution be to drop one of the correlating variables (var2 or var3)?
This may be an unrelated question to the topic, but when Var4 has such a high p-value, and make minimal difference on R-squared, should it be omitted anyways?
Thanks in advance.
Answer: Sounds like you've got this problem:
\begin{eqnarray}
\mathrm{var_1} &=& y\\
\langle \mathrm{var_2,var_3,var_4} \rangle &=& \vec{x}
\end{eqnarray}
You're data matrix isn't very large, just 25 x 3:
\begin{eqnarray}
X &=& \left( \begin{array}{c} \vec{x}_1 \\ \vec{x}_2 \\ \dots \\ \vec{x}_{25}\end{array}\right)
\end{eqnarray}
with a covariance matrix something like this:
\begin{eqnarray}
\rho_{ij} = \Sigma_{ij}/\Sigma_{ii}&=& \left( \begin{array}{c} 1 & .97 & .48 \\ .97 & 1 & .5 \\ .48 & .5 & 1\end{array}\right)
\end{eqnarray}
If the first two components of your predicting variables -- $var_2$ and $var_3$ -- are so correlated, you've got a couple choices:

Regularize the regression -- Ridge Regression -- with an L1 or L2 norm. (The L1, or "LASSO", will probably just choose between $var_2$ and $var_3$ if sufficiently strong).
Do PCA, as you said, and regress on the resulting features (should make it 3 or less) but you'll probably get similar results as to the option above, with a lot more complexity. The features -- and regression coefficients $\vec{\beta}$ -- will no longer be interpretable.
Just drop $var_2$ or $var_3$, based on which one has less incremental benefit --
reduction in $\chi^2$ or RSS -- after fitting a model with only $var_4$, then ($var_2$, $var_4$) vs. ($var_3$, $var_4$)
Comment: Thanks for answering. Regarding choice nr3: is it correct to keep Var_4 even if its p-value is very high and it does not add anything to R-squared (RSS) in both cases (meaning only using either var_2 or var_3 in the regression)?. Regarding choice nr2: should PCA be done including all three variables?
Comment: I agree with rspeare's answer. To answer your additional question, if you have a theoretical reason to include var_4 in the model, then keep it in the model. Removing it because the p-value is > .05 is accepting the null (i.e., you are accepting that the true B is 0).


Django: CSRF verification failed. Request aborted

Question: The called view function is like this
def parsing(request):
    url = request.POST['url']
    ...
    return HttpResponse(json.dumps(resultDict))

When I make a post request to it via the following code,
import requests
url = 'http://tv.cntv.cn/video/C12278/a7ea7c0e810b4701bf1d3f5254b8a26a'
c = requests.post("http://127.0.0.1:8000/VideoParser/", data={'url': url})
print(c.text)

then the request failed and it just give out the following HTML code,

<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="robots" content="NONE,NOARCHIVE">
  <title>403 Forbidden</title>

Forbidden (403)

CSRF verification failed. Request aborted.

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.

Help

Reason given for failure:

    CSRF cookie not set.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when
  Django's
  CSRF mechanism has not been used correctly.  For POST forms, you need to
  ensure:

Your browser is accepting cookies.

The view function passes a request to the template's render
    method.

In the template, there is a {% csrf_token
    %} template tag inside each POST form that
    targets an internal URL.

If you are not using CsrfViewMiddleware, then you must use
    csrf_protect on any views that use the csrf_token
    template tag, as well as those that accept the POST data.

You're seeing the help section of this page because you have DEBUG =
  True in your Django settings file. Change that to False,
  and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

It seems reason given for failure is
CSRF cookie not set.
however, my app doesn't involve any cookie and template explicitly during the whole process, anyone can help fix the problem ? I am just a beginning Django learner .
Comment: Just a simple `csrf_exempt` decorator will do the job. See my answer below.
Answer: You can use csrf_exempt decorator for your view:
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def parsing(request):
    url = request.POST['url']
    ...
    return HttpResponse(json.dumps(resultDict))

From the docs:

This decorator marks a view as being exempt from the protection
  ensured by the middleware.

You can read more about csrf protection here
Answer: You are using a POST request, which is protected again CSRF's attacks by requesting a token.
You can read more about CSRF tokens at Django docs :  https://docs.djangoproject.com/en/1.9/ref/csrf/
Answer: Just remove "django.middleware.csrf.CsrfViewMiddleware" from MIDDLEWARE_CLASSES in your settings.py
Comment: I believe removing `django.middleware.csrf.CsrfViewMiddleware` from middlewares is not wise. This is what `csrf_exempt` decorator stands for.
Answer: You have two option fro this problem
First:-
If you want to use csrf authentication you must need to add cookie in every request coming from the front end for that you need to add following sniipet in your front end code
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

and pass this csrftoken in your Ajax call or angular service as a header.
Second :-
And if your getting cross-header error so if it is denying your request to django server then just do pip install django-cors-headers and modify settings.py with
INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)

Hope so it ill help you !!


Integrating Drupal into an existing site to manage comments

Question: I am involved in a project that wishes to post a wide range of products, and allows users to review these products. I don't want to use Drupal for the design, layout, etc. I am only interested in using Drupal for managing all of the user generated reviews. Is this integration possible, or recommended?
Could anyone please point me in the right direction for more information about the subject?
Answer: Though this is an old question, and it probably depends on what your project is using other than Drupal, from what I hear there are some decent "hybrid" CMS options out there.
You can combine Drupal with NodeJS or AngularJS.
Since you said you don't want Drupal for the design, that is called "headless/decoupled Drupal".
Here is some more information: Headless Drupal: The What, Why and How


Custom placeholder markup when leveraging #lazy_builder in elements

Question: Using bigpipe.
To avoid blocking page loads for long-lasting API calls, etc, I implement:
<code>$element = [
  '#lazy_builder' => ['service.admin:method', []],
  '#create_placeholder' => TRUE,
];
</code>
and it works great! The page loads, and once the service returns the render array, it gets popped into the placeholder.
However, the placeholder span is empty and does not provide the user with any useful status. My goal is to have the empty placeholder replaced with a message (i.e. 'Loading data..'). This is proving more difficult than I assumed - I feel like I must be missing something.
My first crack was manually defining the placeholder:
<code>$element = [
  '#markup' => 'Loading data..',
  '#attached' => [
    'placeholders' => [
      'Loading data..' => [
        '#lazy_builder' => ['service.admin:method', []],
      ],
    ],
  ],
];
</code>
This generates the desired content, but blocks any elements further down of it from loading until the method returns - pausing with half the page rendered. I assume it pushes the lazy_builder into the render process where it isn't as useful for this purpose.
I skimmed through core and couldn't glean any examples of this.
Is there an easy way to add text to the placeholder? This cannot be a novel need.
Warm Regards.
Answer: I know this is an old question, but for anyone who stumbles upon it via a search engine (like I did), then the answer is that as of right now, you can't provide custom placeholder markup, but there is a Drupal.org issue with patches that adds this functionality, so it's possible that the feature will eventually be available in the Big Pipe module without a patch.


Can someone please explain this symbol?

Question: I'm trying to learn this piece that is called "Waltz in A minor" and I don't know to play that little symbol.
Comment: May be way off the case here, but that looks very much like the playback position indicator from a bit of software that is playing back the piece on MIDI. Is this a printed score in a book, or a PDF someone has sent you?
Comment: _which_ symbol?
Comment: Listen to several recordings and it will show itself - or not.
Comment: By any chance, do you mean the tiny notes at the start of the more complete measure?
Answer: (I assume you mean the gray triangle with the vertical line; the two smaller notes at the beginning of the bar are grace notes.)
Googling for sheet music for "Waltz in A minor" yields a couple of results like this one from pianotv.net. None of them have such a symbol at the end of the third bar (or anywhere else) so I guess Steve Mansfield's hunch is right: it's just a software artifact, indicating the current position. It might not even be your software if somebody took a screenshot and sent it to you.

Can someone please explain this symbol?


Is the mapping from a Schatten-class compact operator to its spectrum continuous?

Question: On an infinite dimensional Hilbert space, let $S_p$ be the Banach space of compact operators that are $p$ Schatten class. Since for $A\in S_p$ its spectrum $\sigma(A)$ is at most countably infinite, we can naturally consider it as an element of the Banach space $\ell_p$
Is the mapping from an operator to its spectrum $\sigma: S_p \to \ell_p$ continuous for any $p\in [1,\infty]$? This is true for finite-dimensional Hilbert spaces but I'm wondering how it generalizes.
In particular, what if we restrict things to the subspace of $S_p$ consisting of self-adjoint operators?
Comment: Suppose $1, 2, i+1$ are the eigenvalues of some operator $A$. So, do you map it to $(1, 2, i+1)$ or $(2, 1, i+1)$ or $(i+1, 2, 1)$...? All I wanted to say is that $\ell_p$ has ordering but the spectrum does have a natural order. Maybe the easiest might be to consider the ordering by the magnitude of the eigenvalues. Of course, in the end it doesn't really matter when it comes to the continuity since all of these ordering are unitarily equivalent.
Comment: So, what is the map $\sigma:S_p\rightarrow \ell_p$? Can you be more specific (even in the finite-dimensional case)? Is it basis dependent?
Comment: $\sigma$ maps an operator to its spectrum and is basis-independent. I rewrote the question to be more explicit.
Comment: Ah I see what you meant now. For concreteness, we'll order for the eigenvalues by decreasing absolute value.
Comment: Then what is the difficulty? Is it obvious then?
Comment: I'm not sure what you mean. The only thing I can think is that since finite rank operators are dense in $S_p$, $\sigma$ being uniformly continuous for finite dimensions would give us the desired result. But that fact isn't obvious to me.
Answer: This is less of an answer and more of a related result that came to mind: Lemma 5 in Chapter XI.9 of the Dunford & Schwartz classic "Linear operators. Part II. Spectral theory" reads

Let $T_n,T$ be compact operators, and let $T_n\to T$ in the uniform operator topology. Let $\lambda_m(T)$ be an enumeration of the non-zero eigenvalues of $T$, each repeated according to its multiplicity. Then there exist enumerations $\lambda_m(T_n)$ of the non-zero eigenvalues of $T_n$, with repetitions according to multiplicity, such that
$$
\lim_{n\to\infty}\lambda_m(T_n)=\lambda_m(T),\qquad m\geq 1,
$$
the limit being uniform in $m$.

Once the spectral mapping $\sigma:\mathcal K(\mathcal H)\to\ell^\infty(\mathbb N)$ (resp. the restriction to some Schatten class) is well-defined${}^1$ this result may allow to generalize the result from finite dimensions to the general setting.

 ${}^1$: In a comment you specified that $\sigma$ shall order the eigenvalues of the input decreasingly according to its absolute value, but this leaves room for problems. For example if the input has eigenvalues $i$, $-i$ then $\sigma$ fails to give a unique ordering to them. Of course this problem vanishes for the simpler special case of self-adjoint operators you mentioned in your post; so you may want to try to rigorously formulate and prove that result first and then try to "make sense" of the case of arbitrary input operators.


Clique longo com JavaScript

Question: No Android existe o método OnLongClickListener no qual é possível manter pressionado o dedo em uma View e é disparada uma ação (se o desenvolvedor definir uma ação) caso esse clique permaneça um pouco mais de 1 segundo.
Tenho essa pequena tabela abaixo com 4 cores. No JavaScript qual seria melhor forma de fazer esta ação do "clique longo" ao manter o cursor pressionado em alguma cor? Por exemplo exibir um alert com a cor pressionada.

     black = "#000000"

     green = "#008000"

     silver = "#C0C0C0"

     lime = "#00FF00"

Answer: Você pode utilizar setTimeout() do JavaScript.

var timer;

$("td").mouseup(function(){
  clearTimeout(timer);
  // Limpa o timeout
  return false;
}).mousedown(function(){
  var elemento = this;
  // Seta o timeout
  timer = window.setTimeout(function() {
    // Funciona para  que definiu a propriedade backgroundColor
    console.log("Clique longo ativado. Cor do background: " + elemento.style.backgroundColor);
  }, 1000);
  return false;
});

      black = "#000000"

      green = "#008000"

      silver = "#C0C0C0"

      lime = "#00FF00"

Comment: @acklay atualizei a resposta. Se clicar e segurar em ` `, você quer que logue `black`, correto?
Comment: Nessa mesma linha de raciocino, é possível logar o nome da cor do item ´pressionado ?
Comment: @acklay por nome da cor você quer dizer o valor da propriedade `background-color`?
Comment: O valor de cada item ao segurar o cursor em cima.
Answer: Uma modificação para o código proposto acima seria criar o evento longclick
var timer;

$("td").mouseup(function(){
  clearTimeout(timer);
  // Limpa o timeout
  return false;
}).mousedown(function(){
  // Seta o timeout
  var clickedItem = this;
  timer = window.setTimeout(function() { $(clickedItem).trigger('longClick'); }, 1000);
  return false;
});
$("td").on('longClick', longClickCallback);

var timer;

$("td").mouseup(function(){
  clearTimeout(timer);
  // Limpa o timeout
  return false;
}).mousedown(function(){
  // Seta o timeout
  timer = window.setTimeout(function() { console.log("Clique longo ativado."); }, 1000);
  return false;
});

      black = "#000000"

      green = "#008000"

      silver = "#C0C0C0"

      lime = "#00FF00"

Clique longo com JavaScript


Como carregar uma Imagem em uma UITableView?

Question: Realizei uma requisição que me retornou alguns textos e umas urls com imagens, estas imagens eu preciso carrega-las juntamente com o texto  em paralelo na tabela.
Estou utilizando Alamofire + AlamofireImage para carregar os textos/Imagens, minha duvida e a seguinte, eu devo realizar o processo de insercao destes elementos na celula da tabela pelo método cellForRowAtIndexPath ?  por que este evento é disparado quando e iniciado e quando eu percorro pela tabela, com isto as imagens acabam duplicando.
Exemplo:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
    print("Evento acontece")
    if self.verifyUrl(self.texto[indexPath.row]){

        Alamofire.request(.GET, self.texto[indexPath.row])
            .responseImage { response in

                if let image = response.result.value {
                    let size = CGSize(width: 300.00, height: 130.0)
                    let aspectScaledToFillImage = image.af_imageScaledToSize(size)
                    cell.imageView?.image = aspectScaledToFillImage
                }
        }

    }else{

        cell.textLabel?.text = self.texto[indexPath.row]
    }

    return cell
}

Repare que alem de mal alinhada fica um texto bem a direita dela, alem disso abaixo e carregado as mesmas imagens.
Answer: Vamos por etapa:

eu devo realizar o processo de insercao destes elementos na celula da
  tabela pelo método cellForRowAtIndexPath?

A maioria dos lugares em que encontramos códigos sobre UITableView usam o método tableView:cellForRowAtIndexPath: para preencher os dados da tabela quando na verdade este método deveria retorna uma célula reusável o mais rápido possível.
Mas onde devo preencher os dados da minha célula? Resposta: No método tableView:willDisplayCell:forRowAtIndexPath: pois como diz a documentação esse método é chamado antes da célula (que já foi criada no cellForRowAtIndexPath) ser desenhada e mostrada na tela.

Estou utilizando Alamofire + AlamofireImage para carregar os
  textos/Imagens

Para carregar o conteúdo do textos aconselho você usar os métodos iniciais da sua ViewController usando um Array para guardar o conteúdo retornado dentro do closure do Alamofire.request para preencher o seu array e dar um tableView.reloadData() assim os dados estariam prontos na hora de formatar a célula.
Quanto as imagens: usando o AlamofireImage você carrega as imagens de forma assíncrona usando o método  af_setImageWithURL(url)
No final seria mais ou menos assim que ficaria:
if self.verifyUrl(self.texto[indexPath.row]){
   cell.imageView?.af_setImageWithURL(NSURL(string: self.texto[indexPath.row])!)
   // outras configurações da imagem....
}else{
   cell.textLabel?.text = self.texto[indexPath.row]
}

Repare que alem de mal alinhada fica um texto bem a direita dela, alem
  disso abaixo e carregado as mesmas imagens.

Isso bem provável(digamos 99,99%) é a configuração da sua célula no storyboard especificamente seus constraints. Tente dar uma olhada nessa outra questão aqui do pt.stackoverflow pois pode te ajudar nessa parte.
Comment: No meu ViewController tem uma fun chamada loadPosts que retorna os jsons, esses jsons eu coloco no array texto. vou fazer os testes mudando para willdisplaycell, quanto ao alinhamento as configurações estão conforme o seu post, até por que foi eu quem fiz a pergunta :)
Comment: Ah é nem tinha visto , os jsons que você fala é o objeto depois do parse do json? Se tiver um desenho de como você quer mais ou menos a cell eu posso te ajudar com os constraints
Comment: Um exemplo da forma que estou carregando: https://github.com/Gabrielr47/tableWithImage
Comment: Vou dar uma olhada e fazer um `pull request` depois.
Comment: Fiz o pull request. Dê uma olhada pois abrange tudo isso que escrevi na resposta.
Comment: Fiz o pull e to testando/Adaptando para a minha necessidade, assim que tiver ok marco como aceita valeu.


Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?

Question: I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?
>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true

Comment: You should remember, that `a.fill()` creates a single instance of its argument and does not copy it (object-like behavior). So, every element of `a` is the same exact object.
Comment: This question appears literally dozens of times for each language on SO.
Answer: var a = Array(100).fill(Array(100).fill(false));

a contains an array, each element of which references to an array. you are filling the outer array with an array which contains all false values. The inner array is being made only once and reference to the same array is passed to each element of outer array that is why if you perform an operation on one element it reflects on other elements as well.
This is actually equivalent to
var a1 = Array(100).fill(false);
var a = Array(100).fill(a1);

here a gets 100 elements all having reference to same array a1. So if you change one element of a, all elements change since they are references to same array.
you will need to fill each element in outer array with a new array. you can do something like this:
var a = [];
for(var i=0; i<100; i++)
  a.push(Array(100).fill(false));

Answer: Your entire array will be filled with references to the same (second dimension) array object.
To fill it with distinct objects, you'd have to do something like this:

const a = Array(100).fill(false).map(x => Array(100).fill(false));

a[0][0] = true;

console.log(a[0][0]);
console.log(a[0][1]);
console.log(a[1][1]);

Note that the values in the initial array need to be explicitly set to something (in my example false, but could also be undefined), because the array created by the constructor is sparse and the map() function will only operate on properties that actually exist.
To work around that, you could use Array.from():

const a = Array.from(Array(100), x => Array(100).fill(false));

a[0][0] = true;

console.log(a[0][0]);
console.log(a[0][1]);
console.log(a[1][1]);
Answer: Your problem is that you are using the second Array(100).fill(false) in every position of the first array. Thats why when you change one value in the "second" dimension it will change in every single position of the array. If you want to avoid this you hve to create a new Array for each position of the initial.
var x = Array(100).fill().map(x => Array(100).fill(false));

Comment: Will not work. The `map()` function will not operate on the undefined properties of a sparse array.
Comment: Forgot to fill the initial array
Answer: what you are doing here is adding the same array object at each index of bigger array.
So when you do
Array(x).fill(Array(y).fill(false));

What you are doing actually is :
Array(x).fill(Y); // i.e. X.fill(Y)

Now whenever you change Y, you will get the same value at each index of X.
You should use loop to fill in data when data itself is an object(remember Array is object).
Answer: These looks like a duplicate question but I've always just used something like this
var x = new Array(10);
for (var i = 0; i < 10; i++) {
  x[i] = new Array(10).fill(false);
}
x[5][5] = true

Credit: How can I create a two dimensional array in JavaScript?
Answer: Since arrays are reference types, creating an N Dimensional array in JS is not so trivial. You need to create a clone tool first.

Array.prototype.clone = function(){
  return this.map(e => Array.isArray(e) ? e.clone() : e);
};

function arrayND(...n){
  return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
}

var arr = arrayND(2,3,4,"x")
console.log(JSON.stringify(arr));

arrayND takes indefinite number of integer arguments each designating the size of a dimension and the last argument is the fill value.
Answer: The fill function as described in mdn, copies the same value to all array indices. You can use the below utility to create clones of the array. But since i am using the slice operator, this is restricted to cloning arrays.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
   if (!Array.prototype.clonefill) {
  Object.defineProperty(Array.prototype, 'clonefill', {
    value: function(value) {

      // Steps 1-2.
      if (this == null) {
        throw new TypeError('this is null or not defined');
      }

      var O = Object(this);

      // Steps 3-5.
      var len = O.length >>> 0;

      // Steps 6-7.
      var start = arguments[1];
      var relativeStart = start >> 0;

      // Step 8.
      var k = relativeStart < 0 ?
        Math.max(len + relativeStart, 0) :
        Math.min(relativeStart, len);

      // Steps 9-10.
      var end = arguments[2];
      var relativeEnd = end === undefined ?
        len : end >> 0;

      // Step 11.
      var final = relativeEnd < 0 ?
        Math.max(len + relativeEnd, 0) :
        Math.min(relativeEnd, len);

      // Step 12.
      while (k < final) {
        O[k] = value.slice(0);
        k++;
      }

      // Step 13.
      return O;
    }
  });
}
Array(100).clonefill(Array(100))
a[0][0] = true
a[1][0]
false


Objectify in App Engine+Endpoint+GCM Backend. Children & parent

Question: I create my "App Engine Backend with Google Cloud Messaging" Template, like this one
Then i make my entety class Employee. And entety class Manager.
<code> @Entity

public class Employee {

    @Id
    Long id;
    @Index
    private String regId;

    @Index
    private String email;

    /*
    @Index
    @Load
    Ref <Manager> managerRef;
    */

    @Index
    @Parent
    Key <Manager> managerKey;

    public Employee (){};

    public void setRelationKey(Key<Manager> managerKey){
    this.managerKey = managerKey;
    }

    public Key<Manager> getRelationKey(){
        return managerKey;

    }

    public Long getId(){
        return id;
    }

    public String getRegId() {
        return regId;
    }

    public void setRegId(String regId) {
        this.regId = regId;
    }

    public String getEmail() {
        return email;
    }

    public void setEmai(String email) {
        this.email = email;
    }

}
</code>
For work with data it use objectify. So wont groups of employee whith header manager. I put
<code> `@Index
    @Parent
    Key <Manager> managerKey;`
</code>
in Emplyee. Then i Generate Cloud Endpoint from java class: EmployeeEndpoint and ManagerEndpoint
Then Build -> Deploy Modul to AppEngine
And give BUILD FAILED
FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':backend:appengineEndpointsGetClientLibs'.

There was an error running endpoints command get-client-lib: Parameterized type com.googlecode.objectify.Key
  < com.example.Operator.myapplication.backend.Manager> not supported.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
My hope for your help.
Answer: I found solution from this
You will have to annotate your methods with @ApiResourceProperty and set its ignored attribute to true as illustrated in the code below:
<code> @Entity

public class Employee {

    /** */
    /*
    public static Key<Employee> key(long id) {
        return Key.create(Employee.class, id);
    }
    */
    @Parent
    Key<ManagerManager> managerKey;
    @Id
    Long id;
    @Index
    private String regId;

    @Index
    private String email;

    /*
    @Index
    @Load
    Ref <Manager> managerRef;
    */

    public Employee (){};

    @ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
    public void setRelationKey(Key<ManagerManager> managerKey){
    this.managerKey = managerKey;
    }

    @ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
    public Key<ManagerManager> getRelationKey(){
        return managerKey;
   ....
</code>
And it BUILD SUCCESSFUL


Angular multipart form data upload webapi 404

Question: I'm trying to upload a file from AngularJS to ASP.NET WebAPI. For some reason, it is being rejected by WebAPI with a 404 status code. Here's the code:
Angular JS:
function upload(file, assessmentId, progressCallback) {
    var formData = new FormData();
    formData.append('file', file, file.name);
    formData.append('assessmentId', assessmentId);

    // post the file
    return $http({
        data: formData,
        headers: { 'Content-Type': undefined },
        method: 'POST',
        url: _api('api/video/upload')
    });
}

Also tried:
function upload(file, assessmentId, progressCallback) {
    var formData = new FormData();
    formData.append('file', file, file.name);
    formData.append('assessmentId', assessmentId);

    return $http.post(_api('api/video/upload'), formData, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    });
}

C# WebApi:
[HttpPost]
[Route("api/video/upload")]
public async Task<IHttpActionResult> Upload()
{
    if (!Request.Content.IsMimeMultipartContent("form-data"))
        return StatusCode(HttpStatusCode.UnsupportedMediaType);

    /* do stuff */

    return Ok(new { test = "ing" });
}

If I comment out formData.append('file', file, file.name); so only appending the assessmentId, WebApi accepts the request.
file is from the HTML file upload control: element[0].files[0]. I wonder if that's where the error is?
Another thing to note is in the Chrome Developer Tools Console, after the 404 POST error, there's a CORS error on the same request. I've seen this occur before when WebApi fails, but I don't think there is actually a CORS error because it works when I exclude the file from the request.
Update
The plot thickens. It works fine with small files (a few MB). If I upload a 27MB file, I get a 500 error stating "Maximum request length exceeded". Great! Getting somewhere. But if I upload a 56MB file, I get the 404 status code. What's going on here?
With the following config, the 27MB file works, but the 56MB file still returns 404.
<location path="api/video/upload">
    <system.web>
        <httpRuntime executionTimeout="86400" maxRequestLength="4194304" />
    </system.web>
</location>

Comment: Have you tried using file-upload directives of AngularJs
Comment: @RohanKawade no, but I've used this same code elsewhere (with Angular Audio Recorder) and it works fine.
Comment: @RohanKawade However I'm using a directive derived from [here](https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs) to bind the input element.
Answer: Ok, with fresh eyes, I've reach the cause. There are yet more config settings to limit the request size in ASP.NET. The code in the OP is fine. This configuration is required (4GB limit):
<location path="api/video/upload">
    <system.web>
        <httpRuntime executionTimeout="86400" maxRequestLength="4194303" />
    </system.web>
    <system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="4294967295" />
            </requestFiltering>
        </security>
    </system.webServer>
</location>

And for the sake of this answer being a full solution, here's the code again:
Angular JS Service Operation:
upload: function (file, assessmentId, progressCallback) {
    var formData = new FormData();
    formData.append('file', file, file.name);
    formData.append('assessmentId', assessmentId);

    // post the file
    return $http({
        data: formData,
        headers: { 'Content-Type': undefined },
        method: 'POST',
        url: _api('api/video/upload')
    });
}

WebApi Action:
[HttpPost]
[Route("api/video/upload")]
public async Task<IHttpActionResult> Upload()
{
    if (!Request.Content.IsMimeMultipartContent("form-data"))
        return StatusCode(HttpStatusCode.UnsupportedMediaType);

    /* do stuff */

    return Ok(new { test = "ing" });
}

WebAPI web.config:
<location path="api/video/upload">
    <system.web>
        <httpRuntime executionTimeout="86400" maxRequestLength="4194303" />
    </system.web>
    <system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="4294967295" />
            </requestFiltering>
        </security>
    </system.webServer>
</location>


How to establish a video call programmatically via UCMA 2.0?

Question: I am trying to establish a video call with with UCMA 2.0. But, I always end up with establishing an audio call.
I found that default value of the DefaultMediaType property of the AudioVideoCall is MediaType.Audio.
Sample code is:
<code>_call = new AudioVideoCall (_conversation);
_call.DefaultMediaType = MediaType.Video;

call.BeginEstablish(_yourSipUri, null , CallEstablishCompleted, _call);
</code>
Do you guys know the right way to establish a video call between users with UCMA 2.0 and OCS 2007 R2?
Answer: UCMA doesn't support this, for a number of reasons. The primary being that there isn't anything UCMA can do with the video stream. Unlike text and audio, UCMA cannot do any recognition against video and it cannot generate any video.
UCMA can recognize what you speak or type, and it can generate text or audio (using Text-to-Speech) responses. Video is very different, it cannot recognize images and it couldn't generate any video responses. While the technology exists to do these things, they are far beyond the scope of what UCMA can handle.
Another important thing to remember is that not all callers have video support, and even fewer have a camera with the quality required to do recognition. Video is still very expensive to work with (both computationally and in bandwidth). I expect you won't see support for it until systems like Kinect (with high-quality cameras and built in recognition capabilities) become commonplace.
You didn't mention what the goal of this was so I'll make a small assumption that you're looking for a way to initiate a video call between two parties programmatically. If this is the case, what you really want here is the Communicator 2007 (of Lync 2010) SDK. This is an SDK for automating the communicator client itself.
Communication 2007 SDK: http://www.microsoft.com/download/en/details.aspx?id=10176
Lync 2010 SDK: http://www.microsoft.com/download/en/details.aspx?id=18898
Comment: Yes, you make the right guess and I did it with Communicator 2007 SDK. Thanks for the tip.


Prove that $(-1)x = -x$

Question: My question is a proof in a vector-spaces chapter in an undergraduate book. I have tried using the existence of additive identity but that hasn't worked.
Comment: What have you tried?
Answer: If $x$ is any vector in a vector space $V$, then
$0=0x=(1-1)x=1x+(-1)x=x+(-1)x$
which follows that $(-1)x=-x$

Note:  For $0=0x$
$0x=(0+0)x=0x+0x$ adding $-0x$ both side we get $0x=0$
Answer: Since\begin{align}x+(-1)\times x&=1\times x+(-1)\times x\\&=\bigl((1+(-1)\bigr)\times x\\&=0\times x\\&=0,\end{align}you have that $(-1)\times x=-x$. Of course, now you have to prove that $0\times x=0$.

Prove that $(-1)x = -x$


Addition statements along with stored procedures

Question: I have written a program block like:
DECLARE
  recCount pls_integer:=0;
  idCounter pls_integer:=0;
BEGIN
  SELECT COUNT(value) into recCount FROM classname_ WHERE value='CONNECT_BLOG_INTERPRETER';
  SELECT MAX(classnameid)+1 into idCounter FROM classname_;
  IF recCount = 0 THEN
    INSERT INTO classname_ (classnameid, value) values (idCounter, 'CONNECT_BLOG_INTERPRETER');
    DBMS_OUTPUT.PUT_LINE('Inserting Record CONNECT_BLOG_INTERPRETER');
  ELSE
        DBMS_OUTPUT.PUT_LINE('Record CONNECT_BLOG_INTERPRETER already exists.');
  END IF;
END;

This statement executes without any problem, but if I wish to execute addition statements with it like:
select * from emp;

This gives me error like:
Error report:
ORA-06550: line 14, column 1:
PLS-00103: Encountered the symbol "SELECT"
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

But now, I need this to work together. Lets consider the case of DB-Patching, where multiple statements are executed one after the other.
Please guide me.
Answer: Ok I found the solution.
Its just about seperating 2 statements with /. This solved the issue.
So now, the final query can work together happily:
DECLARE
  recCount pls_integer:=0;
  idCounter pls_integer:=0;
BEGIN
  SELECT COUNT(value) into recCount FROM classname_ WHERE value='CONNECT_BLOG_INTERPRETER';
  SELECT MAX(classnameid)+1 into idCounter FROM classname_;
  IF recCount = 0 THEN
    INSERT INTO classname_ (classnameid, value) values (idCounter, 'CONNECT_BLOG_INTERPRETER');
    DBMS_OUTPUT.PUT_LINE('Inserting Record CONNECT_BLOG_INTERPRETER');
  ELSE
        DBMS_OUTPUT.PUT_LINE('Record CONNECT_BLOG_INTERPRETER already exists.');
  END IF;
END;

/

select * from emp;


SSRS Group values outside the group

Question: Below is my tablar matrix. with multiple groups.

the result after executing is as follows.

In the highlighted red text box in image (OrganizationId2), I want to see a values as
<code>=OrganizationId /OrganizationId1
</code>
when I am trying to copy the expression from OrganizationId and paste it does not allow me as aggregate value is out of the group. I tried ReportItems expression, since i have many recurring rows, this did not work.
Can any one help me in achieving this.?
Comment: Have you tried using a lookup? https://learn.microsoft.com/en-us/sql/reporting-services/report-design/report-builder-functions-lookup-function?view=sql-server-2017
Answer: Add the scope to your expression. Like this:
<code>=(Fields!YourField.Value,  "OrganizationId") / (Fields!YourField.Value, "OrganizationId2")
</code>

SSRS Group values outside the group


Making fields, condition and join dynamic in db_select query

Question: What is the Drupal way of creating queries which are dynamic in nature ?
What I mean is for example- In my module I am asking the user to select some content types and the fields associated with each of them. If node type "article" is present the user can select it and also select some fields lets say- field3, field4 - out of all the fields present field1-10. This custom selection is then stored in a table lets say "custom_table"
<code>How can i create queries of the form-
db_select('node','n')
->fields('n','field3','field4') //fields are dynamic based on user's choice stored in custom_table
->condition('n.node-type', 'article') //node type is dynamic based on user's choice stored in custom_table
->join with fields table to get field value //only for value fields
</code>
I really dont want to use php string handling and create a "select from node..." type string while looping over values in custom_table.
Is there a less time and space complex drupal way to achieve this ?
Answer: Don't chain your query, just put in some ifs and add to the query.  Like so
<code>$query = db_select('node', 'n');
if(isset($field)) {
  // Add each field separate
  $query->addField('n', 'title', 'title');
}

if(isset($article)) {
  $query->condition('n.node-type', 'article', '=');
}

if(isset($join)) {
  $query->join()....
}

$query->execute();
</code>
I think this will get you to where you want.  Please also see this thread: http://drupal.org/node/310075


The golden ratio and the logistic equation

Question: I have this bonus question in an assignment: How is the golden ratio related to the logistic equation in discrete time?
The logistic equation is $x_{n+1}=rx_n(1-x_n)$.  The professor suggested looking at the number of 2 point cycles, and 4 point cycles, and 3, 5, 6, 7, point cycles, etc. I started doing this, but it quickly becomes cumbersome to find 4-point cycles and higher.
Any suggestions?
Comment: related : [sounding number](http://www.music.sc.edu/fs/bain/soundingnumber/tracks/wheninspirationcame.html)
Comment: I don't see, how is it related to stochastic processes, so let me retag.
Comment: @draks: Transition to chaos actually occurs for $r > 4$, but showing that involves more sophisticated techniques (Schwartzian derivatives); see here: http://www2.warwick.ac.uk/fac/sci/maths/people/staff/sebastian_van_strien/demelo-strien.pdf. This is why I'm a bit confused as to the hint. For instance, in the chaotic case, the map is conjugate to a right shift on the space of 2-symbols, hence periodic points (i.e. $k$-cycles) grow as $2^k$ (i.e. number of $k$-cycles is $2^k$).
Comment: Oh sorry I broke the commenting flow, by deleting mine. They are part of my answer. See below.
Answer: Since the correct answer depends on what your professor thinks, and the fact that there are plenty of relations, I'll put my favorite:
EDIT: You might have noticed, that $2$-,$4$-,$3$-,$5$-,$6$- and $7$-point cycles start at increasing values of $r$. See here for a list. So the relation, that your professor bears in mind, could be: Can you show that there is an upper bound for $r$ using the golden ratio. You might have heard already that chaos starts at 4.00 (pm), so you have to choose $r>4$ (and better lock your door at $t<4$).
The logistic map relates to the Golden Ratio, such that a beautiful proof exists, which shows that $x_{n+1}=F(x_n)=rx_n(1-x_n)$ is chaotic, if $r>\phi^3$:
Since $r>4$, the interval $I=[0,1]$ is split into three parts. If $x_0$ lies inside the middle part, it will leave $I$ after one iteration. It is left to show that this will happen for the left ($I_0$) and right ($I_1$) interval too.
Therefore, we require that $|F(x)'|>\lambda>1$ for all $x\in I_0 \bigcup I_1 $. This union set is further called $A$. We have $|F(0)'|=|F(1)'|=r$, so $r>1$.
The roots of $F(x)=1$, giving the right/left edges of $I_{0,1}$, are
$$x_{-,+}=(1\pm \sqrt{1-4/r})/2.$$
 Substituting $x_{-,+}$ in $F(x)'$ gives
$$r^2-4r=1, \; \text{   which has roots at   } \;\; r_{+,-}=2\pm \sqrt{5}.$$
Since $r_-<0$, you choose $r_+=2+\sqrt{5}=2\phi +1=\phi^2+\phi=\phi^3$.
From here on, I copied what I needed from here, since I'm not at all experienced on this field:
By the chain rule, it follows that
$|F_n(x)'|>\lambda^n$ as well. Indeed, if this were so, we could choose two distinct point $x$ and $y$ in $A$ with the closed interval
$[x,y]\subset A$. Choose $n$ so that $\lambda^n |y-x|>1$.
By the Mean Value Theorem, it then follows that
$$|F^n(y)-F^n(x)|>\lambda^n |y-x|>1,$$
which implies that at least one of
$F^n(y)$ or $F^n(x)$ lies outside of $I$.

On the very nice linked page, you'll also find that the set $A$ is Cantor Set. (This distracted me quite a time, because I always tried to find the no-middle-third set.)
As WNY points out in his comment, the logistic map becomes chaotic for all $r>4$, but the proofs don't seem share the same kind of beauty.
In total, I think there might be plenty of relations between the logistic map and the golden ratio.
Answer: I was digging on Google and I found your question. Hopefully it's not too late.
The following is an image of some iterations of the logistic map x' = rx(1-x). To get a sense of what's going on, notice that each of the six regions represent x = [0,1] and r = [0,4].
Unfortunately I can't post images directly on this site yet, so I'll have to give a link:
http://chaotic-prng.googlecode.com/files/logistic_golden_ratio.png
The bottom-right region shows the values of x ranging from 0 to 1 as a green gradient. The bottom-right region shows the same set of values, but using only 2 colours -- green for values >= 0.5 or black for values < 0.5.
After running each value through the logistic function one time, we arrive at the middle region -- the result of the first iteration.
After running each value through the logistic function one last time, we arrive at the top region -- the result of the second iteration.
You will notice that there is most definitely a branch formed by the values in the top row. It's unmistakable in the 2 colour version. You will also notice from the 2 colour version that the trunk starts at r=2, the branches start at r = sqrt(5) + 1, and the branches effectively end at r=4.
Doing some arithmetic to get the distances involved:
D1 = (sqrt(5) + 1) - 2 = sqrt(5) - 1,
D2 = 4 - (sqrt(5) + 1),
you will notice that D1/D2 (ie. trunk length to branch length ratio) is equal to the golden ratio
phi = (sqrt(5) + 1) / 2.
Also, you will notice that 2/D1 (ie. pretrunk length to trunk length ratio) also equals the golden ratio.
Presumably, this relationship pops up in all similar maps, because...
The paper "Fibonacci order in the period-doubling cascade to chaos" by Linage et al doesn't directly mention this, but does show you from a different point of view how it comes to be.
Answer: P.S. Yes this exists in all similar maps. If you look at the second image on the page http://mathworld.wolfram.com/FeigenbaumConstant.html you will see a red-brown line that starts at the top-left and then eventually splits into three lines and then continues on. The ratio of distances covered by the line after and before the split works out to be the golden ratio.
Comment: Hi, I've merged your two accounts. If you register your account (go to your user page by clicking on your name, and select register) the software will be better able to keep track of your postings. That will, in addition to other benefits, allow you to edit your own posts.


How can recover all data and sites from accidentally delete virtual machine - Microsoft Azure

Question: We have accidentally deleted Virtual Machine from Azure portal. Virtual Machine had about 12 - 15 SQL Server databases and about 10 websites/projected hosted on it.
We are having Biz Spark account. How can we get all the data and website/projects restore. We lost all our projects. Please help me to know the way to get everything restore. Or Is there a way to undelete? We tried the option of selecting from gallery but with no success.
Thanks,
Tariq
Answer: When deleting an Azure virtual machine, you can choose if you want to delete only the VM or the attached disks too; if you didn't delete its disks, you will find them in the storage account which the VM was using, and you can use them to create a new VM with the same configuration; but if you deleted the disks together with the VM, then you are out of luck and it's time to bring forth your backups (which you have, don't you?).
Comment: You can try contacting them, maybe they can do something; but officially, you have lost your VM and it can't be recovered.
Comment: Unfortunately, attached disks also deleted. And even worst we were having database backups on save VM. Is there any why by contact Microsoft Azure support team can solve the problem.


Alternative to org.easymock.EasyMock.capture in Java 8 to 11

Question: I'm trying to capture values in my test
...
final Capture<MyDTO> myDTOCaptured = new Capture<MyDTO>();

EasyMock.expect(this.serviceMock.execute(capture(myDTOCaptured)).andReturn(someResult);
...

The Documentation says:
Deprecated API

org.easymock.EasyMock.capture(Capture)
            Because of harder erasure enforcement, doesn't compile in Java 7

http://easymock.sourceforge.net/api/easymock/3.1/deprecated-list.html
Version 3.1 is the version we are using.
Is there any alternative for capture in Java 8+? I guess the alternative is upgrading the version.
Answer: This website is obsolete. The real up-to-date EasyMock website is http://easymock.org/. EasyMock moved out of SourceForge a long time ago.
Latest EasyMock would be
Capture<TwoWayChannelMessage> initiateCapture = EasyMock.newCapture();
connection.sendToClient(capture(initiateCapture));

Answer: Upgrade to latest EasyMock (4.2) and use generic method capture(Capture<T> captured) as a replacement

Expect any object but captures it for later use

Example:

final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
connection.sendToClient(capture(initiateCapture));

Comment: @PascalPetruch yes, upgrade to latest 4.2


Change a normal submit 'input' type to 'button' type with button tag

Question: Is it possible in Drupal 8 to change a regular form submit button from Drupal into a button tag?
This is the output I need to achieve:
<button type="button" class="search-box__button">
  <svg class="icon search-box__open">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/build/img/svg-sprite.svg#icon-search"></use>
  </svg>
</button>

Answer: Well that was quick... I used my intuition and was able to accomplish it by doing the following:
In mytheme.theme:
/**
 * @param $suggestions
 * @param array $variables
 */
function mytheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#attributes']['data-twig-suggestion'])) {
    $suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['data-twig-suggestion'];
  }
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-results') {
    $form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_results_submit';
    $form['actions']['submit']['#attributes']['class'][] = 'search-box__button';
  }
}

In input--submit--search-results-submit.html.twig
{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<button{{ attributes }}>
  <svg class="icon search-box__open">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/themes/custom/mytheme/build/img/svg-sprite.svg#icon-search"></use>
  </svg>
</button>

Form still submits and functions as expected. Is this the general approach or at least acceptable? I will go with this unless there is a better way.
Comment: To use for all use:
`{{ attributes.value }}`
Comment: Looks good. Don't think there is a twig only solution, so you need to do something like this. Theme suggestion like you did or one big input.html.twig with all input versions which you select by the attributes you set in form alter.
Comment: I'll probably want to use a data-attribute on the tag instead of just the name, most likely.
Comment: Yep - I changed it to a data attribute so it doesn't interfere with anything else that may be relying on the name attribute. Works great.
Comment: Following up on comment from @VSS , to convert all input type="submit" to buttons, add `input--submit.htm.twig` to your theme with contents: `{{ attributes.value }}`.
Answer: You simply could use inline_template.
$build['hello']  = [
  '#type' => 'inline_template',
  '#template' => '<button type="button" class="search-box__button">
     <svg class="icon search-box__open">
       <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/build/img/svg-sprite.svg#icon-search"></use>
     </svg>
   </button>',
];

Comment: Won't you lose anything added on by `{{ attributes }}`?
Comment: I guess you would have to set your own attributes in the `'#context'` array.


True/ False: Let A be an n×n matrix. The set of all n×n matrices X that satisfies (A+A^2)X = O is not closed under the matrix multiplication.

Question: Question: Let A be an n×n matrix. The set of all n×n matrices X that satisfies (A+A^2)X = O is not closed under the matrix multiplication.
I understand that the I have to somehow prove that the set X is closed under the matrix multiplication/or not closed; however, I am not sure how to start working on this problem.
Would you be able to help me get an idea of where to start?
Thank you.
Comment: Well, it *is* closed under matrix multiplication. Actually, if $X$ is in the set and $Y$ is *any* $n\times n$ matrix, then $XY$ is in the set.
Comment: Thank you for your comment, I am not sure how to start the prof, since X is the set and it is also involved into the equality.
Do I say that since A is in X, then for any n x n matrix C, the equality (AC+(AC)^2)X=O holds?
Thank you!
Comment: The set is not $X$. Call it $\mathcal{A}$ or whatever: you want to show that $\mathcal{A}=\{X:(A+A^2)X=O\}$ is closed under matrix multiplication. Please, remove the wrong "not be" from your text.
Answer: You're under a misunderstanding. Let's fix some notation: $M_{n}$ is the set of $n\times n$ matrices. You want to see whether
$$
\mathcal{S}=\{X\in M_n: (A+A^2)X=O\}
$$
is (or is not) closed under matrix multiplication. There is no $X$, it's just a placeholder, and surely the text doesn't say that the set is called $X$. And $A$ is a fixed matrix, and generally $A\notin\mathcal{S}$.
Now, if $B,X,Y$ are $n\times n$ matrices and $BX=O$, then $BXY=O$ as well. So, if $BX=O$ and $BY=O$, then $B(XY)=O$.
Can you finish by choosing $B=A+A^2$?
Comment: Oh, I see now, thank you very much for your explanation, my perception of this questions was wrong! I can proceed by showing that the set S is closed under matrix multiplication, given that multiplying arbitrary n x n matrices by X will yield O.
Comment: @Valeri Yes, that's right.


Reusing a view model but applying different validation rules in ASP.NET MVC

Question: So we use DataAnnotations to achieve input validation for our ASP.NET MVC forms. If we were to start again I'd consider Fluent Validation, but we're too far along now to make the change.
So this project requires us to build a lot of forms. As we've progressed, we've identified groups of inputs that get repeated across forms. An example of this might be a set of inputs to represent an Address.
We've then turned the Address input into a reusable module by creating an _AddressEntry partial view for it along with an associated view model - AddressViewModel. The view model for the parent form then looks like:
public class SubmitEnquiryViewModel
{
    public AddressViewModel Address { get; set; }

    public string Enquiry { get; set; }

    ...
}

In the _SubmitEnquiry view, we then insert the _AddressEntry partial view using EditorFor().
This works fine until we realise different instances of the Address input have different validation requirements - the validation attributes decorating AddressViewModel do not always apply. To get around the problem we define an IAddressViewModel:
public interface IAddressViewModel
{
    string LineOne { get; set; }

    string LineTwo { get; set; }

    ...
}

And then define concrete implementations of this interface for all the different permutations of validation specification - e.g. AddressViewModel (default validation), AddressNoValidationViewModel etc.
The _AddressEntry partial view is then bound to IAddressViewModel and the appropriate concrete implementation is chosen for the Address property of the parent view model.
The main drawback of this approach is that we could potentially end up with quite a few view models that only differ by the validation attributes applied to them. This is deemed acceptable though as the number of reusable modules is expected to be relatively small.
Has anyone else faced this challenge before? What solution did you come up with? What are your thoughts on the solution described above?
Comment: How are you doing your validations, exactly?
Comment: Using OOTB `DataAnnotations` validation attributes and letting `DefaultModelBinder` do its thing (and thus `DataAnnotationsModelValidator` I guess).
Answer: You may want to look into the MetadataTypeAttribute.
Base class:
public abstract class AddressDetailsBase
{
  public string Line1 { get; set; }
  public string Line2 { get; set; }
  public string City { get; set; }
  public string State { get; set; }
  public int PostalCode { get; set;}
}

Validation (I use interfaces so it can't be accidentally instantiated):
public interface IUserAddressDetailsValidation
{
  [required]
  string Line1 { get; set; }
  [required]
  string Line2 { get; set; }
  [required]
  string City { get; set; }
  [required]
  string State { get; set; }
  [required]
  int PostalCode { get; set;}
}

View Model Type:
[MetadataType(typeof(IUserAddressDetailsValidation))]
public class UserAddressDetails : AddressDetailsBase { }

Comment: Thanks for bringing MetadataTypeAttribute to my attention.

This solution works apart from one issue - binding the view to AddressDetailsBase, the HTML helpers don't pick up validation attributes applied in IUserAddressDetailsValidation so client side validation doesn't work. Any ideas?

I'm trying to dynamically change the parameter type of the expression passed in to the HTML helper from AddressDetailsBase to UserAddressDetails but I'm struggling at the moment!
Comment: In this instance you would not use the Base object for validation, it has no validation.  As for the struggle with changing it, I can't help you as you haven't provided any details what so ever.
Comment: The fundamental issue has been identified here: http://stackoverflow.com/a/15232767/3619572 I have resolved the issue by using the non generic HTML helpers.
Answer: Data Annotations are good for very simple scenarios and for prototype projects.
As you can see, you are already fighting the annotations, which are not suited to work in different contexts.
Just use plain ModelState.AddModelError in controller actions, and build custom validation logic in your controller.
ModelState.AddModelError("Prop", "Your custom 'validation failed' message.");

You can still evaluate ModelState.IsValid before doing your custom validation, so you can still use DataAnnotations for simple cases for some code reuse.


Using two structures in Array or ArrayList in Java

Question: In C#, there was a chance to use:
Arraylist<String,int> data = Arraylist();

as far as i remember.
Is there any version of this in Java?
For example, the information on the array will be :
Apple 5
Tomato 3
Potato 9
... etc.

This is why I am trying to define such a structure.
EDITED:
How about creating a class such as;
public class x
{
int a;
String  b;
}

and creating the arraylist from this class.
ArrayList<x> data = new ArrayList<x>();

Will this work?
Comment: C# does not allow that. In fact, there's no such thing as a generic ArrayList in C#. And List takes a single generic parameter.
Comment: Note: C# would be `Dictionary`, where the strings are unique. Having a non-unique key value list is slightly less straightforward.
Comment: What exactly is your intent with this code? What's the relationship of the number to the `String`? The best thing to do here depends greatly on that.
Answer: Assuming you are looking for a way to do  { key,value } pair then you should use a Map. Example below and check out the java docs.
Map<String,Integer> someMap = new HashMap<String,Integer>();

Read more on map here.
If you are looking for a place holder to store the piece of data then you need to something like this.
public final class Fruit{

private String fruitName;
private Integer fruitCount;

//constructor initialized values.
//getters and setters for those
}

Then in your main class you define this way.
List<Fruit> fruits = new ArrayList<Fruit>();

To read up more on list read this link.
Comment: Assuming you are actually trying to map a String to an integer, yes.  If the OP is just trying to correlate the two pieces of data (say each element of the list represents a container of fruit of a variable quantity) than you just need a class with a `String` and `int` member and store that instead.
Comment: Correct Mark. But from the data it looks like he is wanting a fruit name and perhaps a count of how many fruits of each type he has. However, I could be completely wrong here. If it's just a data holder then we need to create a class of fruits. I will modify my answer and add proper assumptions.
Answer: It seems to me that you need a Map instead of a List:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Apple", 5);
map.put("Tomato", 3);
map.put("Potato", 9);

Answer: One other option (I'm not saying it's a better option) would be to use:
List<Pair<String, Integer>> list = new ArrayList<Pair<String, Integer>>

Where you have a class Pair:
class Pair<E, F> {
    public E one;
    public F two;
}

Comment: I often see java answers with `List foo = new ArrayList()` or, in this question, `Map map = new HashMap()`. Is `ArrayList<>` a more specialized version of `List<>` and its just a convention to declare and instantiate this way? Or is there something else to it?
Comment: @Anthony Pegram List is an interface.  ArrayList is an implementation of List.
Comment: @Anthony: it's always best to program to the most general interface that meets your requirements.  Declaring your variable as `List` or `Map` means that you can easily swap in a new implementation (say `LinkedList` or `SortedMap`) at a later time if you so desire.
Comment: @Justin: Under rare cases this might be nice, but I find typically if you're going to go this route you should just make an actual class that encapsulates the two fields.
Comment: @Anthony, `List` is the interface and `ArrayList` is the class that implements it.  It is just good practice to declare the variable as the interface.  It will allow you to change the implementation that you want to use in the future.
Comment: @Jonathan, Mark, thanks. I understand the principal, certainly, yet seeing *every* answer do it (might be overstating) almost makes it seem compulsory rather than simply being good practice.
Comment: I accepted Justin's solution, since this is what I really want. Thanks to everyone.
Answer: What the best thing to do here is depends greatly on what the relationship between the String and the number are. Here are a number of possibilities and what you might want to do with them.
The number is an ID or some such closely related property:
Create a class to represent these objects and associate their properties.
public class Item {
  private final int id;
  private final String name;

  // constructor, getters, equals, hashCode, toString
}

The number is a count of the named items:
Use a Guava Multiset to keep a count of the items.
Multiset<String> items = HashMultiset.create();
items.add("Apple", 5);
items.add("Tomato", 3);
// etc.

The number is something else related to the String but not closely enough to store in a single object:
Use a normal Map as suggested in other answers.
A Pair is not a great solution
While you've accepted an answer suggesting the use of a Pair class, I strongly recommend against that, as Pair does nothing to indicate what the two values it contains are nor what the relationship between them is and it doesn't provide the conveniences of a Map as far as getting the value that's associated with a particular key either.


Fitting melodies to beats!

Question: OK, need a head's up so I can practice this: the basic technique for fitting a tune to a beat. Take, for example, Red Red Wine.  UB40 did it as a reggae song.  I've heard it as a blues ballad, a pop song, even a neo-rave track!
Imagine you've got the basic drums-rhythm set up for several different styles.  How do you then go about fitting the right part of the melody to the right part of the beat so it still 'sounds right'?  (Another example is Galloping Home from Black Beauty - there's an awesome rave version on YouTube

 )
Basically, any info on changing rhythms and fitting tunes to rhythms, on-beats/offbeats, how to make a tune/rhythm 'sit right' together would be greatly appreciated.  All info will be practiced!
Note: I'm not looking for info on how to use a drum machine, but how to fit the music to the rhythm afterwards.
Comment: You mean to change the whole feeling of the song? Or even the structure of the song?
Answer: You're asking about re-arranging the music and that is an artistic process, which no one else can tell you how to do precisely.
If you're not sure where to begin, then:

Learn to play the song that you want to re-arrange in the original style.
Learn to play several songs in the style that you want to change the original song into.
Get your beat going, then use your knowledge of both the original song and the style that you gained from the first two steps above to play the song in the new style.

When you have done the homework before re-arranging the song, by learning the target style and the song itself backwards and forwards, performing the song in the target style will be much easier. You'll be able to make choices about how you want to change the song almost without thinking about it. It will be a very creative, artistic process.
One larger point: Most of the time, when a question on this site is something like "How do I do ____?", the answer almost always boils down to practice! Sometimes (as in this case), you have to practice something other than what you're trying to do to gain the tools you need to do it.

Fitting melodies to beats!


Input text dentro de If

Question: Olá, estou fazendo um formulário e gostaria que algumas perguntas (em formato input)
aparecessem apenas se fosse selecionado certa resposta no select anterior.
Você trabalha no Desktop ou no Notebook?:
<select name="pc1">
<option selected="selected"> </option>
<option>Desktop</option>
<option>Notebook</option>
</select>

No caso de usar Desktop, quantos monitores?:
<input type="text" name="numtela" size="5" />

Invés da pergunta "No caso de usar Desktop", gostaria que a pergunta somente aparecesse caso seja selecionado "Desktop", imagino que seja algo como:
<?php
if ($pc1 = $Desktop) {
No caso de usar Desktop, quantos monitores?:
<input type="text" name="numtela" size="5" />

}
?>

Porém não consegui fazer funcionar (comecei hoje a programar em php, não sei nada nada nada)
Comment: Está faltando alguns detalhes, mas de antemão ,  o sinal para fazer a comparação é `==`...
Answer: Nesse caso, para mostrar ou esconder um contéudo(o chamado toggle), você pode usar Javascript ao invés de php.
primeiro atribua um valor para cada option e dê um id para o select, a pergunta e o input.
Teste o código abaixo.

//esconde a pergunta e o input
document.getElementById("perguntamonitores").style.display = 'none';
document.getElementById('monitores').style.display = 'none';

function mostrarpergunta() {
    //Se for selecionado o desktop, mostra o
 e o <input> como bloco(mas pode ser como flex também)
    let select = document.getElementById("desk/note")
    let opcao = select.options[select.selectedIndex].value;
    if (opcao === "desk"){
        document.getElementById("perguntamonitores").style.display = 'block';
        document.getElementById('monitores').style.display = 'block';
    }
}

Você trabalha no Desktop ou no Notebook?

<select name="pc1" id="desk/note" onblur="mostrarpergunta();">
    <option selected="selected"></option>
    <option value="desk">Desktop</option>
    <option value="note">Notebook</option>
</select>

No caso de usar Desktop, quantos monitores?

<input id="monitores" type="text" name="numtela" size="5" />

caso você queira que ao aparecer tenha uma transição ou um estilo css especifico para mostrar e esconder, sugiro que ao invés de usar o document.getElementById('id').style.display = 'block'; use o Element.classList
Espero ter ajudado João

Input text dentro de If