问:
OpenCV Multi-threading giving errors
I am running OpenCV code on multiple threads in the following fashion:

```<code>std::thread t1(runOnSingleCamera, alphaFile, featureToUse, classifier,0);
  std::thread t2(runOnSingleCamera, betaFile, featureToUse, classifier,1);
  std::thread t3(runOnSingleCamera, gammaFile, featureToUse, classifier,2);
  std::thread t4(runOnSingleCamera, deltaFile, featureToUse, classifier,3);
  t1.join();
  t2.join();
  t3.join();
  t4.join();
</code>```

This compiles fine, but when I run it I get a variety of errors, and it even occasionally works...

Here is a sample of some of the errors I get:

```<code>tom@thinkpad:~/Documents/Project/reidThermal/src$ ./main -d=1 -c=0 -f=1
Segmentation fault (core dumped)
tom@thinkpad:~/Documents/Project/reidThermal/src$ ./main -d=1 -c=0 -f=1

(betaInput.webm:8571): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8571): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8571): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8571): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8571): Gtk-CRITICAL **: IA__gtk_widget_new: assertion 'g_type_is_a (type, GTK_TYPE_WIDGET)' failed

(betaInput.webm:8571): Gtk-CRITICAL **: IA__gtk_widget_new: assertion 'g_type_is_a (type, GTK_TYPE_WIDGET)' failed
Segmentation fault (core dumped)
tom@thinkpad:~/Documents/Project/reidThermal/src$ ./main -d=1 -c=0 -f=1

(alphaInput.webm:8593): GLib-GObject-WARNING **: invalid cast from 'CvImageWidget' to 'CvImageWidget'

** (alphaInput.webm:8593): CRITICAL **: void cvImageWidget_size_allocate(GtkWidget*, GtkAllocation*): assertion 'CV_IS_IMAGE_WIDGET (widget)' failed

** (alphaInput.webm:8593): CRITICAL **: void cvImageWidget_realize(GtkWidget*): assertion 'CV_IS_IMAGE_WIDGET (widget)' failed
**
Gtk:ERROR:/build/gtk+2.0-KsZKkB/gtk+2.0-2.24.30/gtk/gtkwidget.c:8861:gtk_widget_real_map: assertion failed: (gtk_widget_get_realized (widget))
Aborted (core dumped)
tom@thinkpad:~/Documents/Project/reidThermal/src$ ./main -d=1 -c=0 -f=1
/usr/share/themes/Ambiance/gtk-2.0/gtkrc:720: Unable to find include file: "apps/ff.rc"

(betaInput.webm:8615): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8615): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8615): Gtk-CRITICAL **: IA__gtk_widget_new: assertion 'g_type_is_a (type, GTK_TYPE_WIDGET)' failed
Segmentation fault (core dumped)
</code>```

Has anyone seen this before/know what is going wrong and how to fix it?

Running using gdb gives the following:

```<code>Thread 4 "main" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffdb7fe700 (LWP 29317)]
0x0000000000000000 in ?? ()
</code>```

I am on the most up to date version of Ubuntu using the most up to date version of OpenCV at the time of asking.

Full code below as requested, it is very long and made up of multiple elements, I imagine the issue would be early or in the declarations, or possibly an incompatability with the imshow function:

```int runOnSingleCamera(String file, int featureToUse, int classifier, int cameraID)
{
    //enable velocity
    int timeSteps = 0;

  string windowName = file; // window name

  Mat img, outputImage, foreground; // image objects
  VideoCapture cap;

  bool keepProcessing = true;   // loop control flag
  unsigned char  key;           // user input
  int  EVENT_LOOP_DELAY = 40;   // delay for GUI window, 40 ms equates to 1000ms/25fps = 40ms per frame

  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;
  int width = 40;
  int height = 100;
  int learning = 1000;
  int padding = 40;

  // if command line arguments are provided try to read image/video_name
  // otherwise default to capture from attached H/W camera
  if((cap.open(file) == true))
  {
        // create window object (use flag=0 to allow resize, 1 to auto fix size)
        namedWindow(windowName, 1);

        // create background / foreground Mixture of Gaussian (MoG) model
        Ptr<BackgroundSubtractorMOG2> MoG = createBackgroundSubtractorMOG2(500,25,false);

        HOGDescriptor hog;
        hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());

        CascadeClassifier cascade = CascadeClassifier(CASCADE_TO_USE);

    Ptr<SuperpixelSEEDS> seeds;

        // start main loop
      while(keepProcessing)
        {
          int64 timeStart = getTickCount();

            if (cap.isOpened())
          {
                cap >> img;

                if(img.empty())
                {
                    std::cerr << "End of video file reached" << std::endl;
                    exit(0);
                }
                outputImage = img.clone();

                cvtColor(img, img, CV_BGR2GRAY);
            }
          else
          {
              // if not a capture object set event delay to zero so it waits
              // indefinitely (as single image file, no need to loop)
              EVENT_LOOP_DELAY = 0;
          }

          // update background model and get background/foreground
          MoG->apply(img, foreground, (double)(1.0/learning));

          //imshow("old foreground", foreground);

/////////////////////////////////////////////////////////////////////////////////SUPERPIXELS
          int useSuperpixels = 0;

          if(useSuperpixels == 1)
            {
              Mat seedMask, labels, result;

              result = img.clone();

              int width = img.size().width;
            int height = img.size().height;

            seeds = createSuperpixelSEEDS(width, height, 1, 2000, 10, 2, 5, true);

          seeds->iterate(img, 10);

            seeds->getLabels(labels);

            vector<int> counter(seeds->getNumberOfSuperpixels(),0);
            vector<int> numberOfPixelsPerSuperpixel(seeds->getNumberOfSuperpixels(),0);

            vector<bool> useSuperpixel(seeds->getNumberOfSuperpixels(),false);

            for(int i = 0; i<foreground.rows; i++)
            {
                for(int j = 0; j<foreground.cols; j++)
                {
                    numberOfPixelsPerSuperpixel[labels.at<int>(i,j)] += 1;
                    if(foreground.at<unsigned char>(i,j)==255)
                    {
                        counter[labels.at<int>(i,j)] += 1;
                    }
                }
            }

            for(int i = 0; i<counter.size(); i++)
            {
                if(counter[i]/numberOfPixelsPerSuperpixel[i] > 0.0001)
                {
                    useSuperpixel[i] = true;
                }
            }

            for(int i = 0; i<foreground.rows; i++)
            {
                for(int j = 0; j<foreground.cols; j++)
                {
                    if(useSuperpixel[labels.at<int>(i,j)] == true)
                    {
                        foreground.at<unsigned char>(i,j) = 255;
                    }
                    else
                    {
                        foreground.at<unsigned char>(i,j) = 0;
                    }
                }
            }
            }
/////////////////////////////////////////////////////////////////////////////////
            else
            {
              // perform erosion - removes boundaries of foreground object
              erode(foreground, foreground, Mat(),Point(),1);

              // perform morphological closing
              dilate(foreground, foreground, Mat(),Point(),5);
              erode(foreground, foreground, Mat(),Point(),1);
            }
          //imshow("foreground", foreground);

          // get connected components from the foreground
          findContours(foreground, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

          // iterate through all the top-level contours,
          // and get bounding rectangles for them (if larger than given value)

          for(int idx = 0; idx >=0; idx = hierarchy[idx][0])
          {
                Rect r = boundingRect(contours[idx]);

                // adjust bounding rectangle to be padding% larger
                // around the object
                r.x = max(0, r.x - (int) (padding/100.0 * (double) r.width));
                r.y = max(0, r.y - (int) (padding/100.0 * (double) r.height));

                r.width = min(img.cols - 1, (r.width + 2 * (int) (padding/100.0 * (double) r.width)));
                r.height = min(img.rows - 1, (r.height + 2 * (int) (padding/100.0 * (double) r.height)));

                // draw rectangle if greater than width/height constraints and if
                // also still inside image
                if ((r.width >= width) && (r.height >= height) && (r.x + r.width < img.cols) && (r.y + r.height < img.rows))
                {
                  vector<Rect> found, found_filtered;

                  Mat roi = outputImage(r);

                  if (classifier == 1)
                  {
                        //changing last parameter helps deal with multiple rectangles per person
                        if (cameraID == 3)
                        {
                            hog.detectMultiScale(roi, found, 0, Size(8,8), Size(32,32), 1.05, 5);
                        }
                        else
                        {
                            hog.detectMultiScale(roi, found, 0, Size(8,8), Size(64,64), 1.05, 5);
                        }
                  }
                  else
                  {
                    if (cameraID == 3)
                    {
                        cascade.detectMultiScale(roi, found, 1.1, 4, CV_HAAR_DO_CANNY_PRUNING, cvSize(32,32));
                    }
                    else
                    {
                        cascade.detectMultiScale(roi, found, 1.1, 4, CV_HAAR_DO_CANNY_PRUNING, cvSize(64,64));
                    }
                  }

                  for(size_t i = 0; i < found.size(); i++ )
                  {
                        Rect rec = found[i];

                        rec.x += r.x;
                        rec.y += r.y;

                        size_t j;
                        // Do not add small detections inside a bigger detection.
                        for ( j = 0; j < found.size(); j++ )
                        {
                          if ( j != i && (rec & found[j]) == rec )
                          {
                              break;
                          }
                        }

                        if (j == found.size())
                        {
                          found_filtered.push_back(rec);
                        }
                  }
                  for (size_t i = 0; i < found_filtered.size(); i++)
                  {
                        Rect rec = found_filtered[i];

                        // The HOG/Cascade detector returns slightly larger rectangles than the real objects,
                        // so we slightly shrink the rectangles to get a nicer output.
                        rec.x += rec.width*0.1;
                        rec.width = rec.width*0.8;
                        rec.y += rec.height*0.1;
                        rec.height = rec.height*0.8;
                        // rectangle(img, rec.tl(), rec.br(), cv::Scalar(0,255,0), 3);

                        Point2f center = Point2f(float(rec.x + rec.width/2.0), float(rec.y + rec.height/2.0));

                        Mat regionOfInterest;

                        Mat regionOfInterestOriginal = img(rec);
                        //Mat regionOfInterestOriginal = img(r);

                        Mat regionOfInterestForeground  = foreground(rec);
                        //Mat regionOfInterestForeground = foreground(r);

                        bitwise_and(regionOfInterestOriginal, regionOfInterestForeground, regionOfInterest);

                        Mat clone = regionOfInterest.clone();

                        resize(clone, regionOfInterest, Size(64,128), CV_INTER_CUBIC);

                        imshow("roi", regionOfInterest);

                        double huMoments[7];
                        vector<double> hu(7);
                        Mat hist;
                        vector<float> descriptorsValues;

                        Mat feature;

                        if(featureToUse == 1) //HuMoments
                        {
                          vector<vector<Point> > contoursHu;
                          vector<Vec4i> hierarchyHu;

                          findContours(regionOfInterest, contoursHu, hierarchyHu, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

                          double largestSize,size;
                          int largestContour;

                          for(int i = 0; i < contoursHu.size(); i++)
                          {
                                size = contoursHu[i].size();

                                if(size > largestSize)
                                {
                                  largestSize = size;
                                  largestContour = i;
                                }
                          }
                          Moments contourMoments;

                          contourMoments = moments(contoursHu[largestContour]);

                          HuMoments(contourMoments, huMoments);

                          hu.assign(huMoments,huMoments+7);

              feature = Mat(hu);
              feature = feature.t();
                        }
                        else if(featureToUse == 2) //HistogramOfIntensities
                        {
                          int histSize = 16;    // bin size - need to determine which pixel threshold to use
                          float range[] = {0,255};
                          const float *ranges[] = {range};
                          int channels[] = {0, 1};

                          calcHist(&regionOfInterest, 1, channels, Mat(), hist, 1, &histSize, ranges, true, false);

                          feature = hist.clone();
                          feature = feature.t();
                        }

                        else if(featureToUse == 3) //HOG
                        {
                          //play with these parameters to change HOG size
                          cv::HOGDescriptor descriptor(Size(64, 128), Size(16, 16), Size(16, 16), Size(16, 16), 4, -1, 0.2, true, 64);

                          descriptor.compute(regionOfInterest, descriptorsValues);

                          feature = Mat(descriptorsValues);
                          feature = feature.t();
                        }

                        else if(featureToUse == 4) //Correlogram
                        {
                            Mat correlogram(8,8,CV_64F);
                            Mat occurances(8,8,CV_8U);

                            int xIntensity, yIntensity;

                            for(int i = 0; i<regionOfInterest.rows; i++)
                            {
                                for(int j = 0; j<regionOfInterest.cols; j++)
                                {
                                    xIntensity = floor(regionOfInterest.at<unsigned char>(i,j)/32);

                                    for(int k = i; k<regionOfInterest.rows; k++)
                                    {
                                        for(int l = 0; l<regionOfInterest.cols; l++)
                                        {
                                            if((k == i && l > j) || k > i)
                                            {
                                                yIntensity = floor(regionOfInterest.at<unsigned char>(k,l)/32);

                                                correlogram.at<double>(xIntensity,yIntensity) += (norm(Point(i,j)-Point(k,l)));
                                                correlogram.at<double>(yIntensity,xIntensity) += (norm(Point(i,j)-Point(k,l)));

                                                occurances.at<unsigned char>(xIntensity,yIntensity) += 1;
                                                occurances.at<unsigned char>(yIntensity,xIntensity) += 1;
                                            }
                                        }
                                    }
                                }
                            }
                            //average it out
                            for(int i = 0; i<correlogram.rows; i++)
                            {
                                for(int j = 0; j<correlogram.cols; j++)
                                {
                                    correlogram.at<double>(i,j) = occurances.at<unsigned char>(i,j);
                                }
                            }

                            feature = correlogram.reshape(1,1);
                        }
                        else if(featureToUse == 5) //Flow
                        {

                        }

                        feature.convertTo(feature, CV_64F);

                        normalize(feature, feature, 1, 0, NORM_L1, -1, Mat());
                        cout << "New Feature" << endl << feature << endl;

                        //classify first target
                        if(targets.size() == 0) //if first target found
                        {
                          Person person(0, center.x, center.y, timeSteps, rec.width, rec.height);

                          person.kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                          Rect p = person.kalmanPredict();

                          person.updateFeatures(feature);

                          person.setCurrentCamera(cameraID);

                          rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                          char str[200];
                          sprintf(str,"Person %d",person.getIdentifier());

                          putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));

                          targets.push_back(person);
                        }
                        else
                        {
                            vector<double> mDistances;
                            bool singleEntry = false;

                            for(int i = 0; i<targets.size(); i++)
                            {
                                if(targets[i].getFeatures().rows == 1)
                                {
                                    singleEntry = true;
                                }
                            }

                            for(int i = 0; i<targets.size(); i++)
                            {
                                Mat covar, mean;
                                Mat data = targets[i].getFeatures();

                                calcCovarMatrix(data,covar,mean,CV_COVAR_NORMAL|CV_COVAR_ROWS);

                                // cout << i << " data" << endl << data << endl;

                                // cout << i << " Covar" << endl << covar << endl;

                                // cout << i << " mean" << endl << mean << endl;

                                double mDistance;

                                if(singleEntry == false)
                                {
                                    Mat invCovar;

                                    invert(covar,invCovar,DECOMP_SVD);

                                    mDistance = Mahalanobis(feature,mean,invCovar);

                                    cout << i << " Mahalanobis Distance" << endl << mDistance << endl;
                                }
                                else
                                {
                                    mDistance = norm(feature,mean,NORM_L1);

                                    cout << i << " Norm Distance" << endl << mDistance << endl;
                                }
                                mDistances.push_back(mDistance);
                            }

                            Mat test = Mat(mDistances);
                            cout << "Distances" << endl << test << endl;

                            double sum = 0.0;
                            for(int i = 0; i<mDistances.size(); i++)
                            {
                                sum += mDistances[i];
                            }
                            for(int i = 0; i<mDistances.size(); i++)
                            {
                                mDistances[i] = sum/mDistances[i];
                            }

                            normalize(mDistances,mDistances,1,0,NORM_L1,-1,Mat());

                            Mat probabilities = Mat(mDistances);

                            cout << "Probabilities" << endl << probabilities << endl;

                            //special case to classify second target
                        if(targets.size() == 1)
                        {
                            if(fabs(center.x-targets[0].getLastPosition().x)<100 and fabs(center.y-targets[0].getLastPosition().y)<100)
                            {
                                targets[0].kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                                  Rect p = targets[0].kalmanPredict();

                                targets[0].updateFeatures(feature);

                                targets[0].setCurrentCamera(cameraID);

                                  rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                                  char str[200];
                                  sprintf(str,"Person %d",targets[0].getIdentifier());

                                  putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));
                            }
                            else
                            {
                                Person person(1, center.x, center.y, timeSteps, rec.width, rec.height);

                                  person.kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                                  Rect p = person.kalmanPredict();

                                person.updateFeatures(feature);

                                person.setCurrentCamera(cameraID);

                                  rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                                  char str[200];
                                  sprintf(str,"Person %d",person.getIdentifier());

                                  putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));

                                  targets.push_back(person);
                            }
                        }

                        else
                        {
                            double greatestProbability = 0.0;
                            int identifier = 0;

                            double min, max;
                                Point min_loc, max_loc;
                                minMaxLoc(probabilities, &min, &max, &min_loc, &max_loc);

                                greatestProbability = max;
                                identifier = max_loc.y;

                                cout << greatestProbability << " at " << identifier << endl;

                            if(greatestProbability >= 0.5)
                            {
                                targets[identifier].kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                                  Rect p = targets[identifier].kalmanPredict();

                                targets[identifier].updateFeatures(feature);

                                targets[identifier].setCurrentCamera(cameraID);

                                  rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                                  char str[200];
                                  sprintf(str,"Person %d",targets[identifier].getIdentifier());

                                  putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));
                            }
                            else
                            {
                                int identifier = targets.size();
                                  Person person(identifier, center.x, center.y, timeSteps, rec.width, rec.height);

                                  person.kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                                  Rect p = person.kalmanPredict();

                                person.updateFeatures(feature);

                                person.setCurrentCamera(cameraID);

                                  rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                                  char str[200];
                                  sprintf(str,"Person %d",person.getIdentifier());

                                  putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));

                                  targets.push_back(person);
                            }
                        }
                    }
                  }
                  rectangle(outputImage, r, Scalar(0,0,255), 2, 8, 0);
                }
          }
          // display image in window
          imshow(windowName, outputImage);

      key = waitKey((int) std::max(2.0, EVENT_LOOP_DELAY - (((getTickCount() - timeStart) / getTickFrequency())*1000)));

      if (key == 'x')
    {
            // if user presses "x" then exit
            std::cout << "Keyboard exit requested : exiting now - bye!" << std::endl;
            keepProcessing = false;
      }
      timeSteps += 1;
      }
      // the camera will be deinitialized automatically in VideoCapture destructor
      // all OK : main returns 0
      return 0;
    }
    // not OK : main returns -1
    return -1;
}
```

答:
What's happening is that you're abusing some feature of OpenCV that doesn't support running in a multi-threaded environment, or else you're not making proper use of control mechanisms such as mutexes and monitors to restrict access to critical sections of your code to one thread at a time. We won't be able to tell you what you're doing wrong unless you share more of your code though. From your log it seems as though some sort of initialization is being run more than once.

From your code and your log, two things come to mind:

Are you accidentally trying to access video capture hardware on multiple threads?

Maybe creating a new window causes initialization of something in GTK. Try to create your windows on the main thread, see if it helps. Note that OpenCV or not, having more than one thread for your UI is a bad idea.

If none of this helps, try adding some log output to your code so we can be sure which line is causing the errors.

So it was #2 after all. To fix it, you must move all the namedWindow calls to the main thread. Afterwards, if it still fails on the imshow calls, you'll have to move that to the main thread as well. You'll need a condition variable for each thread, and global variables which the threads write to and the main thread uses to update the windows. I'd provide the code, but I don't know much about c++ concurrency. You can read more about this task here: waiting thread until a condition has been occurred

Title: OpenCV Multi-threading giving errors

Body:
I am running OpenCV code on multiple threads in the following fashion:

std::thread t1(runOnSingleCamera, alphaFile, featureToUse, classifier,0);
  std::thread t2(runOnSingleCamera, betaFile, featureToUse, classifier,1);
  std::thread t3(runOnSingleCamera, gammaFile, featureToUse, classifier,2);
  std::thread t4(runOnSingleCamera, deltaFile, featureToUse, classifier,3);
  t1.join();
  t2.join();
  t3.join();
  t4.join();

This compiles fine, but when I run it I get a variety of errors, and it even occasionally works...

Here is a sample of some of the errors I get:

tom@thinkpad:~/Documents/Project/reidThermal/src$ ./main -d=1 -c=0 -f=1
Segmentation fault (core dumped)
tom@thinkpad:~/Documents/Project/reidThermal/src$ ./main -d=1 -c=0 -f=1

(betaInput.webm:8571): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8571): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8571): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8571): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8571): Gtk-CRITICAL **: IA__gtk_widget_new: assertion 'g_type_is_a (type, GTK_TYPE_WIDGET)' failed

(betaInput.webm:8571): Gtk-CRITICAL **: IA__gtk_widget_new: assertion 'g_type_is_a (type, GTK_TYPE_WIDGET)' failed
Segmentation fault (core dumped)
tom@thinkpad:~/Documents/Project/reidThermal/src$ ./main -d=1 -c=0 -f=1

(alphaInput.webm:8593): GLib-GObject-WARNING **: invalid cast from 'CvImageWidget' to 'CvImageWidget'

** (alphaInput.webm:8593): CRITICAL **: void cvImageWidget_size_allocate(GtkWidget*, GtkAllocation*): assertion 'CV_IS_IMAGE_WIDGET (widget)' failed

** (alphaInput.webm:8593): CRITICAL **: void cvImageWidget_realize(GtkWidget*): assertion 'CV_IS_IMAGE_WIDGET (widget)' failed
**
Gtk:ERROR:/build/gtk+2.0-KsZKkB/gtk+2.0-2.24.30/gtk/gtkwidget.c:8861:gtk_widget_real_map: assertion failed: (gtk_widget_get_realized (widget))
Aborted (core dumped)
tom@thinkpad:~/Documents/Project/reidThermal/src$ ./main -d=1 -c=0 -f=1
/usr/share/themes/Ambiance/gtk-2.0/gtkrc:720: Unable to find include file: "apps/ff.rc"

(betaInput.webm:8615): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8615): GLib-GObject-WARNING **: cannot register existing type 'CvImageWidget'

(betaInput.webm:8615): Gtk-CRITICAL **: IA__gtk_widget_new: assertion 'g_type_is_a (type, GTK_TYPE_WIDGET)' failed
Segmentation fault (core dumped)

Has anyone seen this before/know what is going wrong and how to fix it?

Running using gdb gives the following:

Thread 4 "main" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffdb7fe700 (LWP 29317)]
0x0000000000000000 in ?? ()

I am on the most up to date version of Ubuntu using the most up to date version of OpenCV at the time of asking.

Full code below as requested, it is very long and made up of multiple elements, I imagine the issue would be early or in the declarations, or possibly an incompatability with the imshow function:

int runOnSingleCamera(String file, int featureToUse, int classifier, int cameraID)
{
    //enable velocity
    int timeSteps = 0;

  string windowName = file; // window name

  Mat img, outputImage, foreground; // image objects
  VideoCapture cap;

  bool keepProcessing = true;   // loop control flag
  unsigned char  key;           // user input
  int  EVENT_LOOP_DELAY = 40;   // delay for GUI window, 40 ms equates to 1000ms/25fps = 40ms per frame

  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;
  int width = 40;
  int height = 100;
  int learning = 1000;
  int padding = 40;

  // if command line arguments are provided try to read image/video_name
  // otherwise default to capture from attached H/W camera
  if((cap.open(file) == true))
  {
        // create window object (use flag=0 to allow resize, 1 to auto fix size)
        namedWindow(windowName, 1);

        // create background / foreground Mixture of Gaussian (MoG) model
        Ptr<BackgroundSubtractorMOG2> MoG = createBackgroundSubtractorMOG2(500,25,false);

        HOGDescriptor hog;
        hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());

        CascadeClassifier cascade = CascadeClassifier(CASCADE_TO_USE);

    Ptr<SuperpixelSEEDS> seeds;

        // start main loop
      while(keepProcessing)
        {
          int64 timeStart = getTickCount();

            if (cap.isOpened())
          {
                cap >> img;

                if(img.empty())
                {
                    std::cerr << "End of video file reached" << std::endl;
                    exit(0);
                }
                outputImage = img.clone();

                cvtColor(img, img, CV_BGR2GRAY);
            }
          else
          {
              // if not a capture object set event delay to zero so it waits
              // indefinitely (as single image file, no need to loop)
              EVENT_LOOP_DELAY = 0;
          }

          // update background model and get background/foreground
          MoG->apply(img, foreground, (double)(1.0/learning));

          //imshow("old foreground", foreground);

/////////////////////////////////////////////////////////////////////////////////SUPERPIXELS
          int useSuperpixels = 0;

          if(useSuperpixels == 1)
            {
              Mat seedMask, labels, result;

              result = img.clone();

              int width = img.size().width;
            int height = img.size().height;

            seeds = createSuperpixelSEEDS(width, height, 1, 2000, 10, 2, 5, true);

          seeds->iterate(img, 10);

            seeds->getLabels(labels);

            vector<int> counter(seeds->getNumberOfSuperpixels(),0);
            vector<int> numberOfPixelsPerSuperpixel(seeds->getNumberOfSuperpixels(),0);

            vector<bool> useSuperpixel(seeds->getNumberOfSuperpixels(),false);

            for(int i = 0; i<foreground.rows; i++)
            {
                for(int j = 0; j<foreground.cols; j++)
                {
                    numberOfPixelsPerSuperpixel[labels.at<int>(i,j)] += 1;
                    if(foreground.at<unsigned char>(i,j)==255)
                    {
                        counter[labels.at<int>(i,j)] += 1;
                    }
                }
            }

            for(int i = 0; i<counter.size(); i++)
            {
                if(counter[i]/numberOfPixelsPerSuperpixel[i] > 0.0001)
                {
                    useSuperpixel[i] = true;
                }
            }

            for(int i = 0; i<foreground.rows; i++)
            {
                for(int j = 0; j<foreground.cols; j++)
                {
                    if(useSuperpixel[labels.at<int>(i,j)] == true)
                    {
                        foreground.at<unsigned char>(i,j) = 255;
                    }
                    else
                    {
                        foreground.at<unsigned char>(i,j) = 0;
                    }
                }
            }
            }
/////////////////////////////////////////////////////////////////////////////////
            else
            {
              // perform erosion - removes boundaries of foreground object
              erode(foreground, foreground, Mat(),Point(),1);

              // perform morphological closing
              dilate(foreground, foreground, Mat(),Point(),5);
              erode(foreground, foreground, Mat(),Point(),1);
            }
          //imshow("foreground", foreground);

          // get connected components from the foreground
          findContours(foreground, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

          // iterate through all the top-level contours,
          // and get bounding rectangles for them (if larger than given value)

          for(int idx = 0; idx >=0; idx = hierarchy[idx][0])
          {
                Rect r = boundingRect(contours[idx]);

                // adjust bounding rectangle to be padding% larger
                // around the object
                r.x = max(0, r.x - (int) (padding/100.0 * (double) r.width));
                r.y = max(0, r.y - (int) (padding/100.0 * (double) r.height));

                r.width = min(img.cols - 1, (r.width + 2 * (int) (padding/100.0 * (double) r.width)));
                r.height = min(img.rows - 1, (r.height + 2 * (int) (padding/100.0 * (double) r.height)));

                // draw rectangle if greater than width/height constraints and if
                // also still inside image
                if ((r.width >= width) && (r.height >= height) && (r.x + r.width < img.cols) && (r.y + r.height < img.rows))
                {
                  vector<Rect> found, found_filtered;

                  Mat roi = outputImage(r);

                  if (classifier == 1)
                  {
                        //changing last parameter helps deal with multiple rectangles per person
                        if (cameraID == 3)
                        {
                            hog.detectMultiScale(roi, found, 0, Size(8,8), Size(32,32), 1.05, 5);
                        }
                        else
                        {
                            hog.detectMultiScale(roi, found, 0, Size(8,8), Size(64,64), 1.05, 5);
                        }
                  }
                  else
                  {
                    if (cameraID == 3)
                    {
                        cascade.detectMultiScale(roi, found, 1.1, 4, CV_HAAR_DO_CANNY_PRUNING, cvSize(32,32));
                    }
                    else
                    {
                        cascade.detectMultiScale(roi, found, 1.1, 4, CV_HAAR_DO_CANNY_PRUNING, cvSize(64,64));
                    }
                  }

                  for(size_t i = 0; i < found.size(); i++ )
                  {
                        Rect rec = found[i];

                        rec.x += r.x;
                        rec.y += r.y;

                        size_t j;
                        // Do not add small detections inside a bigger detection.
                        for ( j = 0; j < found.size(); j++ )
                        {
                          if ( j != i && (rec & found[j]) == rec )
                          {
                              break;
                          }
                        }

                        if (j == found.size())
                        {
                          found_filtered.push_back(rec);
                        }
                  }
                  for (size_t i = 0; i < found_filtered.size(); i++)
                  {
                        Rect rec = found_filtered[i];

                        // The HOG/Cascade detector returns slightly larger rectangles than the real objects,
                        // so we slightly shrink the rectangles to get a nicer output.
                        rec.x += rec.width*0.1;
                        rec.width = rec.width*0.8;
                        rec.y += rec.height*0.1;
                        rec.height = rec.height*0.8;
                        // rectangle(img, rec.tl(), rec.br(), cv::Scalar(0,255,0), 3);

                        Point2f center = Point2f(float(rec.x + rec.width/2.0), float(rec.y + rec.height/2.0));

                        Mat regionOfInterest;

                        Mat regionOfInterestOriginal = img(rec);
                        //Mat regionOfInterestOriginal = img(r);

                        Mat regionOfInterestForeground  = foreground(rec);
                        //Mat regionOfInterestForeground = foreground(r);

                        bitwise_and(regionOfInterestOriginal, regionOfInterestForeground, regionOfInterest);

                        Mat clone = regionOfInterest.clone();

                        resize(clone, regionOfInterest, Size(64,128), CV_INTER_CUBIC);

                        imshow("roi", regionOfInterest);

                        double huMoments[7];
                        vector<double> hu(7);
                        Mat hist;
                        vector<float> descriptorsValues;

                        Mat feature;

                        if(featureToUse == 1) //HuMoments
                        {
                          vector<vector<Point> > contoursHu;
                          vector<Vec4i> hierarchyHu;

                          findContours(regionOfInterest, contoursHu, hierarchyHu, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

                          double largestSize,size;
                          int largestContour;

                          for(int i = 0; i < contoursHu.size(); i++)
                          {
                                size = contoursHu[i].size();

                                if(size > largestSize)
                                {
                                  largestSize = size;
                                  largestContour = i;
                                }
                          }
                          Moments contourMoments;

                          contourMoments = moments(contoursHu[largestContour]);

                          HuMoments(contourMoments, huMoments);

                          hu.assign(huMoments,huMoments+7);

              feature = Mat(hu);
              feature = feature.t();
                        }
                        else if(featureToUse == 2) //HistogramOfIntensities
                        {
                          int histSize = 16;    // bin size - need to determine which pixel threshold to use
                          float range[] = {0,255};
                          const float *ranges[] = {range};
                          int channels[] = {0, 1};

                          calcHist(&regionOfInterest, 1, channels, Mat(), hist, 1, &histSize, ranges, true, false);

                          feature = hist.clone();
                          feature = feature.t();
                        }

                        else if(featureToUse == 3) //HOG
                        {
                          //play with these parameters to change HOG size
                          cv::HOGDescriptor descriptor(Size(64, 128), Size(16, 16), Size(16, 16), Size(16, 16), 4, -1, 0.2, true, 64);

                          descriptor.compute(regionOfInterest, descriptorsValues);

                          feature = Mat(descriptorsValues);
                          feature = feature.t();
                        }

                        else if(featureToUse == 4) //Correlogram
                        {
                            Mat correlogram(8,8,CV_64F);
                            Mat occurances(8,8,CV_8U);

                            int xIntensity, yIntensity;

                            for(int i = 0; i<regionOfInterest.rows; i++)
                            {
                                for(int j = 0; j<regionOfInterest.cols; j++)
                                {
                                    xIntensity = floor(regionOfInterest.at<unsigned char>(i,j)/32);

                                    for(int k = i; k<regionOfInterest.rows; k++)
                                    {
                                        for(int l = 0; l<regionOfInterest.cols; l++)
                                        {
                                            if((k == i && l > j) || k > i)
                                            {
                                                yIntensity = floor(regionOfInterest.at<unsigned char>(k,l)/32);

                                                correlogram.at<double>(xIntensity,yIntensity) += (norm(Point(i,j)-Point(k,l)));
                                                correlogram.at<double>(yIntensity,xIntensity) += (norm(Point(i,j)-Point(k,l)));

                                                occurances.at<unsigned char>(xIntensity,yIntensity) += 1;
                                                occurances.at<unsigned char>(yIntensity,xIntensity) += 1;
                                            }
                                        }
                                    }
                                }
                            }
                            //average it out
                            for(int i = 0; i<correlogram.rows; i++)
                            {
                                for(int j = 0; j<correlogram.cols; j++)
                                {
                                    correlogram.at<double>(i,j) = occurances.at<unsigned char>(i,j);
                                }
                            }

                            feature = correlogram.reshape(1,1);
                        }
                        else if(featureToUse == 5) //Flow
                        {

                        }

                        feature.convertTo(feature, CV_64F);

                        normalize(feature, feature, 1, 0, NORM_L1, -1, Mat());
                        cout << "New Feature" << endl << feature << endl;

                        //classify first target
                        if(targets.size() == 0) //if first target found
                        {
                          Person person(0, center.x, center.y, timeSteps, rec.width, rec.height);

                          person.kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                          Rect p = person.kalmanPredict();

                          person.updateFeatures(feature);

                          person.setCurrentCamera(cameraID);

                          rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                          char str[200];
                          sprintf(str,"Person %d",person.getIdentifier());

                          putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));

                          targets.push_back(person);
                        }
                        else
                        {
                            vector<double> mDistances;
                            bool singleEntry = false;

                            for(int i = 0; i<targets.size(); i++)
                            {
                                if(targets[i].getFeatures().rows == 1)
                                {
                                    singleEntry = true;
                                }
                            }

                            for(int i = 0; i<targets.size(); i++)
                            {
                                Mat covar, mean;
                                Mat data = targets[i].getFeatures();

                                calcCovarMatrix(data,covar,mean,CV_COVAR_NORMAL|CV_COVAR_ROWS);

                                // cout << i << " data" << endl << data << endl;

                                // cout << i << " Covar" << endl << covar << endl;

                                // cout << i << " mean" << endl << mean << endl;

                                double mDistance;

                                if(singleEntry == false)
                                {
                                    Mat invCovar;

                                    invert(covar,invCovar,DECOMP_SVD);

                                    mDistance = Mahalanobis(feature,mean,invCovar);

                                    cout << i << " Mahalanobis Distance" << endl << mDistance << endl;
                                }
                                else
                                {
                                    mDistance = norm(feature,mean,NORM_L1);

                                    cout << i << " Norm Distance" << endl << mDistance << endl;
                                }
                                mDistances.push_back(mDistance);
                            }

                            Mat test = Mat(mDistances);
                            cout << "Distances" << endl << test << endl;

                            double sum = 0.0;
                            for(int i = 0; i<mDistances.size(); i++)
                            {
                                sum += mDistances[i];
                            }
                            for(int i = 0; i<mDistances.size(); i++)
                            {
                                mDistances[i] = sum/mDistances[i];
                            }

                            normalize(mDistances,mDistances,1,0,NORM_L1,-1,Mat());

                            Mat probabilities = Mat(mDistances);

                            cout << "Probabilities" << endl << probabilities << endl;

                            //special case to classify second target
                        if(targets.size() == 1)
                        {
                            if(fabs(center.x-targets[0].getLastPosition().x)<100 and fabs(center.y-targets[0].getLastPosition().y)<100)
                            {
                                targets[0].kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                                  Rect p = targets[0].kalmanPredict();

                                targets[0].updateFeatures(feature);

                                targets[0].setCurrentCamera(cameraID);

                                  rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                                  char str[200];
                                  sprintf(str,"Person %d",targets[0].getIdentifier());

                                  putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));
                            }
                            else
                            {
                                Person person(1, center.x, center.y, timeSteps, rec.width, rec.height);

                                  person.kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                                  Rect p = person.kalmanPredict();

                                person.updateFeatures(feature);

                                person.setCurrentCamera(cameraID);

                                  rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                                  char str[200];
                                  sprintf(str,"Person %d",person.getIdentifier());

                                  putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));

                                  targets.push_back(person);
                            }
                        }

                        else
                        {
                            double greatestProbability = 0.0;
                            int identifier = 0;

                            double min, max;
                                Point min_loc, max_loc;
                                minMaxLoc(probabilities, &min, &max, &min_loc, &max_loc);

                                greatestProbability = max;
                                identifier = max_loc.y;

                                cout << greatestProbability << " at " << identifier << endl;

                            if(greatestProbability >= 0.5)
                            {
                                targets[identifier].kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                                  Rect p = targets[identifier].kalmanPredict();

                                targets[identifier].updateFeatures(feature);

                                targets[identifier].setCurrentCamera(cameraID);

                                  rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                                  char str[200];
                                  sprintf(str,"Person %d",targets[identifier].getIdentifier());

                                  putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));
                            }
                            else
                            {
                                int identifier = targets.size();
                                  Person person(identifier, center.x, center.y, timeSteps, rec.width, rec.height);

                                  person.kalmanCorrect(center.x, center.y, timeSteps, rec.width, rec.height);

                                  Rect p = person.kalmanPredict();

                                person.updateFeatures(feature);

                                person.setCurrentCamera(cameraID);

                                  rectangle(outputImage, p.tl(), p.br(), cv::Scalar(255,0,0), 3);

                                  char str[200];
                                  sprintf(str,"Person %d",person.getIdentifier());

                                  putText(outputImage, str, center, FONT_HERSHEY_SIMPLEX,1,(0,0,0));

                                  targets.push_back(person);
                            }
                        }
                    }
                  }
                  rectangle(outputImage, r, Scalar(0,0,255), 2, 8, 0);
                }
          }
          // display image in window
          imshow(windowName, outputImage);

      key = waitKey((int) std::max(2.0, EVENT_LOOP_DELAY - (((getTickCount() - timeStart) / getTickFrequency())*1000)));

      if (key == 'x')
    {
            // if user presses "x" then exit
            std::cout << "Keyboard exit requested : exiting now - bye!" << std::endl;
            keepProcessing = false;
      }
      timeSteps += 1;
      }
      // the camera will be deinitialized automatically in VideoCapture destructor
      // all OK : main returns 0
      return 0;
    }
    // not OK : main returns -1
    return -1;
}


来源: stackexchange

问:
What features of Scala cannot be translated to Java?
The Scala compiler compiles direct to Java byte code (or .NET CIL). Some of the features of Scala could be re-done in Java straightforwardly (e.g. simple for comprehensions, classes, translating anonymous/inner functionc etc). What are the features that cannot be translated that way?

That is presumably mostly of academic interest. More usefully, perhaps, what are the key features or idioms of Scala that YOU use that cannot be easily represented in Java?

Are there any the other way about? Things that can be done straightforwardly in Java that have no straightforward equivalent in Scala? Idioms in Java that don't translate?

答: Three words: higher kinded types.</p>

ContentLicense: CC BY-SA 2.5

Body: Three words: higher kinded types.


问:
Unable to understand this code [JavaScript , Dates and Obtaining TimeZones]
Please help me to understand this code :-

```<code>function seconds_with_leading_zeros(dt)
{
  return /\((.*)\)/.exec(new Date().toString())[1];
}

dt = new Date();
console.log(seconds_with_leading_zeros(dt));

dt = new Date(1989, 10, 1);
console.log(seconds_with_leading_zeros(dt));
</code>```

It is suppose to show user's time zone.

答:
new Date().toString() returns a string like "Wed Mar 29 2017 15:37:26 GMT+0200 (West-Europa (zomertijd))" The timezone is inside the round brackets ().

return /\((.*)\)/.exec("date and time (timezone)")[1]; returns whatever is inside the brackets. In this case it will return the word "timezone"

That's as good as i can explain it :)

ContentLicense: CC BY-SA 3.0

Body:
Please help me to understand this code :-

function seconds_with_leading_zeros(dt)
{
  return /\((.*)\)/.exec(new Date().toString())[1];
}

dt = new Date();
console.log(seconds_with_leading_zeros(dt));

dt = new Date(1989, 10, 1);
console.log(seconds_with_leading_zeros(dt));

It is suppose to show user's time zone.


问:
IBM Cognos DB2 configuration
I'm trying to configure IBM Cognos 10.2.1 with IBM DB2 - 10.5.1 on AIX 7.1. The default installation (in cogstartup.xml) of Cognos comes with Derby database. Cognos with default configuration starts successfully. Dispatcher page comes up but with an error that indicates that Content Store (i.e. Derby) is not available.

However, if I replace the database with DB2, Cognos does not start properly i.e. dispatcher URL is inaccessible.

Can you please see what can be the issue?

答: You might need to copy db2 jar files to cognos lib folder when you change the database from Derby to DB2, directly edit the cogstartup.xml with DB2 data configurations.

Title: IBM Cognos DB2 configuration


问:
How to save a dynamic web page (Cordova App)
I created an App for projects and To Do lists. It consists of one HTML page, which only has an "add To Do list"-button.
The user can click on that button and create a To Do list, in this list he can create tasks.
The lists and tasks are dynamically generated HTML Elements.

Is there a way to just store everything, the dynamically generated DOM and all its elements and their functions? I searched for an answer for hours and all I found was a method to store data locally with  localStorage: http://docs.phonegap.com/en/1.2.0/phonegap_storage_storage.md.html#localStorage

Since my elements contain a lot of js functions, it would be very complicated to store everything with this method...
Is there no way of storing "the whole thing"?
Thanks in advance!

答:
Your question require a very large explanation, anyway I would tell you some tips you can use to step forward since I worked on a similar app last year.

Think about a database structure for your app. I got a table "Tasks" in which I stored both tasks and subtasks (task inside other tasks). I also stored alarms (if a task need an alarm), texts, checked/unchecked, archived flag, deleted flag, and so on. Everything you can associate to a task, you need a column for it.

Think about your data amount globally. If you plan to store a large amount of data (more or less 5MB) you better choose SQLite approach. If you think your data will not reach this edge, think about LocalStorage. You can google both to manage their use.

When the user fill the DOM to create a task and click on "create" (or something similar), you have to "scan" the DOM, acquire all info for the task created and put them into your DB

When the user want to update/modify a task, you have to find it in the DB, fetch related data, create the DOM's structures you need to show data, fill the structures with data

These are more or less few tips I can give you on your long way. Good luck


问:
Expand tree nodes with right and left arrow keys on Eclipse
I have a problem with the right and left keys on Eclipse. Until now, I have used Eclipse on Windows platform and it lets me open the child elements when I clicked on the right arrow key and it closed the child elements with the left arrow key. I switched to the Ubuntu and these keys do not open/close the child elements anymore on Eclipse.

This is the default case:

and then, when I clicked on right arrow key, it opened the child elements like that;

After clicking on right arrow key:

Even if I looked the keys in the settings, I could not find the shortcut entry for this behaviour in the settings of the Eclipse.

答:
I do not know which shortcut entry in Eclipse but when you use the Eclipse on Ubuntu, you can get the same behaviour with shift + left/right arrow keys instead of onyl left/right arrow keys.

In order to change the behaviour on Ubuntu, please have a look at this post and the answer of @big data nerd should work on newer versions of Ubuntu (tested)

I hope this helps.


问:
How modify css for chat application layout especially fixed footer part
I want to create a chat application where will be the header with menu and bellow chat box with some messages and on the bottom the fixed part with input for inserting the chat message.

I've tried create the demo of this layout:

https://jsfiddle.net/6dchq2zq/2/

But I don't know how can I fix following issues:

1.) How calculate the height of the content where are messages and according these height show the scollbar. I've tried put the static value - for the demo.

2.) How create fixed bottom part with input which will be responsive

.chat-item{
      background-color: #ffe1e1;
      margin-top: 10px;
      margin-bottom: 10px;
      border-radius: 30px;
      padding: 50px;
    }

    .chat-footer{
      background-color: #dfeeff;
      padding: 10px;
    }

    .chat-box{
      height: 500px;
      overflow: auto;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
     <div class="chat-box row">
       <div class="col-md-12 chat-item">
        Test Message 1
       </div>

       <div class="col-md-12 chat-item">
        Test Message 2
       </div>

       <div class="col-md-12 chat-item">
        Test Message 3
       </div>

       <div class="col-md-12 chat-item">
        Test Message 4
       </div>
     </div>
    </div>

     <div class="chat-footer">
       <div class="container">
         <input class="form-control" type="text" placeholder="Message" />
       </div>
     </div></code>```

答:
I quickly added a couple lines of css

Here's a jsfiddle: https://jsfiddle.net/6dchq2zq/7/

```<code> .navbar {
    position: fixed;
    width: 100%;
 }

 .chat-footer {
    background-color: #dfeeff;
    padding: 10px;
    position: fixed;
    bottom: 0;
    width: 100%;
 }

 .chat-box {
   height: 100%;
   overflow: auto;
   overflow-x: hidden;
   padding: 60px 0;
 }
</code>```

Body:
I want to create a chat application where will be the header with menu and bellow chat box with some messages and on the bottom the fixed part with input for inserting the chat message.

I've tried create the demo of this layout:

https://jsfiddle.net/6dchq2zq/2/

But I don't know how can I fix following issues:

1.) How calculate the height of the content where are messages and according these height show the scollbar. I've tried put the static value - for the demo.

2.) How create fixed bottom part with input which will be responsive

.chat-item{
      background-color: #ffe1e1;
      margin-top: 10px;
      margin-bottom: 10px;
      border-radius: 30px;
      padding: 50px;
    }

    .chat-footer{
      background-color: #dfeeff;
      padding: 10px;
    }

    .chat-box{
      height: 500px;
      overflow: auto;
    }

        Test Message 1

        Test Message 2

        Test Message 3

        Test Message 4

         <input class="form-control" type="text" placeholder="Message" />

Body:
I quickly added a couple lines of css

Here's a jsfiddle: https://jsfiddle.net/6dchq2zq/7/

 .navbar {
    position: fixed;
    width: 100%;
 }

 .chat-footer {
    background-color: #dfeeff;
    padding: 10px;
    position: fixed;
    bottom: 0;
    width: 100%;
 }

 .chat-box {
   height: 100%;
   overflow: auto;
   overflow-x: hidden;
   padding: 60px 0;
 }


问:
HTML.link from a frame to another opens in new window?How can i fix it?
i want to have a link in frame a and open in frame b without opening new window.

heres my code:

```<code><html>
<base target="main.htm">
<body>
  <body link="blue" vlink="rgb(255,200,0)" alink="green" style="background-color:rgb(255,30,15)">
    <h2><b>ΠΕΡΙΕΧΟΜΕΝΑ</b></h2>
    <a href="personal.htm" target="main" border="0">ΠΡΟΣΩΠΙΚΑ ΣΤΟΙΧΕΙΑ </a><br/>
  <body/>
<html/>
</code>```

答:
Firstly I would suggest a valid doctype declaration, unless of course you're going for HTML5.

Secondly, I would suggest your enclose your <base> tag inside  tag

Thirdly, if you're using either XHTML or HTML 5 (as it seems you're currently doing), you will need to close your <base> tag with </base>

As for answering your actual question, you'll need to use the target attribute, as follows:

```<code><base target="main.htm" target="_parent">
</code>```

Please note that, as far as I know you can't have a link from Frame A open in Frame B, unless it's a parent frame - if you understand what I mean. To get a full understanding of what the target attribute does, check out this link.

Body:
i want to have a link in frame a and open in frame b without opening new window.

heres my code:

<base target="main.htm">

ΠΕΡΙΕΧΟΜΕΝΑ

    ΠΡΟΣΩΠΙΚΑ ΣΤΟΙΧΕΙΑ

Body:
Firstly I would suggest a valid doctype declaration, unless of course you're going for HTML5.

Secondly, I would suggest your enclose your <base> tag inside <head></head> tag

Thirdly, if you're using either XHTML or HTML 5 (as it seems you're currently doing), you will need to close your <base> tag with </base>

As for answering your actual question, you'll need to use the target attribute, as follows:

<base target="main.htm" target="_parent">

Please note that, as far as I know you can't have a link from Frame A open in Frame B, unless it's a parent frame - if you understand what I mean. To get a full understanding of what the target attribute does, check out this link.


问:
Using php.net's password_verify" script as offered works, but fails if hash is read back from DB
php.net script: http://php.net/manual/en/function.password-hash.php
and: http://php.net/manual/en/function.password-verify.php

The apparent simplicity of this password verification routine is very appealing, but after a day of reading at stackoverflow and innumerable hacks, here is my very simple, not-at-all-secure, testing version:

```<code><?php

$p = "bumblebee";
$hash =  (password_hash($p, PASSWORD_DEFAULT));

echo ($p);
echo ($hash);

if (password_verify('bumblebee', $hash)) {
    echo 'Password is valid!';
    } else {
    echo 'Invalid password.';
    }

?>
</code>```

ABOVE RETURNS 'Password is valid!' (this is two scripts from PHP.net combined)

BELOW DOES NOT WORK (only diff is the hash is written to DB and read back, then converted to a string)

```<code><?php

$userName = $_REQUEST["userName"];
$passWord = $_REQUEST["passWord"];

// $p = "$passWord";
// $hash =  (password_hash($p, PASSWORD_DEFAULT));

    //set DB access variables
    require_once('./php/hs_DBlogin.php');

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $passWord_get = mysqli_query($conn, "SELECT passWordHash FROM hsUser WHERE userName='$userName' LIMIT 1");
    $passWord_out = mysqli_fetch_array($passWord_get);
    $hashAsStr = $passWord_out[0];

    echo ($hashAsStr);
    echo ($_REQUEST["passWord"]);

if (password_verify($_REQUEST["passWord"], $hashAsStr)) {
    echo 'Password is valid!';
    } else {
    echo 'Invalid password.';
    }

?>

Here is the insert to DB script:

// Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$passWordHash = password_hash('$passWord', PASSWORD_DEFAULT);

$sql = "INSERT INTO `hsUser`(`firstName`, `lastName`, `userName`, `passWordHash`,`hsStatus`) VALUES ('$firstName','$lastName','$userName','$passWordHash','$hsStatus')";
</code>```

答:
Gave up on php's password_verify and used sha1
script at:
http://www.localwisdom.com/blog/2013/03/building-a-simple-registerlogin-system-in-php-using-sha256/
after some clean-up, works fine</p>

Body:
php.net script: http://php.net/manual/en/function.password-hash.php
and: http://php.net/manual/en/function.password-verify.php

The apparent simplicity of this password verification routine is very appealing, but after a day of reading at stackoverflow and innumerable hacks, here is my very simple, not-at-all-secure, testing version:

<?php

$p = "bumblebee";
$hash =  (password_hash($p, PASSWORD_DEFAULT));

echo ($p);
echo ($hash);

if (password_verify('bumblebee', $hash)) {
    echo 'Password is valid!';
    } else {
    echo 'Invalid password.';
    }

?>

ABOVE RETURNS 'Password is valid!' (this is two scripts from PHP.net combined)

BELOW DOES NOT WORK (only diff is the hash is written to DB and read back, then converted to a string)

<?php

$userName = $_REQUEST["userName"];
$passWord = $_REQUEST["passWord"];

// $p = "$passWord";
// $hash =  (password_hash($p, PASSWORD_DEFAULT));

    //set DB access variables
    require_once('./php/hs_DBlogin.php');

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $passWord_get = mysqli_query($conn, "SELECT passWordHash FROM hsUser WHERE userName='$userName' LIMIT 1");
    $passWord_out = mysqli_fetch_array($passWord_get);
    $hashAsStr = $passWord_out[0];

    echo ($hashAsStr);
    echo ($_REQUEST["passWord"]);

if (password_verify($_REQUEST["passWord"], $hashAsStr)) {
    echo 'Password is valid!';
    } else {
    echo 'Invalid password.';
    }

?>

Here is the insert to DB script:

// Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$passWordHash = password_hash('$passWord', PASSWORD_DEFAULT);

$sql = "INSERT INTO `hsUser`(`firstName`, `lastName`, `userName`, `passWordHash`,`hsStatus`) VALUES ('$firstName','$lastName','$userName','$passWordHash','$hsStatus')";


问:
Most efficient way to check if object value exists in PHP 7
I have the following object in PHP 7:

```<code>(int) 0 => object() {
   'master' => null
},
(int) 1 => object() {
   'master' => true
},
(int) 2 => object() {
   'master' => null
},
</code>```

What is the most efficient way to check whether master is true in any key of that object?

I could loop through the object and then set a variable, e.g.

```<code>$master = 0;
foreach ($obj as $key => $value) {
    if ($value->master) {
       $master++;
    }
}
if ($master !== 0) {

}
</code>```

But this seems inefficient.

The object itself has other data in each node, this is a simplified example.

What I'm trying to write, in as few lines as possible is, does any part of this object have master == true? Or, looking at it the other way round, are all my master nodes set to null on this object? A return of true or false would probably suffice as the output, although a count would also be ok.

答:
Use triple equal</p>

```<code>if ($value->master === TRUE) {
   // your code here
}
</code>```

Body:
I have the following object in PHP 7:

(int) 0 => object() {
   'master' => null
},
(int) 1 => object() {
   'master' => true
},
(int) 2 => object() {
   'master' => null
},

What is the most efficient way to check whether master is true in any key of that object?

I could loop through the object and then set a variable, e.g.

$master = 0;
foreach ($obj as $key => $value) {
    if ($value->master) {
       $master++;
    }
}
if ($master !== 0) {

}

But this seems inefficient.

The object itself has other data in each node, this is a simplified example.

What I'm trying to write, in as few lines as possible is, does any part of this object have master == true? Or, looking at it the other way round, are all my master nodes set to null on this object? A return of true or false would probably suffice as the output, although a count would also be ok.

Body:
Use triple equal

if ($value->master === TRUE) {
   // your code here
}


问:
Get current datetime in odoo 9
How in defaults get current datetime and current datetime + 1 hour?

For date I use below example:

```<code>defaults = {
                 'start': fields.Date.today(),
                 'finish': fields.Date.today(),
}
</code>```

答:
for the new api in odoo there is a default option in the fields, and you can create a function to set the default option two

```<code>start = fields.Datetime('Date', default=fields.Datetime.now,)
finish = fields.Datetime('Date', default='_get_finish_date',)

from datetime import datetime , timedelta
@api.one
def _get_finish_date(self):
    return  datetime.now() + timedelta(hours=1)
</code>```

Title: Get current datetime in odoo 9

Body:
How in defaults get current datetime and current datetime + 1 hour?

For date I use below example:

defaults = {
                 'start': fields.Date.today(),
                 'finish': fields.Date.today(),
}

Body:
for the new api in odoo there is a default option in the fields, and you can create a function to set the default option two

start = fields.Datetime('Date', default=fields.Datetime.now,)
finish = fields.Datetime('Date', default='_get_finish_date',)

from datetime import datetime , timedelta
@api.one
def _get_finish_date(self):
    return  datetime.now() + timedelta(hours=1)


问:
ServerSocket accept() method
Who knows how the port is chosen when I'm using accept method of ServerSocket class? Is it possible to define a range for the ports the method can choose from? Can I 'take' ports one by one just in order?

```<code>ServerSocket sSocket = new ServerSocket(5050);
Socket socket = sSocket.accept();
</code>```

答: You chose the port, when you said new ServerSocket(5050). All that stuff about using a different port for the accepted socket is 100% BS.

Title: ServerSocket accept() method

Body:
Who knows how the port is chosen when I'm using accept method of ServerSocket class? Is it possible to define a range for the ports the method can choose from? Can I 'take' ports one by one just in order?

ServerSocket sSocket = new ServerSocket(5050);
Socket socket = sSocket.accept();


问:
MongoDB secondary completely unable to keep up
We have set up a three member replica set consisting of the following, all on MongoDB version 3.4:

Primary. Physical local server, Windows Server 2012, 64 GB RAM, 6 cores. Hosted in Scandinavia.

Secondary. Amazon EC2, Windows Server 2016, m4.2xlarge, 32 GB RAM, 8 vCPUs. Hosted in Germany.

Arbiter. Tiny cloud based Linux instance.

The problem we are seeing is that the secondary is unable to keep up with the primary. As we seed it with data (copy over from the primary) and add it to the replica set, it typically manages to get in sync, but an hour later it might lag behind by 10 minutes; a few hours later, it's an hour behind, and so on, until a day or two later, it goes stale.

We are trying to figure out why this is. The primary is consistently using 0-1% CPU, while the secondary is under constant heavy load at 20-80% CPU. This seems to be the only potential resource constraint. Disk and network load does not seem to be an issue. There seems to be some locking going on on the secondary, as operations in the mongo shell (such as db.getReplicationInfo()) frequently takes 5 minutes or more to complete, and mongostat rarely works (it just says i/o timeout). Here is output from mongostat during a rare instance when it reported stats for the secondary:

```<code>                   host insert query update delete getmore command dirty  used flushes vsize   res qrw  arw net_in net_out conn set repl                time
        localhost:27017     *0    33    743     *0       0   166|0  1.0% 78.7%       0 27.9G 27.0G 0|0  0|1  2.33m    337k  739  rs  PRI Mar 27 14:41:54.578
  primary.XXX.com:27017     *0    36    825     *0       0   131|0  1.0% 78.7%       0 27.9G 27.0G 0|0  0|0  1.73m    322k  739  rs  PRI Mar 27 14:41:53.614
secondary.XXX.com:27017     *0    *0     *0     *0       0   109|0  4.3% 80.0%       0 8.69G 7.54G 0|0 0|10  6.69k    134k  592  rs  SEC Mar 27 14:41:53.673
</code>```

I ran db.serverStatus() on the secondary, and compared to the primary, and one number that stood out was the following:

"locks" : {"Global" : {"timeAcquiringMicros" : {"r" : NumberLong("21188001783")

The secondary had an uptime of 14000 seconds at the time.

Would appreciate any ideas on what this could be, or how to debug this issue! We could upgrade the Amazon instance to something beefier, but we've done that three times already, and at this point we figure that something else must be wrong.

I'll include output from db.currentOp() on the secondary below, in case it helps. (That command took 5 minutes to run, after which the following was logged: Restarting oplog query due to error: CursorNotFound: Cursor not found, cursor id: 15728290121. Last fetched optime (with hash): { ts: Timestamp 1490613628000|756, t: 48 }[-5363878314895774690]. Restarts remaining: 3)

```
"desc":"conn605",
"connectionId":605,"client":"127.0.0.1:61098",
"appName":"MongoDB Shell",
"secs_running":0,
"microsecs_running":NumberLong(16),
"op":"command",
"ns":"admin.$cmd",
"query":{"currentOp":1},
"locks":{},
"waitingForLock":false,
"lockStats":{}

"desc":"repl writer worker 10",
"secs_running":0,
"microsecs_running":NumberLong(14046),
"op":"none",
"ns":"CustomerDB.ed2112ec779f",
"locks":{"Global":"W","Database":"W"},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"w":NumberLong(1),"W":NumberLong(1)}},"Database":{"acquireCount":{"W":NumberLong(1)}}}

"desc":"ApplyBatchFinalizerForJournal",
"op":"none",
"ns":"",
"locks":{},
"waitingForLock":false,
"lockStats":{}

"desc":"ReplBatcher",
"secs_running":11545,
"microsecs_running":NumberLong("11545663961"),
"op":"none",
"ns":"local.oplog.rs",
"locks":{},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(2)}},"Database":{"acquireCount":{"r":NumberLong(1)}},"oplog":{"acquireCount":{"r":NumberLong(1)}}}

"desc":"rsBackgroundSync",
"secs_running":11545,
"microsecs_running":NumberLong("11545281690"),
"op":"none",
"ns":"local.replset.minvalid",
"locks":{},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(5),"w":NumberLong(1)}},"Database":{"acquireCount":{"r":NumberLong(2),"W":NumberLong(1)}},"Collection":{"acquireCount":{"r":NumberLong(2)}}}

"desc":"TTLMonitor",
"op":"none",
"ns":"",
"locks":{"Global":"r"},
"waitingForLock":true,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(35)},"acquireWaitCount":{"r":NumberLong(2)},"timeAcquiringMicros":{"r":NumberLong(341534123)}},"Database":{"acquireCount":{"r":NumberLong(17)}},"Collection":{"acquireCount":{"r":NumberLong(17)}}}

"desc":"SyncSourceFeedback",
"op":"none",
"ns":"",
"locks":{},
"waitingForLock":false,
"lockStats":{}

"desc":"WT RecordStoreThread: local.oplog.rs",
"secs_running":1163,
"microsecs_running":NumberLong(1163137036),
"op":"none",
"ns":"local.oplog.rs",
"locks":{},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(1),"w":NumberLong(1)}},"Database":{"acquireCount":{"w":NumberLong(1)}},"oplog":{"acquireCount":{"w":NumberLong(1)}}}

"desc":"rsSync",
"secs_running":11545,
"microsecs_running":NumberLong("11545663926"),
"op":"none",
"ns":"local.replset.minvalid",
"locks":{"Global":"W"},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(272095),"w":NumberLong(298255),"R":NumberLong(1),"W":NumberLong(74564)},"acquireWaitCount":{"W":NumberLong(3293)},"timeAcquiringMicros":{"W":NumberLong(17685)}},"Database":{"acquireCount":{"r":NumberLong(197529),"W":NumberLong(298255)},"acquireWaitCount":{"W":NumberLong(146)},"timeAcquiringMicros":{"W":NumberLong(651947)}},"Collection":{"acquireCount":{"r":NumberLong(2)}}}

"desc":"clientcursormon",
"secs_running":0,
"microsecs_running":NumberLong(15649),
"op":"none",
"ns":"CustomerDB.b72ac80177ef",
"locks":{"Global":"r"},
"waitingForLock":true,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(387)},"acquireWaitCount":{"r":NumberLong(2)},"timeAcquiringMicros":{"r":NumberLong(397538606)}},"Database":{"acquireCount":{"r":NumberLong(193)}},"Collection":{"acquireCount":{"r":NumberLong(193)}}}}],"ok":1}
```

答:
JJussi was exactly right (thanks!). The problem was that the active data is bigger than the memory available, and we were using Amazon EBS "Throughput Optimized HDD". We changed this to "General Purpose SSD" and the problem immediately went away. We were even able to downgrade the server from m4.2xlarge to m4.large.

We were confused by the fact that this manifested as high CPU load. We thought disk load was not an issue based on the fairly low amount of data written to disk per second. But when we tried making the AWS server the primary instance, we noticed that there was a very strong correlation between high CPU load and disk queue length. Further testing on the disk showed that it had very bad performance for the type of traffic that Mongo has.

Body:
We have set up a three member replica set consisting of the following, all on MongoDB version 3.4:

Primary. Physical local server, Windows Server 2012, 64 GB RAM, 6 cores. Hosted in Scandinavia.

Secondary. Amazon EC2, Windows Server 2016, m4.2xlarge, 32 GB RAM, 8 vCPUs. Hosted in Germany.

Arbiter. Tiny cloud based Linux instance.

The problem we are seeing is that the secondary is unable to keep up with the primary. As we seed it with data (copy over from the primary) and add it to the replica set, it typically manages to get in sync, but an hour later it might lag behind by 10 minutes; a few hours later, it's an hour behind, and so on, until a day or two later, it goes stale.

We are trying to figure out why this is. The primary is consistently using 0-1% CPU, while the secondary is under constant heavy load at 20-80% CPU. This seems to be the only potential resource constraint. Disk and network load does not seem to be an issue. There seems to be some locking going on on the secondary, as operations in the mongo shell (such as db.getReplicationInfo()) frequently takes 5 minutes or more to complete, and mongostat rarely works (it just says i/o timeout). Here is output from mongostat during a rare instance when it reported stats for the secondary:

                   host insert query update delete getmore command dirty  used flushes vsize   res qrw  arw net_in net_out conn set repl                time
        localhost:27017     *0    33    743     *0       0   166|0  1.0% 78.7%       0 27.9G 27.0G 0|0  0|1  2.33m    337k  739  rs  PRI Mar 27 14:41:54.578
  primary.XXX.com:27017     *0    36    825     *0       0   131|0  1.0% 78.7%       0 27.9G 27.0G 0|0  0|0  1.73m    322k  739  rs  PRI Mar 27 14:41:53.614
secondary.XXX.com:27017     *0    *0     *0     *0       0   109|0  4.3% 80.0%       0 8.69G 7.54G 0|0 0|10  6.69k    134k  592  rs  SEC Mar 27 14:41:53.673

I ran db.serverStatus() on the secondary, and compared to the primary, and one number that stood out was the following:

"locks" : {"Global" : {"timeAcquiringMicros" : {"r" : NumberLong("21188001783")

The secondary had an uptime of 14000 seconds at the time.

Would appreciate any ideas on what this could be, or how to debug this issue! We could upgrade the Amazon instance to something beefier, but we've done that three times already, and at this point we figure that something else must be wrong.

I'll include output from db.currentOp() on the secondary below, in case it helps. (That command took 5 minutes to run, after which the following was logged: Restarting oplog query due to error: CursorNotFound: Cursor not found, cursor id: 15728290121. Last fetched optime (with hash): { ts: Timestamp 1490613628000|756, t: 48 }[-5363878314895774690]. Restarts remaining: 3)

"desc":"conn605",
"connectionId":605,"client":"127.0.0.1:61098",
"appName":"MongoDB Shell",
"secs_running":0,
"microsecs_running":NumberLong(16),
"op":"command",
"ns":"admin.$cmd",
"query":{"currentOp":1},
"locks":{},
"waitingForLock":false,
"lockStats":{}

"desc":"repl writer worker 10",
"secs_running":0,
"microsecs_running":NumberLong(14046),
"op":"none",
"ns":"CustomerDB.ed2112ec779f",
"locks":{"Global":"W","Database":"W"},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"w":NumberLong(1),"W":NumberLong(1)}},"Database":{"acquireCount":{"W":NumberLong(1)}}}

"desc":"ApplyBatchFinalizerForJournal",
"op":"none",
"ns":"",
"locks":{},
"waitingForLock":false,
"lockStats":{}

"desc":"ReplBatcher",
"secs_running":11545,
"microsecs_running":NumberLong("11545663961"),
"op":"none",
"ns":"local.oplog.rs",
"locks":{},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(2)}},"Database":{"acquireCount":{"r":NumberLong(1)}},"oplog":{"acquireCount":{"r":NumberLong(1)}}}

"desc":"rsBackgroundSync",
"secs_running":11545,
"microsecs_running":NumberLong("11545281690"),
"op":"none",
"ns":"local.replset.minvalid",
"locks":{},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(5),"w":NumberLong(1)}},"Database":{"acquireCount":{"r":NumberLong(2),"W":NumberLong(1)}},"Collection":{"acquireCount":{"r":NumberLong(2)}}}

"desc":"TTLMonitor",
"op":"none",
"ns":"",
"locks":{"Global":"r"},
"waitingForLock":true,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(35)},"acquireWaitCount":{"r":NumberLong(2)},"timeAcquiringMicros":{"r":NumberLong(341534123)}},"Database":{"acquireCount":{"r":NumberLong(17)}},"Collection":{"acquireCount":{"r":NumberLong(17)}}}

"desc":"SyncSourceFeedback",
"op":"none",
"ns":"",
"locks":{},
"waitingForLock":false,
"lockStats":{}

"desc":"WT RecordStoreThread: local.oplog.rs",
"secs_running":1163,
"microsecs_running":NumberLong(1163137036),
"op":"none",
"ns":"local.oplog.rs",
"locks":{},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(1),"w":NumberLong(1)}},"Database":{"acquireCount":{"w":NumberLong(1)}},"oplog":{"acquireCount":{"w":NumberLong(1)}}}

"desc":"rsSync",
"secs_running":11545,
"microsecs_running":NumberLong("11545663926"),
"op":"none",
"ns":"local.replset.minvalid",
"locks":{"Global":"W"},
"waitingForLock":false,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(272095),"w":NumberLong(298255),"R":NumberLong(1),"W":NumberLong(74564)},"acquireWaitCount":{"W":NumberLong(3293)},"timeAcquiringMicros":{"W":NumberLong(17685)}},"Database":{"acquireCount":{"r":NumberLong(197529),"W":NumberLong(298255)},"acquireWaitCount":{"W":NumberLong(146)},"timeAcquiringMicros":{"W":NumberLong(651947)}},"Collection":{"acquireCount":{"r":NumberLong(2)}}}

"desc":"clientcursormon",
"secs_running":0,
"microsecs_running":NumberLong(15649),
"op":"none",
"ns":"CustomerDB.b72ac80177ef",
"locks":{"Global":"r"},
"waitingForLock":true,
"lockStats":{"Global":{"acquireCount":{"r":NumberLong(387)},"acquireWaitCount":{"r":NumberLong(2)},"timeAcquiringMicros":{"r":NumberLong(397538606)}},"Database":{"acquireCount":{"r":NumberLong(193)}},"Collection":{"acquireCount":{"r":NumberLong(193)}}}}],"ok":1}


问:
Writing to file only writes last item, not all items, why?
i'm trying to write a feed to a file using node.js. the problem is, it doesn't write all the feeds, only the last 1.

```<code>var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
  console.log('title; ', article.title);
    fs.writeFile("articles.json", JSON.stringify(article.title), function(err) {
    if(err) {
          console.log(err);
    }
  });
});
</code>```

Why?

答:
As @Robert says you should use appendFile, but also note that that change won't write out valid json. I'm not sure what output you're trying to achieve - it you just want the titles you could write out a txt file with a title on each line like so:

```<code>var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
  console.log('title; ', article.title);
    fs.appendFile("articles.txt", article.title + "\n", function(err) {
    if(err) {
          console.log(err);
    }
  });
});
</code>```

To write out json you can do:

```<code>var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
let titles = [];

feedParser.parseUrl(url)
  .on('article', function (article) {
    console.log('title; ', article.title);
    titles.push(article.title);
  })
  .on('end', function () {
    fs.writeFile('articles.json', JSON.stringify({ titles }), function (err) {
      if (err) {
        console.log(err);
      }
    });
  });
</code>```

Body:
i'm trying to write a feed to a file using node.js. the problem is, it doesn't write all the feeds, only the last 1.

var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
  console.log('title; ', article.title);
    fs.writeFile("articles.json", JSON.stringify(article.title), function(err) {
    if(err) {
          console.log(err);
    }
  });
});

Why?

Body:
As @Robert says you should use appendFile, but also note that that change won't write out valid json. I'm not sure what output you're trying to achieve - it you just want the titles you could write out a txt file with a title on each line like so:

var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
  console.log('title; ', article.title);
    fs.appendFile("articles.txt", article.title + "\n", function(err) {
    if(err) {
          console.log(err);
    }
  });
});

To write out json you can do:

var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
let titles = [];

feedParser.parseUrl(url)
  .on('article', function (article) {
    console.log('title; ', article.title);
    titles.push(article.title);
  })
  .on('end', function () {
    fs.writeFile('articles.json', JSON.stringify({ titles }), function (err) {
      if (err) {
        console.log(err);
      }
    });
  });


问:
Ignore or not API endpoint parameters based on access level
I am working on an API endpoint that returns a list of products:

```<code>"api/products"
</code>```

The endpoint accepts the following parameters:

```<code>page_size
page_number
</code>```

Each product has a boolean property named IsApproved.

In the web application used by common users I always want to return only the Approved products ... On the web ADMIN application used by administrators I want to return all products, Approved or Not ...

My idea would be to add a new parameter (enumeration) named:

```<code>ApprovedStatus
</code>```

And the values would be Approved, NotApproved and All.

On each API call I would check the user permissions ... If is admin I will consider the value on this parameter. If not then I will always return only approved products.

Another solution would be to have different endpoints ...

Any advice on which approach to take or is there other options?

答:
The approval status is part of the product, therefore, in a perfect REST world, you don't want a different endpoint at all since you're accessing the same resource.

Then, for filtering a resource based on a property value, I think the convention is that if you specify that property as a query parameter it will only return those matching the value, and if not, it will return all of them, so I don't see the need to define a special ApprovedStatus parameter with some special values. Just query by isApproved!

Finally, about how to handle authorization. This, I think, should be handled at a completely separate layer**. If authorization is involved, you should have an explicit authorization layer that decides, for a specific resource and user, wether access is granted or not. This means the query would be triggered and if one of the resources generated by the query fails to be authorized for the user that triggered the query, it's taken out of the results. This accomplishes the behaviour you want without having any code that is checking specific users against specific query parameters, which is good because if tomorrow you have another endpoint that exposes this objects you won't have to implement the same authorization policy twice. Pundit is a perfect example on how to do this with Ruby elegantly.

**Of course, this approach retrieves data from the database unnecessarily which could matter to you, and also opens your endpoint up to timing attacks. Even then, I would consider tackling these problems premature optimizations and should be ignored unless you have a very good reason.

Body:
I am working on an API endpoint that returns a list of products:

"api/products"

The endpoint accepts the following parameters:

page_size
page_number

Each product has a boolean property named IsApproved.

In the web application used by common users I always want to return only the Approved products ... On the web ADMIN application used by administrators I want to return all products, Approved or Not ...

My idea would be to add a new parameter (enumeration) named:

ApprovedStatus

And the values would be Approved, NotApproved and All.

On each API call I would check the user permissions ... If is admin I will consider the value on this parameter. If not then I will always return only approved products.

Another solution would be to have different endpoints ...

Any advice on which approach to take or is there other options?


问:
MD5/SHA "update" property?
What is the MD5/SHA property that allows you to "update" them? For example, if you have the hash for "test" you can add "case" to get the hash for "testcase". I would like to read up on this property a bit but my searches turn up nothing...</p>

答:
EDIT: This isn't even theoretically possible, due to the 1-bit padding I mention below. In effect, md5("case", seed=md5("test")) == md5("test" + <1-bit> + "case"). There is no way to use md5("test") to incrementally compute md5("test" + "case").

This is theoretically possible if you concatenate 512-bit chunks. It won't work for appending "case" to "test", because the first run of the state machine is polluted by the padding used to turn "case" into a 512-bit chunk.

Additionally, the padding isn't just a bunch of zeros. The message is always first padded with a 1 bit, so that "case" and "case\0" produce different hashes. Thus you can't rely on "case" having the same hash with or without padding.

Title: MD5/SHA "update" property?


问:
Error installing module l10n_es_aeat_mod303 from spanish odoo localization in odoo 9
In odoo 9, installing the module l10n_es_aeat_mod303, from spanish localization, gives me this error:

```<code>(...)File "/etc/odoo/server/openerp/addons/base/ir/ir_model.py", line 995, in xmlid_lookup
raise ValueError('External ID not found in the system: %s' % (xmlid))
ParseError: ""External ID not found in the system: l10n_es.account_tax_template_s_iva4b" while evaluating
"[(6, False, [ref('l10n_es.account_tax_template_s_iva4b'), ref('l10n_es.account_tax_template_s_iva4s')])]"" while parsing /etc/odoo/server/addons_extra/l10n_es_aeat_mod303/data/tax_code_map_mod303_data.xml:9, near
<record id="aeat_mod303_map_line_01" model="l10n.es.aeat.map.tax.line">
    <field name="map_parent_id" ref="aeat_mod303_map"/>
    <field name="field_number">01</field>
    <field name="name">Régimen General - Base imponible 4%</field>
    <field name="to_regularize" eval="False"/>
    <field name="move_type">regular</field>
    <field name="field_type">base</field>
    <field name="sum_type">both</field>
    <field name="inverse" eval="False"/>
<!-- Base facturas de venta (haber) - Descuentos en facturas de venta(debe):
     S_IVA4B, S_IVA4S -->
<field name="tax_ids" eval="[(6, False, [ref('l10n_es.account_tax_template_s_iva4b'), ref('l10n_es.account_tax_template_s_iva4s')])]"/>
</code>```

It appears that it does not find the identifier "account_tax_template_s_iva4b".

¿It is necessary to install some dependency before installing the module or how can I solve this error?

答:
I realized that there is the official l10n_es module inside addons and another in addons_extra.

The main problem is that the conf file gives priority to the official addons, and then, the addons_extra:

```<code>addons_path = /odoo/addons,/odoo/addons_extra
</code>```

To change this I followed these steps:

Make sure that the new module of l10n_es is inside addons_extra folder.

Put the path in the first place of addons_path parameter in conf file (the important part is that the official addons path will be after our new module path):

addons_path = /odoo/addons_extra/l10n-spain,/odoo/addons,/odoo/addons_extra

Restart the server and update the module list.

Update the l10n_es module.

Now, the new module is installed and I can install the l10n_es_aeat_mod303 module without errors.

Body:
In odoo 9, installing the module l10n_es_aeat_mod303, from spanish localization, gives me this error:

(...)File "/etc/odoo/server/openerp/addons/base/ir/ir_model.py", line 995, in xmlid_lookup
raise ValueError('External ID not found in the system: %s' % (xmlid))
ParseError: ""External ID not found in the system: l10n_es.account_tax_template_s_iva4b" while evaluating
"[(6, False, [ref('l10n_es.account_tax_template_s_iva4b'), ref('l10n_es.account_tax_template_s_iva4s')])]"" while parsing /etc/odoo/server/addons_extra/l10n_es_aeat_mod303/data/tax_code_map_mod303_data.xml:9, near
<record id="aeat_mod303_map_line_01" model="l10n.es.aeat.map.tax.line">
    <field name="map_parent_id" ref="aeat_mod303_map"/>
    <field name="field_number">01</field>
    <field name="name">Régimen General - Base imponible 4%</field>
    <field name="to_regularize" eval="False"/>
    <field name="move_type">regular</field>
    <field name="field_type">base</field>
    <field name="sum_type">both</field>
    <field name="inverse" eval="False"/>

<field name="tax_ids" eval="[(6, False, [ref('l10n_es.account_tax_template_s_iva4b'), ref('l10n_es.account_tax_template_s_iva4s')])]"/>

It appears that it does not find the identifier "account_tax_template_s_iva4b".

¿It is necessary to install some dependency before installing the module or how can I solve this error?

Body:
I realized that there is the official l10n_es module inside addons and another in addons_extra.

The main problem is that the conf file gives priority to the official addons, and then, the addons_extra:

addons_path = /odoo/addons,/odoo/addons_extra

To change this I followed these steps:

Make sure that the new module of l10n_es is inside addons_extra folder.

Put the path in the first place of addons_path parameter in conf file (the important part is that the official addons path will be after our new module path):

addons_path = /odoo/addons_extra/l10n-spain,/odoo/addons,/odoo/addons_extra

Restart the server and update the module list.

Update the l10n_es module.

Now, the new module is installed and I can install the l10n_es_aeat_mod303 module without errors.