Programs & Examples On #Opencv

OpenCV (Open Source Computer Vision) is a library for real time computer vision: * Human-Computer Interaction; Object Identification, * Face and Gesture Recognition; * Segmentation and Recognition; Motion Tracking, Motion Understanding; * Stereo and Multi-Camera Calibration and Depth Computation; Mobile Robotics.

Pycharm/Python OpenCV and CV2 install error

In jetso nano this work for me.

$ git clone https://github.com/JetsonHacksNano/buildOpenCV
$ cd buildOpenCV

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

If you are interested in it being realtime, then what you need is to add in a pre-processing filter to determine what gets scanned with the heavy-duty stuff. A good fast, very real time, pre-processing filter that will allow you to scan things that are more likely to be a coca-cola can than not before moving onto more iffy things is something like this: search the image for the biggest patches of color that are a certain tolerance away from the sqrt(pow(red,2) + pow(blue,2) + pow(green,2)) of your coca-cola can. Start with a very strict color tolerance, and work your way down to more lenient color tolerances. Then, when your robot runs out of an allotted time to process the current frame, it uses the currently found bottles for your purposes. Please note that you will have to tweak the RGB colors in the sqrt(pow(red,2) + pow(blue,2) + pow(green,2)) to get them just right.

Also, this is gona seem really dumb, but did you make sure to turn on -oFast compiler optimizations when you compiled your C code?

Python+OpenCV: cv2.imwrite

enter image description here enter image description here enter image description here

Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:

1 Perform face detection(Input an image, output all boxes of detected faces):

from mtcnn.mtcnn import MTCNN
import cv2

face_detector = MTCNN()

img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)

[{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]

2 save all detected faces to separate files:

for i in range(len(detect_boxes)):
    box = detect_boxes[i]["box"]
    face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

3 or Draw rectangles of all detected faces:

for box in detect_boxes:
    box = box["box"]
    pt1 = (box[0], box[1]) # top left
    pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
    cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)

inverting image in Python with OpenCV

Alternatively, you could invert the image using the bitwise_not function of OpenCV:

imagem = cv2.bitwise_not(imagem)

I liked this example.

Size of Matrix OpenCV

For 2D matrix:

mat.rows – Number of rows in a 2D array.

mat.cols – Number of columns in a 2D array.

Or: C++: Size Mat::size() const

The method returns a matrix size: Size(cols, rows) . When the matrix is more than 2-dimensional, the returned size is (-1, -1).

For multidimensional matrix, you need to use

int thisSizes[3] = {2, 3, 4};
cv::Mat mat3D(3, thisSizes, CV_32FC1);
// mat3D.size tells the size of the matrix 
// mat3D.size[0] = 2;
// mat3D.size[1] = 3;
// mat3D.size[2] = 4;

Note, here 2 for z axis, 3 for y axis, 4 for x axis. By x, y, z, it means the order of the dimensions. x index changes the fastest.

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

The patch is here: https://code.ros.org/trac/opencv/attachment/ticket/862/OpenCV-2.2-nov4l1.patch

By adding #ifdef HAVE_CAMV4L around

#include <linux/videodev.h>

in OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp and removing || defined (HAVE_CAMV4L2) from line 174 allowed me to compile.

Checking images for similarity with OpenCV

If for matching identical images ( same size/orientation )

// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
    // Calculate the L2 relative error between images.
    double errorL2 = norm( A, B, CV_L2 );
    // Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
    double similarity = errorL2 / (double)( A.rows * A.cols );
    return similarity;
}
else {
    //Images have a different size
    return 100000000.0;  // Return a bad value
}

Source

How can I convert a cv::Mat to a gray scale in OpenCv?

May be helpful for late comers.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
  if (argc != 2) {
    cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
    return -1;
}else{
    Mat image;
    Mat grayImage;

    image = imread(argv[1], IMREAD_COLOR);
    if (!image.data) {
        cout << "Could not open the image file" << endl;
        return -1;
    }
    else {
        int height = image.rows;
        int width = image.cols;

        cvtColor(image, grayImage, CV_BGR2GRAY);


        namedWindow("Display window", WINDOW_AUTOSIZE);
        imshow("Display window", image);

        namedWindow("Gray Image", WINDOW_AUTOSIZE);
        imshow("Gray Image", grayImage);
        cvWaitKey(0);
        image.release();
        grayImage.release();
        return 0;
    }

  }

}

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Explicitly specifying the max_iter resolves the warning as the default max_iter is 100. [For Logistic Regression].

 logreg = LogisticRegression(max_iter=1000)

Is there a way to detect if an image is blurry?

Thanks nikie for that great Laplace suggestion. OpenCV docs pointed me in the same direction: using python, cv2 (opencv 2.4.10), and numpy...

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) numpy.max(cv2.convertScaleAbs(cv2.Laplacian(gray_image,3)))

result is between 0-255. I found anything over 200ish is very in focus, and by 100, it's noticeably blurry. the max never really gets much under 20 even if it's completely blurred.

OpenCV !_src.empty() in function 'cvtColor' error

If the path is correct and the name of the image is OK, but you are still getting the error

use:

from skimage import io

img = io.imread(file_path)

instead of:

cv2.imread(file_path)

The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).

OpenCV - Apply mask to a color image

Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

enter image description here

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

How to detect simple geometric shapes using OpenCV

If you have only these regular shapes, there is a simple procedure as follows :

  1. Find Contours in the image ( image should be binary as given in your question)
  2. Approximate each contour using approxPolyDP function.
  3. First, check number of elements in the approximated contours of all the shapes. It is to recognize the shape. For eg, square will have 4, pentagon will have 5. Circles will have more, i don't know, so we find it. ( I got 16 for circle and 9 for half-circle.)
  4. Now assign the color, run the code for your test image, check its number, fill it with corresponding colors.

Below is my example in Python:

import numpy as np
import cv2

img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==5:
        print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 9:
        print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 15:
        print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Below is the output:

enter image description here

Remember, it works only for regular shapes.

Alternatively to find circles, you can use houghcircles. You can find a tutorial here.

Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.

You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf

How to convert a python numpy array to an RGB image with Opencv 2.4?

The images c, d, e , and f in the following show colorspace conversion they also happen to be numpy arrays <type 'numpy.ndarray'>:

import numpy, cv2
def show_pic(p):
        ''' use esc to see the results'''
        print(type(p))
        cv2.imshow('Color image', p)
        while True:
            k = cv2.waitKey(0) & 0xFF
            if k == 27: break 
        return
        cv2.destroyAllWindows()

b = numpy.zeros([200,200,3])

b[:,:,0] = numpy.ones([200,200])*255
b[:,:,1] = numpy.ones([200,200])*255
b[:,:,2] = numpy.ones([200,200])*0
cv2.imwrite('color_img.jpg', b)


c = cv2.imread('color_img.jpg', 1)
c = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)

d = cv2.imread('color_img.jpg', 1)
d = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)

e = cv2.imread('color_img.jpg', -1)
e = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)

f = cv2.imread('color_img.jpg', -1)
f = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)


pictures = [d, c, f, e]

for p in pictures:
        show_pic(p)
# show the matrix
print(c)
print(c.shape)

See here for more info: http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor

OR you could:

img = numpy.zeros([200,200,3])

img[:,:,0] = numpy.ones([200,200])*255
img[:,:,1] = numpy.ones([200,200])*255
img[:,:,2] = numpy.ones([200,200])*0

r,g,b = cv2.split(img)
img_bgr = cv2.merge([b,g,r])

How can I upgrade NumPy?

Because you have multiple versions of NumPy installed.

Try pip uninstall numpy and pip list | grep numpy several times, until you see no output from pip list | grep numpy.

Then pip install numpy will get you the newest version of NumPy.

how to convert an RGB image to numpy array?

PIL (Python Imaging Library) and Numpy work well together.

I use the following functions.

from PIL import Image
import numpy as np

def load_image( infilename ) :
    img = Image.open( infilename )
    img.load()
    data = np.asarray( img, dtype="int32" )
    return data

def save_image( npdata, outfilename ) :
    img = Image.fromarray( np.asarray( np.clip(npdata,0,255), dtype="uint8"), "L" )
    img.save( outfilename )

The 'Image.fromarray' is a little ugly because I clip incoming data to [0,255], convert to bytes, then create a grayscale image. I mostly work in gray.

An RGB image would be something like:

 outimg = Image.fromarray( ycc_uint8, "RGB" )
 outimg.save( "ycc.tif" )

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

For me, I had to have OpenCV (3.4.2), Py-OpenCV (3.4.2), LibOpenCV (3.4.2).

My Python was version 3.5.6 with Anaconda in Windows OS 10.

How do I install opencv using pip?

Install opencv-python (which is an unofficial pre-built OpenCV package for Python) by issuing the following command:

pip install opencv-python

Combining Two Images with OpenCV

in OpenCV 3.0 you can use it easily as follow:

#combine 2 images same as to concatenate images with two different sizes
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#create empty martrix (Mat)
res = np.zeros(shape=(max(h1, h2), w1 + w2, 3), dtype=np.uint8)
# assign BGR values to concatenate images
for i in range(res.shape[2]):
    # assign img1 colors
    res[:h1, :w1, i] = np.ones([img1.shape[0], img1.shape[1]]) * img1[:, :, i]
    # assign img2 colors
    res[:h2, w1:w1 + w2, i] = np.ones([img2.shape[0], img2.shape[1]]) * img2[:, :, i]

output_img = res.astype('uint8')

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

"Could not find a version that satisfies the requirement opencv-python"

I had the same error. The first time I used the 32-bit version of python but my computer is 64-bit. I then reinstalled the 64-bit version and succeeded.

Simple and fast method to compare images for similarity

Does the screenshot contain only the icon? If so, the L2 distance of the two images might suffice. If the L2 distance doesn't work, the next step is to try something simple and well established, like: Lucas-Kanade. Which I'm sure is available in OpenCV.

Python: how to capture image from webcam on click using OpenCV

Here is a simple programe to capture a image from using laptop default camera.I hope that this will be very easy method for all.

import cv2

# 1.creating a video object
video = cv2.VideoCapture(0) 
# 2. Variable
a = 0
# 3. While loop
while True:
    a = a + 1
    # 4.Create a frame object
    check, frame = video.read()
    # Converting to grayscale
    #gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    # 5.show the frame!
    cv2.imshow("Capturing",frame)
    # 6.for playing 
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows 

You can see my github code here

Package opencv was not found in the pkg-config search path

$ apt-file search opencv.pc $ ls /usr/local/lib/pkgconfig/ $ sudo cp /usr/local/lib/pkgconfig/opencv4.pc /usr/lib/x86_64-linux-gnu/pkgconfig/opencv.pc $ pkg-config --modversion opencv

Python: How to pip install opencv2 with specific version 2.4.9?

If you are using windows os, you can download your desired opencv unofficial windows binary from here, and type something like pip install opencv_python-2.4.13.2-cp27-cp27m-win_amd64.whl in the directory of binary file.

How to crop a CvMat in OpenCV?

I understand this question has been answered but perhaps this might be useful to someone...

If you wish to copy the data into a separate cv::Mat object you could use a function similar to this:

void ExtractROI(Mat& inImage, Mat& outImage, Rect roi){
    /* Create the image */
    outImage = Mat(roi.height, roi.width, inImage.type(), Scalar(0));

    /* Populate the image */
    for (int i = roi.y; i < (roi.y+roi.height); i++){
        uchar* inP = inImage.ptr<uchar>(i);
        uchar* outP = outImage.ptr<uchar>(i-roi.y);
        for (int j = roi.x; j < (roi.x+roi.width); j++){
            outP[j-roi.x] = inP[j];
        }
    }
}

It would be important to note that this would only function properly on single channel images.

How to fill Matrix with zeros in OpenCV?

You can choose filling zero data or create zero Mat.

  1. Filling zero data with setTo():

    img.setTo(Scalar::all(0));
    
  2. Create zero data with zeros():

    img = zeros(img.size(), img.type());
    

The img changes address of memory.

Convert RGB to Black & White in OpenCV

A simple way of "binarize" an image is to compare to a threshold: For example you can compare all elements in a matrix against a value with opencv in c++

cv::Mat img = cv::imread("image.jpg", CV_LOAD_IMAGE_GRAYSCALE); 
cv::Mat bw = img > 128;

In this way, all pixels in the matrix greater than 128 now are white, and these less than 128 or equals will be black

Optionally, and for me gave good results is to apply blur

cv::blur( bw, bw, cv::Size(3,3) );

Later you can save it as said before with:

cv::imwrite("image_bw.jpg", bw);

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

I am having OpenCV version 3.4.3 on MacOS. I was getting the same error as above.

I changed my code from

frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)   

to

frame = cv2.resize(frame, None, fx=0.5, fy=0.5)    

Now its working fine for me.

overlay a smaller image on a larger image python OpenCv

A simple 4on4 pasting function that works-

def paste(background,foreground,pos=(0,0)):
    #get position and crop pasting area if needed
    x = pos[0]
    y = pos[1]
    bgWidth = background.shape[0]
    bgHeight = background.shape[1]
    frWidth = foreground.shape[0]
    frHeight = foreground.shape[1]
    width = bgWidth-x
    height = bgHeight-y
    if frWidth<width:
        width = frWidth
    if frHeight<height:
        height = frHeight
    # normalize alpha channels from 0-255 to 0-1
    alpha_background = background[x:x+width,y:y+height,3] / 255.0
    alpha_foreground = foreground[:width,:height,3] / 255.0
    # set adjusted colors
    for color in range(0, 3):
        fr = alpha_foreground * foreground[:width,:height,color]
        bg = alpha_background * background[x:x+width,y:y+height,color] * (1 - alpha_foreground)
        background[x:x+width,y:y+height,color] = fr+bg
    # set adjusted alpha and denormalize back to 0-255
    background[x:x+width,y:y+height,3] = (1 - (1 - alpha_foreground) * (1 - alpha_background)) * 255
    return background

Converting Numpy Array to OpenCV Array

This is what worked for me...

import cv2
import numpy as np

#Created an image (really an ndarray) with three channels 
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)

#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255

#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)

#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image

#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

How does one convert a grayscale image to RGB in OpenCV (Python)?

Alternatively, cv2.merge() can be used to turn a single channel binary mask layer into a three channel color image by merging the same layer together as the blue, green, and red layers of the new image. We pass in a list of the three color channel layers - all the same in this case - and the function returns a single image with those color channels. This effectively transforms a grayscale image of shape (height, width, 1) into (height, width, 3)

To address your problem

I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.

This is because you're trying to display three channels on a single channel image. To fix this, you can simply merge the three single channels

image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])

Example

We create a color image with dimensions (200,200,3)

enter image description here

image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)

Next we convert it to grayscale and create another image using cv2.merge() with three gray channels

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])

We now draw a filled contour onto the single channel grayscale image (left) with shape (200,200,1) and the three channel grayscale image with shape (200,200,3) (right). The left image showcases the problem you're experiencing since you're trying to display three channels on a single channel image. After merging the grayscale image into three channels, we can now apply color onto the image

enter image description here enter image description here

contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])

Full code

import cv2
import numpy as np

# Create random color image
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)

# Convert to grayscale (1 channel)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Merge channels to create color image (3 channels)
gray_three = cv2.merge([gray,gray,gray])

# Fill a contour on both the single channel and three channel image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])

cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.imshow('gray_three', gray_three)
cv2.waitKey()

OpenCV error: the function is not implemented

Before installing libgtk2.0-dev and pkg-config or libqt4-dev. Make sure that you have uninstalled opencv. You can confirm this by running import cv2 on your python shell. If it fails, then install the needed packages and re-run cmake .

How to draw a rectangle around a region of interest in python

You can use cv2.rectangle():

cv2.rectangle(img, pt1, pt2, color, thickness, lineType, shift)

Draws a simple, thick, or filled up-right rectangle.

The function rectangle draws a rectangle outline or a filled rectangle
whose two opposite corners are pt1 and pt2.

Parameters
    img   Image.
    pt1   Vertex of the rectangle.
    pt2    Vertex of the rectangle opposite to pt1 .
    color Rectangle color or brightness (grayscale image).
    thickness  Thickness of lines that make up the rectangle. Negative values,
    like CV_FILLED , mean that the function has to draw a filled rectangle.
    lineType  Type of the line. See the line description.
    shift   Number of fractional bits in the point coordinates.

I have a PIL Image object and I want to draw rectangle on this image, but PIL's ImageDraw.rectangle() method does not have the ability to specify line width. I need to convert Image object to opencv2's image format and draw rectangle and convert back to Image object. Here is how I do it:

# im is a PIL Image object
im_arr = np.asarray(im)
# convert rgb array to opencv's bgr format
im_arr_bgr = cv2.cvtColor(im_arr, cv2.COLOR_RGB2BGR)
# pts1 and pts2 are the upper left and bottom right coordinates of the rectangle
cv2.rectangle(im_arr_bgr, pts1, pts2,
              color=(0, 255, 0), thickness=3)
im_arr = cv2.cvtColor(im_arr_bgr, cv2.COLOR_BGR2RGB)
# convert back to Image object
im = Image.fromarray(im_arr)

What does OpenCV's cvWaitKey( ) function do?

The cvWaitKey simply provides something of a delay. For example:

char c = cvWaitKey(33);
if( c == 27 ) break;

Tis was apart of my code in which a video was loaded into openCV and the frames outputted. The 33 number in the code means that after 33ms, a new frame would be shown. Hence, the was a dely or time interval of 33ms between each frame being shown on the screen. Hope this helps.

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

How to write text on a image in windows using python opencv2

I know this is a really old question but i think i have a solution In the newer versions of openCV fonts are repesented by a number like this

    FONT_HERSHEY_SIMPLEX = 0,
    FONT_HERSHEY_PLAIN = 1,
    FONT_HERSHEY_DUPLEX = 2,
    FONT_HERSHEY_COMPLEX = 3,
    FONT_HERSHEY_TRIPLEX = 4,
    FONT_HERSHEY_COMPLEX_SMALL = 5,
    FONT_HERSHEY_SCRIPT_SIMPLEX = 6,
    FONT_HERSHEY_SCRIPT_COMPLEX = 7,
    FONT_ITALIC = 16

so all you have to do is replace the font name with the corresponding number

cv2.putText(image,"Hello World!!!", (x,y), 0, 2, 255)

again i know its an old question but it may help someone in the future

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

How can I sharpen an image in OpenCV?

You can also try this filter

sharpen_filter = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
sharped_img = cv2.filter2D(image, -1, sharpen_filter)

Easiest way to rotate by 90 degrees an image using OpenCV?

Here's my EmguCV (a C# port of OpenCV) solution:

public static Image<TColor, TDepth> Rotate90<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static Image<TColor, TDepth> Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = img.CopyBlank();
    rot = img.Flip(FLIP.VERTICAL);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static void _Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    img._Flip(FLIP.VERTICAL);
    img._Flip(FLIP.HORIZONTAL);
}

public static Image<TColor, TDepth> Rotate270<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.VERTICAL);
    return rot;
}

Shouldn't be too hard to translate it back into C++.

Displaying a webcam feed using OpenCV and Python

An update to show how to do it in the recent versions of OpenCV:

import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break

cv2.destroyWindow("preview")
vc.release()

It works in OpenCV-2.4.2 for me.

Why is Visual Studio 2010 not able to find/open PDB files?

Referring to the first thread / another possibility VS cant open or find pdb file of the process is when you have your executable running in the background. I was working with mpiexec and ran into this issue. Always check your task manager and kill any exec process that your gonna build in your project. Once I did that, it debugged or built fine.

Also, if you try to continue with the warning , the breakpoints would not be hit and it would not have the current executable

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

For me the problem was that I was using different versions of Python in the same Eclipse project. My setup was not consistent with the Project Properties and the Run Configuration Python versions.

In Project > Properties > PyDev, I had the Interpreter set to Python2.7.11.

In Run Configurations > Interpreter, I was using the Default Interpreter. Changing it to Python 2.7.11 fixed the problem.

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Image size (Python, OpenCV)

You can use image.shape to get the dimensions of the image. It returns 3 values. First value is width of an image, second is height and last one is channel. You dont need last value here so you can use below code to get height and width of image:

width, height = src.shape[:2]<br>
print(width, height)

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

In these two lines:

mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

try instead:

cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

I had the same problem and the variables were being returned empty

Convert np.array of type float64 to type uint8 scaling values

you can use skimage.img_as_ubyte(yourdata) it will make you numpy array ranges from 0->255

from skimage import img_as_ubyte

img = img_as_ubyte(data)
cv2.imshow("Window", img)

Convert image from PIL to openCV format

This is the shortest version I could find,saving/hiding an extra conversion:

pil_image = PIL.Image.open('image.jpg')
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)

If reading a file from a URL:

import cStringIO
import urllib
file = cStringIO.StringIO(urllib.urlopen(r'http://stackoverflow.com/a_nice_image.jpg').read())
pil_image = PIL.Image.open(file)
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Setting Camera Parameters in OpenCV/Python

To avoid using integer values to identify the VideoCapture properties, one can use, e.g., cv2.cv.CV_CAP_PROP_FPS in OpenCV 2.4 and cv2.CAP_PROP_FPS in OpenCV 3.0. (See also Stefan's comment below.)

Here a utility function that works for both OpenCV 2.4 and 3.0:

# returns OpenCV VideoCapture property id given, e.g., "FPS"
def capPropId(prop):
  return getattr(cv2 if OPCV3 else cv2.cv,
    ("" if OPCV3 else "CV_") + "CAP_PROP_" + prop)

OPCV3 is set earlier in my utilities code like this:

from pkg_resources import parse_version
OPCV3 = parse_version(cv2.__version__) >= parse_version('3')

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I was facing similar issue with openCV on the python:3.7-slim docker box. Following did the trick for me :

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

Please see if this helps !

How do I increase the contrast of an image in Python OpenCV

I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.

I have done the following using OpenCV 3.0.0 and python:

import cv2

#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)
cv2.imshow("img",img) 

#-----Converting image to LAB Color model----------------------------------- 
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imshow("lab",lab)

#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)

#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)

#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)

#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)

#_____END_____#

You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.

C++ - unable to start correctly (0xc0150002)

It is because there is a DLL that your program is missing or can't find.

In your case I believe you are missing the openCV dlls. You can find these under the "build" directory that comes with open CV. If you are using VS2010 and building to an x86 program you can locate your dlls here under "opencv\build\x86\vc10\bin". Simply copy all these files to your Debug and Release folders and it should resolve your issues.

Generally you can resolve this issue using the following procedure:

  1. Download Dependency Walker from here: http://www.dependencywalker.com/
  2. Load your .exe file into Dependency Walker (under your projects Debug or Release folder), in your case this would be DisplayImage.exe
  3. Look for any DLL's that are missing, or are corrupt, or are for the wrong architecture (i.e. x64 instead of x86) these will be highlighted in red.
  4. For each DLL that you are missing either copy to your Debug or Release folders with your .exe, or install the required software, or add the path to the DLLs to your environment variables (Win+Pause -> Advanced System Settings -> Environment Variables)

Remember that you will need to have these DLLs in the same directory as your .exe. If you copy the .exe from the Release folder to somewhere else then you will need those DLLs copied with the .exe as well. For portability I tend to try and have a test Virtual Machine with a clean install of Windows (no updates or programs installed), and I walk through the Dependencies using the Dependency Walker one by one until the program is running happily.

This is a common problem. Also see these questions:

Can't run a vc++, error code 0xc0150002

The application was unable to start (0xc0150002) with libcurl C++ Windows 7 VS 2010

0xc0150002 Error when trying to run VC++ libcurl

The application was unable to start correctly 0xc150002

The application was unable to start correctly (0*0150002) - OpenCv

Good Luck!

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.

Accessing certain pixel RGB value in openCV

The low-level way would be to access the matrix data directly. In an RGB image (which I believe OpenCV typically stores as BGR), and assuming your cv::Mat variable is called frame, you could get the blue value at location (x, y) (from the top left) this way:

frame.data[frame.channels()*(frame.cols*y + x)];

Likewise, to get B, G, and R:

uchar b = frame.data[frame.channels()*(frame.cols*y + x) + 0];    
uchar g = frame.data[frame.channels()*(frame.cols*y + x) + 1];
uchar r = frame.data[frame.channels()*(frame.cols*y + x) + 2];

Note that this code assumes the stride is equal to the width of the image.

OpenCV & Python - Image too big to display

In opencv, cv.namedWindow() just creates a window object as you determine, but not resizing the original image. You can use cv2.resize(img, resolution) to solve the problem.

Here's what it displays, a 740 * 411 resolution image. The original image

image = cv2.imread("740*411.jpg")
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, it displays a 100 * 200 resolution image after resizing. Remember the resolution parameter use column first then is row.

Image after resizing

image = cv2.imread("740*411.jpg")
image = cv2.resize(image, (200, 100))
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

Based on what @J. Calleja said, you have two choices

Method 1 - Random access

If you want to random access the element of Mat, just simply use

Mat.at<data_Type>(row_num, col_num) = value;

Method 2 - Continuous access

If you want to continuous access, OpenCV provides Mat iterator compatible with STL iterator and it's more C++ style

MatIterator_<double> it, end;
for( it = I.begin<double>(), end = I.end<double>(); it != end; ++it)
{
    //do something here
}

or

for(int row = 0; row < mat.rows; ++row) {
    float* p = mat.ptr(row); //pointer p points to the first place of each row
    for(int col = 0; col < mat.cols; ++col) {
         *p++;  // operation here
    }
}

If you have any difficulty to understand how Method 2 works, I borrow the picture from a blog post in the article Dynamic Two-dimensioned Arrays in C, which is much more intuitive and comprehensible.

See the picture below.

enter image description here

Getting started with OpenCV 2.4 and MinGW on Windows 7

As pointed out by @Nenad Bulatovic one has to be careful while adding libraries(19th step). one should not add any trailing spaces while adding each library line by line. otherwise mingw goes haywire.

OpenCV - Saving images to a particular folder of choice

You can use this simple code in loop by incrementing count

cv2.imwrite("C:\Sharat\Python\Images\frame%d.jpg" % count, image)

images will be saved in the folder by name line frame0.jpg, frame1.jpg frame2.jpg etc..

Extracting text OpenCV

I used a gradient based method in the program below. Added the resulting images. Please note that I'm using a scaled down version of the image for processing.

c++ version

The MIT License (MIT)

Copyright (c) 2014 Dhanushka Dangampola

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

#include "stdafx.h"

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;

#define INPUT_FILE              "1.jpg"
#define OUTPUT_FOLDER_PATH      string("")

int _tmain(int argc, _TCHAR* argv[])
{
    Mat large = imread(INPUT_FILE);
    Mat rgb;
    // downsample and use it for processing
    pyrDown(large, rgb);
    Mat small;
    cvtColor(rgb, small, CV_BGR2GRAY);
    // morphological gradient
    Mat grad;
    Mat morphKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
    morphologyEx(small, grad, MORPH_GRADIENT, morphKernel);
    // binarize
    Mat bw;
    threshold(grad, bw, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
    // connect horizontally oriented regions
    Mat connected;
    morphKernel = getStructuringElement(MORPH_RECT, Size(9, 1));
    morphologyEx(bw, connected, MORPH_CLOSE, morphKernel);
    // find contours
    Mat mask = Mat::zeros(bw.size(), CV_8UC1);
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    findContours(connected, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
    // filter contours
    for(int idx = 0; idx >= 0; idx = hierarchy[idx][0])
    {
        Rect rect = boundingRect(contours[idx]);
        Mat maskROI(mask, rect);
        maskROI = Scalar(0, 0, 0);
        // fill the contour
        drawContours(mask, contours, idx, Scalar(255, 255, 255), CV_FILLED);
        // ratio of non-zero pixels in the filled region
        double r = (double)countNonZero(maskROI)/(rect.width*rect.height);

        if (r > .45 /* assume at least 45% of the area is filled if it contains text */
            && 
            (rect.height > 8 && rect.width > 8) /* constraints on region size */
            /* these two conditions alone are not very robust. better to use something 
            like the number of significant peaks in a horizontal projection as a third condition */
            )
        {
            rectangle(rgb, rect, Scalar(0, 255, 0), 2);
        }
    }
    imwrite(OUTPUT_FOLDER_PATH + string("rgb.jpg"), rgb);

    return 0;
}

python version

The MIT License (MIT)

Copyright (c) 2017 Dhanushka Dangampola

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

import cv2
import numpy as np

large = cv2.imread('1.jpg')
rgb = cv2.pyrDown(large)
small = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
grad = cv2.morphologyEx(small, cv2.MORPH_GRADIENT, kernel)

_, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel)
# using RETR_EXTERNAL instead of RETR_CCOMP
contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#For opencv 3+ comment the previous line and uncomment the following line
#_, contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

mask = np.zeros(bw.shape, dtype=np.uint8)

for idx in range(len(contours)):
    x, y, w, h = cv2.boundingRect(contours[idx])
    mask[y:y+h, x:x+w] = 0
    cv2.drawContours(mask, contours, idx, (255, 255, 255), -1)
    r = float(cv2.countNonZero(mask[y:y+h, x:x+w])) / (w * h)

    if r > 0.45 and w > 8 and h > 8:
        cv2.rectangle(rgb, (x, y), (x+w-1, y+h-1), (0, 255, 0), 2)

cv2.imshow('rects', rgb)

enter image description here enter image description here enter image description here

Converting an OpenCV Image to Black and White

Pay attention, if you use cv.CV_THRESH_BINARY means every pixel greater than threshold becomes the maxValue (in your case 255), otherwise the value is 0. Obviously if your threshold is 0 everything becomes white (maxValue = 255) and if the value is 255 everything becomes black (i.e. 0).

If you don't want to work out a threshold, you can use the Otsu's method. But this algorithm only works with 8bit images in the implementation of OpenCV. If your image is 8bit use the algorithm like this:

cv.Threshold(im_gray_mat, im_bw_mat, threshold, 255, cv.CV_THRESH_BINARY | cv.CV_THRESH_OTSU);

No matter the value of threshold if you have a 8bit image.

Writing an mp4 video using python opencv

Anyone who's looking for most convenient and robust way of writing MP4 files with OpenCV or FFmpeg, can see my state-of-the-art VidGear Video-Processing Python library's WriteGear API that works with both OpenCV backend and FFmpeg backend and even supports GPU encoders. Here's an example to encode with H264 encoder in WriteGear with FFmpeg backend:

# import required libraries
from vidgear.gears import WriteGear
import cv2

# define suitable (Codec,CRF,preset) FFmpeg parameters for writer
output_params = {"-vcodec":"libx264", "-crf": 0, "-preset": "fast"}

# Open suitable video stream, such as webcam on first index(i.e. 0)
stream = cv2.VideoCapture(0) 

# Define writer with defined parameters and suitable output filename for e.g. `Output.mp4`
writer = WriteGear(output_filename = 'Output.mp4', logging = True, **output_params)

# loop over
while True:

    # read frames from stream
    (grabbed, frame) = stream.read()

    # check for frame if not grabbed
    if not grabbed:
      break

    # {do something with the frame here}
    # lets convert frame to gray for this example
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # write gray frame to writer
    writer.write(gray)

    # Show output window
    cv2.imshow("Output Gray Frame", gray)

    # check for 'q' key if pressed
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

# close output window
cv2.destroyAllWindows()

# safely close video stream
stream.release()

# safely close writer
writer.close() 

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

You haven't put the shared library in a location where the loader can find it. look inside the /usr/local/opencv and /usr/local/opencv2 folders and see if either of them contains any shared libraries (files beginning in lib and usually ending in .so). when you find them, create a file called /etc/ld.so.conf.d/opencv.conf and write to it the paths to the folders where the libraries are stored, one per line.

for example, if the libraries were stored under /usr/local/opencv/libopencv_core.so.2.4 then I would write this to my opencv.conf file:

/usr/local/opencv/

Then run

sudo ldconfig -v

If you can't find the libraries, try running

sudo updatedb && locate libopencv_core.so.2.4

in a shell. You don't need to run updatedb if you've rebooted since compiling OpenCV.

References:

About shared libraries on Linux: http://www.eyrie.org/~eagle/notes/rpath.html

About adding the OpenCV shared libraries: http://opencv.willowgarage.com/wiki/InstallGuide_Linux

OpenCV NoneType object has no attribute shape

I also face the same issue "OpenCV NoneType object has no attribute shape" and i solve this by changing the image location. I also use the PyCharm IDE. Currently my image location and class file in the same folder. enter image description here

Access IP Camera in Python OpenCV

You can access most IP cameras using the method below.

import cv2 

# insert the HTTP(S)/RSTP feed from the camera
url = "http://username:password@your_ip:your_port/tmpfs/auto.jpg"

# open the feed
cap = cv2.VideoCapture(url)

while True:
    # read next frame
     ret, frame = cap.read()
    
    # show frame to user
     cv2.imshow('frame', frame)
    
    # if user presses q quit program
     if cv2.waitKey(1) & 0xFF == ord("q"):
        break

# close the connection and close all windows
cap.release()
cv2.destroyAllWindows()

How to crop an image in OpenCV using Python

Below is the way to crop an image.

image_path: The path to the image to edit

coords: A tuple of x/y coordinates (x1, y1, x2, y2)[open the image in mspaint and check the "ruler" in view tab to see the coordinates]

saved_location: Path to save the cropped image

from PIL import Image
    def crop(image_path, coords, saved_location:
        image_obj = Image.open("Path of the image to be cropped")
            cropped_image = image_obj.crop(coords)
            cropped_image.save(saved_location)
            cropped_image.show()


if __name__ == '__main__':
    image = "image.jpg"
    crop(image, (100, 210, 710,380 ), 'cropped.jpg')

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:

cv2.cv.CV_CAP_PROP_POS_FRAMES

to

cv2.CAP_PROP_POS_FRAMES

and same applies to cv2.CAP_PROP_POS_FRAME_COUNT.

Hope it helps.

Convert Mat to Array/Vector in OpenCV

cv::Mat m;
m.create(10, 10, CV_32FC3);

float *array = (float *)malloc( 3*sizeof(float)*10*10 );
cv::MatConstIterator_<cv::Vec3f> it = m.begin<cv::Vec3f>();
for (unsigned i = 0; it != m.end<cv::Vec3f>(); it++ ) {
    for ( unsigned j = 0; j < 3; j++ ) {
        *(array + i ) = (*it)[j];
        i++;
    }
}

Now you have a float array. In case of 8 bit, simply change float to uchar, Vec3f to Vec3b and CV_32FC3 to CV_8UC3.

DLL load failed error when importing cv2

(base) C:\WINDOWS\system32>conda install C:\Users\Todd\Downloads\opencv3-3.1.0-py35_0.tar.bz2

I ran this command from anaconda terminal after I downloaded the version from https://anaconda.org/menpo/opencv3/files

This is the only way I could get cv2 to work and I tried everything for two days.

Using other keys for the waitKey() function of opencv

The answer that works on Ubuntu18, python3, opencv 3.2.0 is similar to the one above. But with the change in line cv2.waitKey(0). that means the program waits until a button is pressed.

With this code I found the key value for the arrow buttons: arrow up (82), down (84), arrow left(81) and Enter(10) and etc..

import cv2
img = cv2.imread('sof.jpg') # load a dummy image
while(1):
    cv2.imshow('img',img)
    k = cv2.waitKey(0)
    if k==27:    # Esc key to stop
        break
    elif k==-1:  # normally -1 returned,so don't print it
        continue
    else:
        print k # else print its value

Could not find module FindOpenCV.cmake ( Error in configuration process)

Followed @hugh-pearse 's and @leszek-hanusz 's answers, with a little tweak. I had installed opencv from ubuntu 12.10 repository (libopencv-)* and had the same problem. Couldn't solve it with export OpenCV_DIR=/usr/share/OpenCV/ (since my OpenCVConfig.cmake whas there). It was solved when I also changed some lines on the OpenCVConfig.cmake file:

# ======================================================
# Include directories to add to the user project:
# ======================================================

# Provide the include directories to the caller

#SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")

SET(OpenCV_INCLUDE_DIRS "/usr/include/opencv;/usr/include/opencv2")
INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS})

# ======================================================
# Link directories to add to the user project:
# ======================================================

# Provide the libs directory anyway, it may be needed in some cases.

#SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")

SET(OpenCV_LIB_DIR "/usr/lib")

LINK_DIRECTORIES(${OpenCV_LIB_DIR})

And that worked on my Ubuntu 12.10. Remember to add the target_link_libraries(yourprojectname ${OpenCV_LIBS}) in your CMakeLists.txt.

How can I add new dimensions to a Numpy array?

There is no structure in numpy that allows you to append more data later.

Instead, numpy puts all of your data into a contiguous chunk of numbers (basically; a C array), and any resize requires allocating a new chunk of memory to hold it. Numpy's speed comes from being able to keep all the data in a numpy array in the same chunk of memory; e.g. mathematical operations can be parallelized for speed and you get less cache misses.

So you will have two kinds of solutions:

  1. Pre-allocate the memory for the numpy array and fill in the values, like in JoshAdel's answer, or
  2. Keep your data in a normal python list until it's actually needed to put them all together (see below)

images = []
for i in range(100):
    new_image = # pull image from somewhere
    images.append(new_image)
images = np.stack(images, axis=3)

Note that there is no need to expand the dimensions of the individual image arrays first, nor do you need to know how many images you expect ahead of time.

How do I install Python OpenCV through Conda?

To install OpenCV in Anaconda, start up the Anaconda command prompt and install OpenCV with

conda install -c https://conda.anaconda.org/menpo opencv3

Test that it works in your Anaconda Spyder or IPython console with

import cv2

You can also check the installed version using:

cv2.__version__

How to use opencv in using Gradle?

As per OpenCV docs(1), below steps using OpenCV manager is the recommended way to use OpenCV for production runs. But, OpenCV manager(2) is an additional install from Google play store. So, if you prefer a self contained apk(not using OpenCV manager) or is currently in development/testing phase, I suggest answer at https://stackoverflow.com/a/27421494/1180117.

Recommended steps for using OpenCV in Android Studio with OpenCV manager.

  1. Unzip OpenCV Android sdk downloaded from OpenCV.org(3)
  2. From File -> Import Module, choose sdk/java folder in the unzipped opencv archive.
  3. Update build.gradle under imported OpenCV module to update 4 fields to match your project's build.gradle a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and 4) targetSdkVersion.
  4. Add module dependency by Application -> Module Settings, and select the Dependencies tab. Click + icon at bottom(or right), choose Module Dependency and select the imported OpenCV module.

As the final step, in your Activity class, add snippet below.

    public class SampleJava extends Activity  {

        private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch(status) {
                case LoaderCallbackInterface.SUCCESS:
                    Log.i(TAG,"OpenCV Manager Connected");
                    //from now onwards, you can use OpenCV API
                    Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
                    break;
                case LoaderCallbackInterface.INIT_FAILED:
                    Log.i(TAG,"Init Failed");
                    break;
                case LoaderCallbackInterface.INSTALL_CANCELED:
                    Log.i(TAG,"Install Cancelled");
                    break;
                case LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION:
                    Log.i(TAG,"Incompatible Version");
                    break;
                case LoaderCallbackInterface.MARKET_ERROR:
                    Log.i(TAG,"Market Error");
                    break;
                default:
                    Log.i(TAG,"OpenCV Manager Install");
                    super.onManagerConnected(status);
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        //initialize OpenCV manager
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, mLoaderCallback);
    }
}

Note: You could only make OpenCV calls after you receive success callback on onManagerConnected method. During run, you will be prompted for installation of OpenCV manager from play store, if it is not already installed. During development, if you don't have access to play store or is on emualtor, use appropriate OpenCV manager apk present in apk folder under downloaded OpenCV sdk archive .

Pros

  • Apk size reduction by around 40 MB ( consider upgrades too ).
  • OpenCV manager installs optimized binaries for your hardware which could help speed.
  • Upgrades to OpenCV manager might save your app from bugs in OpenCV.
  • Different apps could share same OpenCV library.

Cons

  • End user experience - might not like a install prompt from with your application.

OpenCV in Android Studio

Android Studio 3.4 + OpenCV 4.1

  1. Download the latest OpenCV zip file from here (current newest version is 4.1.0) and unzip it in your workspace or in another folder.

  2. Create new Android Studio project normally. Click File->New->Import Module, navigate to /path_to_unzipped_files/OpenCV-android-sdk/sdk/java, set Module name as opencv, click Next and uncheck all options in the screen.

  3. Enable Project file view mode (default mode is Android). In the opencv/build.gradle file change apply plugin: 'com.android.application' to apply plugin: 'com.android.library' and replace application ID "org.opencv" with

    minSdkVersion 21
    targetSdkVersion 28
    

    (according the values in app/build.gradle). Sync project with Gradle files.

  4. Add this string to the dependencies block in the app/build.gradle file

    dependencies {
        ...
        implementation project(path: ':opencv')
        ...
    }
    
  5. Select again Android file view mode. Right click on app module and goto New->Folder->JNI Folder. Select change folder location and set src/main/jniLibs/.

  6. Select again Project file view mode and copy all folders from /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/libs to app/src/main/jniLibs.

  7. Again in Android file view mode right click on app module and choose Link C++ Project with Gradle. Select Build System ndk-build and path to OpenCV.mk file /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/jni/OpenCV.mk.

    path_to_unzipped_files must not contain any spaces, or you will get error!

To check OpenCV initialization add Toast message in MainActivity onCreate() method:

Toast.makeText(MainActivity.this, String.valueOf(OpenCVLoader.initDebug()), Toast.LENGTH_LONG).show();

If initialization is successful you will see true in Toast message else you will see false.

How to use OpenCV SimpleBlobDetector

Python: Reads image blob.jpg and performs blob detection with different parameters.

#!/usr/bin/python

# Standard imports
import cv2
import numpy as np;

# Read image
im = cv2.imread("blob.jpg")

# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

# Change thresholds
params.minThreshold = 10
params.maxThreshold = 200


# Filter by Area.
params.filterByArea = True
params.minArea = 1500

# Filter by Circularity
params.filterByCircularity = True
params.minCircularity = 0.1

# Filter by Convexity
params.filterByConvexity = True
params.minConvexity = 0.87

# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.01

# Create a detector with the parameters
detector = cv2.SimpleBlobDetector(params)


# Detect blobs.
keypoints = detector.detect(im)

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures
# the size of the circle corresponds to the size of blob

im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show blobs
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey(0)

C++: Reads image blob.jpg and performs blob detection with different parameters.

#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    // Read image
#if CV_MAJOR_VERSION < 3   // If you are using OpenCV 2
    Mat im = imread("blob.jpg", CV_LOAD_IMAGE_GRAYSCALE);
#else
    Mat im = imread("blob.jpg", IMREAD_GRAYSCALE);
#endif

    // Setup SimpleBlobDetector parameters.
    SimpleBlobDetector::Params params;

    // Change thresholds
    params.minThreshold = 10;
    params.maxThreshold = 200;

    // Filter by Area.
    params.filterByArea = true;
    params.minArea = 1500;

    // Filter by Circularity
    params.filterByCircularity = true;
    params.minCircularity = 0.1;

    // Filter by Convexity
    params.filterByConvexity = true;
    params.minConvexity = 0.87;

    // Filter by Inertia
    params.filterByInertia = true;
    params.minInertiaRatio = 0.01;

    // Storage for blobs
    std::vector<KeyPoint> keypoints;

#if CV_MAJOR_VERSION < 3   // If you are using OpenCV 2

    // Set up detector with params
    SimpleBlobDetector detector(params);

    // Detect blobs
    detector.detect(im, keypoints);
#else 

    // Set up detector with params
    Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params);

    // Detect blobs
    detector->detect(im, keypoints);
#endif 

    // Draw detected blobs as red circles.
    // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures
    // the size of the circle corresponds to the size of blob

    Mat im_with_keypoints;
    drawKeypoints(im, keypoints, im_with_keypoints, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);

    // Show blobs
    imshow("keypoints", im_with_keypoints);
    waitKey(0);
}

The answer has been copied from this tutorial I wrote at LearnOpenCV.com explaining various parameters of SimpleBlobDetector. You can find additional details about the parameters in the tutorial.

Cannot get OpenCV to compile because of undefined references?

For me, this type of error:

mingw-w64-x86_64/lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld: mingw-w64-x86_64/x86_64-w64-mingw32/lib/libTransform360.a(VideoFrameTransform.cpp.obj):VideoFrameTransform.cpp:(.text+0xc7c):
undefined reference to `cv::Mat::Mat(cv::Mat const&, cv::Rect_<int> const&)'

meant load order, I had to do -lTransform360 -lopencv_dnn345 -lopencv... just like that, that order. And putting them right next to each other helped too, don't put -lTransform360 all the way at the beginning...or you'll get, for some freaky reason:

undefined reference to `VideoFrameTransform_new'
undefined reference to `VideoFrameTransform_generateMapForPlane'

...

RuntimeError: module compiled against API version a but this version of numpy is 9

For those using anaconda Python:

conda update anaconda

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

Print out the values of a (Mat) matrix in OpenCV C++

I think using the matrix.at<type>(x,y) is not the best way to iterate trough a Mat object! If I recall correctly matrix.at<type>(x,y) will iterate from the beginning of the matrix each time you call it(I might be wrong though). I would suggest using cv::MatIterator_

cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
    std::cout << *_it << std::endl;
}

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

How to create Haar Cascade (.xml file) to use in OpenCV?

If you are interested to detect simple IR light blob through haar cascade, it will be very odd to do. Because simple IR blob does not have enough features to be trained through opencv like other objects (face, eyes,nose etc). Because IR is just a simple light having only one feature of brightness in my point of view. But if you want to learn how to train a classifier following link will help you alot.

http://note.sonots.com/SciSoftware/haartraining.html

And if you just want to detect IR blob, then you have two more possibilities, one is you go for DIP algorithms to detect bright region and the other one which I recommend you is you can use an IR cam which just pass the IR blob and you can detect easily the IR blob by using opencv blob functiuons. If you think an IR cam is expansive, you can make simple webcam to an IR cam by removing IR blocker (if any) and add visible light blocker i.e negative film, floppy material or any other. You can check the following link to convert simple webcam to IR cam.

http://www.metacafe.com/watch/385098/transform_your_webcam_into_an_infrared_cam/

OpenCV with Network Cameras

I just do it like this:

CvCapture *capture = cvCreateFileCapture("rtsp://camera-address");

Also make sure this dll is available at runtime else cvCreateFileCapture will return NULL

opencv_ffmpeg200d.dll

The camera needs to allow unauthenticated access too, usually set via its web interface. MJPEG format worked via rtsp but MPEG4 didn't.

hth

Si

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

If you want as simple as possible, install from the repository:

sudo apt-get install python-opencv libopencv-dev python-numpy python-dev

How to fill OpenCV image with one solid color?

If you are using Java for OpenCV, then you can use the following code.

Mat img = src.clone(); //Clone from the original image
img.setTo(new Scalar(255,255,255)); //This sets the whole image to white, it is R,G,B value

How to resize an image to a specific size in OpenCV?

For your information, the python equivalent is:

imageBuffer = cv.LoadImage( strSrc )
nW = new X size
nH = new Y size
smallerImage = cv.CreateImage( (nH, nW), imageBuffer.depth, imageBuffer.nChannels )
cv.Resize( imageBuffer, smallerImage , interpolation=cv.CV_INTER_CUBIC )
cv.SaveImage( strDst, smallerImage )

ImportError: numpy.core.multiarray failed to import

uninstall existing numpy and install opencv-python will resolve the issue

openCV video saving in python

jveitchmichaelis at https://github.com/ContinuumIO/anaconda-issues/issues/223 provided a thorough answer. Here I copied his answer:

The documentation in OpenCV says (hidden away) that you can only write to avi using OpenCV3. Whether that's true or not I've not been able to determine, but I've been unable to write to anything else.

However, OpenCV is mainly a computer vision library, not a video stream, codec and write one. Therefore, the developers tried to keep this part as simple as possible. Due to this OpenCV for video containers supports only the avi extension, its first version.

From: http://docs.opencv.org/3.1.0/d7/d9e/tutorial_video_write.html

My setup: I built OpenCV 3 from source using MSVC 2015, including ffmpeg. I've also downloaded and installed XVID and openh264 from Cisco, which I added to my PATH. I'm running Anaconda Python 3. I also downloaded a recent build of ffmpeg and added the bin folder to my path, though that shouldn't make a difference as its baked into OpenCV.

I'm running in Win 10 64-bit.

This code seems to work fine on my computer. It will generate a video containing random static:

writer = cv2.VideoWriter("output.avi",
cv2.VideoWriter_fourcc(*"MJPG"), 30,(640,480))

for frame in range(1000):
    writer.write(np.random.randint(0, 255, (480,640,3)).astype('uint8'))

writer.release()

Some things I've learned through trial and error:

  • Only use '.avi', it's just a container, the codec is the important thing.
  • Be careful with specifying frame sizes. In the constructor you need to pass the frame size as (column, row) e.g. 640x480. However the array you pass in, is indexed as (row, column). See in the above example how it's switched?

  • If your input image has a different size to the VideoWriter, it will fail (often silently)

  • Only pass in 8 bit images, manually cast your arrays if you have to (.astype('uint8'))
  • In fact, never mind, just always cast. Even if you load in images using cv2.imread, you need to cast to uint8...
  • MJPG will fail if you don't pass in a 3 channel, 8-bit image. I get an assertion failure for this at least.
  • XVID also requires a 3 channel image but fails silently if you don't do this.
  • H264 seems to be fine with a single channel image
  • If you need raw output, say from a machine vision camera, you can use 'DIB '. 'RAW ' or an empty codec sometimes works. Oddly if I use DIB, I get an ffmpeg error, but the video is saved fine. If I use RAW, there isn't an error, but Windows Video player won't open it. All are fine in VLC.

In the end I think the key point is that OpenCV is not designed to be a video capture library - it doesn't even support sound. VideoWriter is useful, but 99% of the time you're better off saving all your images into a folder and using ffmpeg to turn them into a useful video.

Installing OpenCV on Windows 7 for Python 2.7

One thing that needs to be mentioned. You have to use the x86 version of Python 2.7. OpenCV doesn't support Python x64. I banged my head on this for a bit until I figured that out.

That said, follow the steps in Abid Rahman K's answer. And as Antimony said, you'll need to do a 'from cv2 import cv'

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

c++ and opencv get and set pixel color to Mat

You did everything except copying the new pixel value back to the image.

This line takes a copy of the pixel into a local variable:

Vec3b color = image.at<Vec3b>(Point(x,y));

So, after changing color as you require, just set it back like this:

image.at<Vec3b>(Point(x,y)) = color;

So, in full, something like this:

Mat image = img;
for(int y=0;y<img.rows;y++)
{
    for(int x=0;x<img.cols;x++)
    {
        // get pixel
        Vec3b & color = image.at<Vec3b>(y,x);

        // ... do something to the color ....
        color[0] = 13;
        color[1] = 13;
        color[2] = 13;

        // set pixel
        //image.at<Vec3b>(Point(x,y)) = color;
        //if you copy value
    }
}

Python - Extracting and Saving Video Frames

This function extracts images from video with 1 fps, IN ADDITION it identifies the last frame and stops reading also:

import cv2
import numpy as np

def extract_image_one_fps(video_source_path):

    vidcap = cv2.VideoCapture(video_source_path)
    count = 0
    success = True
    while success:
      vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))      
      success,image = vidcap.read()

      ## Stop when last frame is identified
      image_last = cv2.imread("frame{}.png".format(count-1))
      if np.array_equal(image,image_last):
          break

      cv2.imwrite("frame%d.png" % count, image)     # save frame as PNG file
      print '{}.sec reading a new frame: {} '.format(count,success)
      count += 1

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

Problem 1 : Different applications use different scales for HSV. For example gimp uses H = 0-360, S = 0-100 and V = 0-100. But OpenCV uses H: 0-179, S: 0-255, V: 0-255. Here i got a hue value of 22 in gimp. So I took half of it, 11, and defined range for that. ie (5,50,50) - (15,255,255).

Problem 2: And also, OpenCV uses BGR format, not RGB. So change your code which converts RGB to HSV as follows:

cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV)

Now run it. I got an output as follows:

enter image description here

Hope that is what you wanted. There are some false detections, but they are small, so you can choose biggest contour which is your lid.

EDIT:

As Karl Philip told in his comment, it would be good to add new code. But there is change of only a single line. So, I would like to add the same code implemented in new cv2 module, so users can compare the easiness and flexibility of new cv2 module.

import cv2
import numpy as np

img = cv2.imread('sof.jpg')

ORANGE_MIN = np.array([5, 50, 50],np.uint8)
ORANGE_MAX = np.array([15, 255, 255],np.uint8)

hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

frame_threshed = cv2.inRange(hsv_img, ORANGE_MIN, ORANGE_MAX)
cv2.imwrite('output2.jpg', frame_threshed)

It gives the same result as above. But code is much more simpler.

OpenCV - DLL missing, but it's not?

Just copy the .dll files to C:\windows\system32\

Find OpenCV Version Installed on Ubuntu

1) Direct Answer: Try this:

   sudo updatedb
   locate OpenCVConfig.cmake

For me, I get:

   /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

To see the version, you can try:

   cat /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

giving

    ....
   SET(OpenCV_VERSION 2.3.1)
    ....

2) Better Answer:

"sudo make install" is your enemy, don't do that when you need to compile/update the library often and possibly debug step through it's internal functions. Notice how my config file is in a local build directory, not in /usr/something. You will avoid this confusion in the future, and can maintain several different versions even (debug and release, for example).

Edit: the reason this questions seems to arise often for OpenCV as opposed to other libraries is that it changes rather dramatically and fast between versions, and many of the operations are not so well-defined / well-constrained so you can't just rely on it to be a black-box like you do for something like libpng or libjpeg. Thus, better to not install it at all really, but just compile and link to the build folder.

100% Min Height CSS layout

A pure CSS solution (#content { min-height: 100%; }) will work in a lot of cases, but not in all of them - especially IE6 and IE7.

Unfortunately, you will need to resort to a JavaScript solution in order to get the desired behavior. This can be done by calculating the desired height for your content <div> and setting it as a CSS property in a function:

function resizeContent() {
  var contentDiv = document.getElementById('content');
  var headerDiv = document.getElementById('header');
  // This may need to be done differently on IE than FF, but you get the idea.
  var viewPortHeight = window.innerHeight - headerDiv.clientHeight;
  contentDiv.style.height = 
    Math.max(viewportHeight, contentDiv.clientHeight) + 'px';
}

You can then set this function as a handler for onLoad and onResize events:

<body onload="resizeContent()" onresize="resizeContent()">
  . . .
</body>

Concat scripts in order with Gulp

I have my scripts organized in different folders for each package I pull in from bower, plus my own script for my app. Since you are going to list the order of these scripts somewhere, why not just list them in your gulp file? For new developers on your project, it's nice that all your script end-points are listed here. You can do this with gulp-add-src:

gulpfile.js

var gulp = require('gulp'),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    addsrc = require('gulp-add-src'),
    sourcemaps = require('gulp-sourcemaps');

// CSS & Less
gulp.task('css', function(){
    gulp.src('less/all.less')
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(minifyCSS())
        .pipe(sourcemaps.write('source-maps'))
        .pipe(gulp.dest('public/css'));
});

// JS
gulp.task('js', function() {
    gulp.src('resources/assets/bower/jquery/dist/jquery.js')
    .pipe(addsrc.append('resources/assets/bower/bootstrap/dist/js/bootstrap.js'))
    .pipe(addsrc.append('resources/assets/bower/blahblah/dist/js/blah.js'))
    .pipe(addsrc.append('resources/assets/js/my-script.js'))
    .pipe(sourcemaps.init())
    .pipe(concat('all.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write('source-maps'))
    .pipe(gulp.dest('public/js'));
});

gulp.task('default',['css','js']);

Note: jQuery and Bootstrap added for demonstration purposes of order. Probably better to use CDNs for those since they are so widely used and browsers could have them cached from other sites already.

'"SDL.h" no such file or directory found' when compiling

For Simple Direct Media Layer 2 (SDL2), after installing it on Ubuntu 16.04 via:

sudo apt-get install libsdl2-dev

I used the header:

#include <SDL2/SDL.h>  

and the compiler linker command:

-lSDL2main -lSDL2 

Additionally, you may also want to install:

apt-get install libsdl2-image-dev  
apt-get install libsdl2-mixer-dev  
apt-get install libsdl2-ttf-dev  

With these headers:

#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>  

and the compiler linker commands:

-lSDL2_image 
-lSDL2_ttf 
-lSDL2_mixer

jQuery append() and remove() element

You can call a reset function before appending. Something like this:

    function resetNewReviewBoardForm() {
    $("#Description").val('');
    $("#PersonName").text('');
    $("#members").empty(); //this one what worked in my case
    $("#EmailNotification").val('False');
}

Making HTTP Requests using Chrome Developer tools

Expanding on @dhfsk answer

Here's my workflow

  1. From Chrome DevTools, right-click the request you want to manipulate > Copy as cURL Chrome DevTools Copy as cURL

  2. Open Postman

  3. Click Import in the upper-left corner then Paste Raw Text Postman Paste Raw Text cURL from Chrome

Explain why constructor inject is better than other options

With examples? Here's a simple one:

public class TwoInjectionStyles {
    private Foo foo;

    // Constructor injection
    public TwoInjectionStyles(Foo f) {
        this.foo = f;
    }

    // Setting injection
    public void setFoo(Foo f) { this.foo = f; }
}

Personally, I prefer constructor injection when I can.

In both cases, the bean factory instantiates the TwoInjectionStyles and Foo instances and gives the former its Foo dependency.

Make just one slide different size in Powerpoint

True you can't have different sized slides. NOT true the size of you slide doesn't matter. It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.

Filter dataframe rows if value in column is in a set list of values

You can also achieve similar results by using 'query' and @:

eg:

df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})
df = pd.DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]})
list_of_values = [3,6]
result= df.query("A in @list_of_values")
result
   A  B
1  6  2
2  3  3

Best way to create an empty map in Java

If you need an instance of HashMap, the best way is:

fileParameters = new HashMap<String,String>();

Since Map is an interface, you need to pick some class that instantiates it if you want to create an empty instance. HashMap seems as good as any other - so just use that.

How to pass the password to su/sudo/ssh without overriding the TTY?

I wrote some Applescript which prompts for a password via a dialog box and then builds a custom bash command, like this:

echo <password> | sudo -S <command>

I'm not sure if this helps.

It'd be nice if sudo accepted a pre-encrypted password, so I could encrypt it within my script and not worry about echoing clear text passwords around. However this works for me and my situation.

Why is my JavaScript function sometimes "not defined"?

It shouldn't be possible for this to happen if you're just including the scripts on the page.

The "copyArray" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency library. There are all sorts of problems with timing if that's the case.

Dump all tables in CSV format using 'mysqldump'

If you are using MySQL or MariaDB, the easiest and performant way dump CSV for single table is -

SELECT customer_id, firstname, surname INTO OUTFILE '/exportdata/customers.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM customers;

Now you can use other techniques to repeat this command for multiple tables. See more details here:

Converting URL to String and back again

In Swift 4 and Swift 3, To convert String to URL:

URL(string: String)

or,

URL.init(string: "yourURLString")

And to convert URL to String:

URL.absoluteString

The one below converts the 'contents' of the url to string

String(contentsOf: URL)

Where is the itoa function in Linux?

EDIT: Sorry, I should have remembered that this machine is decidedly non-standard, having plugged in various non-standard libc implementations for academic purposes ;-)

As itoa() is indeed non-standard, as mentioned by several helpful commenters, it is best to use sprintf(target_string,"%d",source_int) or (better yet, because it's safe from buffer overflows) snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int). I know it's not quite as concise or cool as itoa(), but at least you can Write Once, Run Everywhere (tm) ;-)

Here's the old (edited) answer

You are correct in stating that the default gcc libc does not include itoa(), like several other platforms, due to it not technically being a part of the standard. See here for a little more info. Note that you have to

#include <stdlib.h>

Of course you already know this, because you wanted to use itoa() on Linux after presumably using it on another platform, but... the code (stolen from the link above) would look like:

Example

/* itoa example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char buffer [33];
  printf ("Enter a number: ");
  scanf ("%d",&i);
  itoa (i,buffer,10);
  printf ("decimal: %s\n",buffer);
  itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);
  return 0;
}

Output:

Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110

Hope this helps!

Restrict SQL Server Login access to only one database

For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:

USE master
go
DENY VIEW ANY DATABASE TO [user]
go

This will address exactly the requirement outlined above..

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

Regular expressions in C: examples?

It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

Saving and Reading Bitmaps/Images from Internal memory in Android

// mutiple image retrieve

 File folPath = new File(getIntent().getStringExtra("folder_path"));
 File[] imagep = folPath.listFiles();

 for (int i = 0; i < imagep.length ; i++) {
     imageModelList.add(new ImageModel(imagep[i].getAbsolutePath(), Uri.parse(imagep[i].getAbsolutePath())));
 }
 imagesAdapter.notifyDataSetChanged();

in a "using" block is a SqlConnection closed on return or exception?

I wrote two using statements inside a try/catch block and I could see the exception was being caught the same way if it's placed within the inner using statement just as ShaneLS example.

     try
     {
       using (var con = new SqlConnection(@"Data Source=..."))
       {
         var cad = "INSERT INTO table VALUES (@r1,@r2,@r3)";

         using (var insertCommand = new SqlCommand(cad, con))
         {
           insertCommand.Parameters.AddWithValue("@r1", atxt);
           insertCommand.Parameters.AddWithValue("@r2", btxt);
           insertCommand.Parameters.AddWithValue("@r3", ctxt);
           con.Open();
           insertCommand.ExecuteNonQuery();
         }
       }
     }
     catch (Exception ex)
     {
       MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }

No matter where's the try/catch placed, the exception will be caught without issues.

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

How can I change default dialog button text color in android 5

Kotlin 2020: Very simple method

After dialog.show() use:

dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(requireContext(), R.color.yourColor))

Serializing enums with Jackson

In Spring Boot 2, the easiest way is to declare in your application.properties:

spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true

and define the toString() method of your enums.

How to horizontally align ul to center of div?

Following is a list of solutions to centering things in CSS horizontally. The snippet includes all of them.

_x000D_
_x000D_
html {_x000D_
  font: 1.25em/1.5 Georgia, Times, serif;_x000D_
}_x000D_
_x000D_
pre {_x000D_
  color: #fff;_x000D_
  background-color: #333;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
blockquote {_x000D_
  max-width: 400px;_x000D_
  background-color: #e0f0d1;_x000D_
}_x000D_
_x000D_
blockquote > p {_x000D_
  font-style: italic;_x000D_
}_x000D_
_x000D_
blockquote > p:first-of-type::before {_x000D_
  content: open-quote;_x000D_
}_x000D_
_x000D_
blockquote > p:last-of-type::after {_x000D_
  content: close-quote;_x000D_
}_x000D_
_x000D_
blockquote > footer::before {_x000D_
  content: "\2014";_x000D_
}_x000D_
_x000D_
.container,_x000D_
blockquote {_x000D_
  position: relative;_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  background-color: tomato;_x000D_
}_x000D_
_x000D_
.container::after,_x000D_
blockquote::after {_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  padding: 2px 10px;_x000D_
  border: 1px dotted #000;_x000D_
  background-color: #fff;_x000D_
}_x000D_
_x000D_
.container::after {_x000D_
  content: ".container-" attr(data-num);_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
blockquote::after {_x000D_
  content: ".quote-" attr(data-num);_x000D_
  z-index: 2;_x000D_
}_x000D_
_x000D_
.container-4 {_x000D_
  margin-bottom: 200px;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 1_x000D_
 */_x000D_
.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 2_x000D_
 */_x000D_
.container-2 {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 3_x000D_
 */_x000D_
.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 4_x000D_
 */_x000D_
.container-4 {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 5_x000D_
 */_x000D_
.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<main>_x000D_
  <h1>CSS: Horizontal Centering</h1>_x000D_
_x000D_
  <h2>Uncentered Example</h2>_x000D_
  <p>This is the scenario: We have a container with an element inside of it that we want to center. I just added a little padding and background colors so both elements are distinquishable.</p>_x000D_
_x000D_
  <div class="container  container-0" data-num="0">_x000D_
    <blockquote class="quote-0" data-num="0">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 1: Using <code>max-width</code> & <code>margin</code> (IE7)</h2>_x000D_
_x000D_
  <p>This method is widely used. The upside here is that only the element which one wants to center needs rules.</p>_x000D_
_x000D_
<pre><code>.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-1" data-num="1">_x000D_
    <blockquote class="quote  quote-1" data-num="1">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 2: Using <code>display: inline-block</code> and <code>text-align</code> (IE8)</h2>_x000D_
_x000D_
  <p>This method utilizes that <code>inline-block</code> elements are treated as text and as such they are affected by the <code>text-align</code> property. This does not rely on a fixed width which is an upside. This is helpful for when you don’t know the number of elements in a container for example.</p>_x000D_
_x000D_
<pre><code>.container-2 {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-2" data-num="2">_x000D_
    <blockquote class="quote  quote-2" data-num="2">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 3: Using <code>display: table</code> and <code>margin</code> (IE8)</h2>_x000D_
_x000D_
  <p>Very similar to the second solution but only requires to apply rules on the element that is to be centered.</p>_x000D_
_x000D_
<pre><code>.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-3" data-num="3">_x000D_
    <blockquote class="quote  quote-3" data-num="3">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 4: Using <code>translate()</code> and <code>position</code> (IE9)</h2>_x000D_
_x000D_
  <p>Don’t use as a general approach for horizontal centering elements. The downside here is that the centered element will be removed from the document flow. Notice the container shrinking to zero height with only the padding keeping it visible. This is what <i>removing an element from the document flow</i> means.</p>_x000D_
_x000D_
  <p>There are however applications for this technique. For example, it works for <b>vertically</b> centering by using <code>top</code> or <code>bottom</code> together with <code>translateY()</code>.</p>_x000D_
_x000D_
<pre><code>.container-4 {_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-4" data-num="4">_x000D_
    <blockquote class="quote  quote-4" data-num="4">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 5: Using Flexible Box Layout Module (IE10+ with vendor prefix)</h2>_x000D_
_x000D_
  <p></p>_x000D_
_x000D_
<pre><code>.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-5" data-num="5">_x000D_
    <blockquote class="quote  quote-5" data-num="5">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
</main>
_x000D_
_x000D_
_x000D_


display: flex

.container {
  display: flex;
  justify-content: center;
}

Notes:


max-width & margin

You can horizontally center a block-level element by assigning a fixed width and setting margin-right and margin-left to auto.

.container ul {
  /* for IE below version 7 use `width` instead of `max-width` */
  max-width: 800px;
  margin-right: auto;
  margin-left: auto;
}

Notes:

  • No container needed
  • Requires (maximum) width of the centered element to be known

IE9+: transform: translatex(-50%) & left: 50%

This is similar to the quirky centering method which uses absolute positioning and negative margins.

.container {
  position: relative;
}

.container ul {
  position: absolute;
  left: 50%;
  transform: translatex(-50%);
}

Notes:

  • The centered element will be removed from document flow. All elements will completely ignore of the centered element.
  • This technique allows vertical centering by using top instead of left and translateY() instead of translateX(). The two can even be combined.
  • Browser support: transform2d

IE8+: display: table & margin

Just like the first solution, you use auto values for right and left margins, but don’t assign a width. If you don’t need to support IE7 and below, this is better suited, although it feels kind of hacky to use the table property value for display.

.container ul {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

IE8+: display: inline-block & text-align

Centering an element just like you would do with regular text is possible as well. Downside: You need to assign values to both a container and the element itself.

.container {
  text-align: center;
}

.container ul {
  display: inline-block;

  /* One most likely needs to realign flow content */
  text-align: initial;
}

Notes:

  • Does not require to specify a (maximum) width
  • Aligns flow content to the center (potentially unwanted side effect)
  • Works kind of well with a dynamic number of menu items (i.e. in cases where you can’t know the width a single item will take up)

No visible cause for "Unexpected token ILLEGAL"

I had this same problem and it occurred because I had hit the enter key when adding code in a text string.

Because it was a long string of text I wanted to see it all without having to scroll in my text editor, however hitting enter added an invisible character to the string which was illegal. I was using Sublime Text as my editor.

Convert String into a Class Object

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.


If you did this:

SomeClass object = ...
String s = object.toString();

then the answer is that there is no simple way to turn s back into an instance of SomeClass. You couldn't do it even if the toString() method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)

The only way you could turn the output of toString back into an object would be to:

  • code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and
  • code a constructor or factory method that explicitly parsed a String in the format produced by the toString() method.

This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.


If you did something like this:

SomeClass object = ...
Class c = object.getClass();
String cn = c.toString();

then you could get the same Class object back (i.e. the one that is in c) as follows:

Class c2 = Class.forName(cn);

This gives you the Class but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)


If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString() method at all. Here are some alternatives that you can use:

  • The Java Object Serialization APIs as described in the links in @Nishant's answer.
  • JSON serialization as described in @fatnjazzy's answer.
  • An XML serialization library like XStream.
  • An ORM mapping.

Each of these approaches has advantages and disadvantages ... which I won't go into here.

Facebook api: (#4) Application request limit reached

now Application-Level Rate Limiting 200 calls per hour !

you can look this image.enter image description here

Allow only numbers and dot in script

Hope this could help someone

$(document).on("input", ".numeric", function() {
this.value = this.value.match(/^\d+\.?\d{0,2}/);});

What is a "slug" in Django?

It is a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL.

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

Simulating a click in jQuery/JavaScript on a link

Try this

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
        return;
    }
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(buttonId).dispatchEvent(e);
    } else {
        document.getElementById(buttonId).click();
    }
}

and you can use it like

submitRequest("target-element-id");

How to use "not" in xpath?

None of these answers worked for me for python. I solved by this

a[not(@id='XX')]

Also you can use or condition in your xpath by | operator. Such as

a[not(@id='XX')]|a[not(@class='YY')]

Sometimes we want element which has no class. So you can do like

a[not(@class)]

How to make Regular expression into non-greedy?

The non-greedy regex modifiers are like their greedy counter-parts but with a ? immediately following them:

*  - zero or more
*? - zero or more (non-greedy)
+  - one or more
+? - one or more (non-greedy)
?  - zero or one
?? - zero or one (non-greedy)

How can I use Python to get the system hostname?

Use socket and its gethostname() functionality. This will get the hostname of the computer where the Python interpreter is running:

import socket
print(socket.gethostname())

'IF' in 'SELECT' statement - choose output value based on column values

Most simplest way is to use a IF(). Yes Mysql allows you to do conditional logic. IF function takes 3 params CONDITION, TRUE OUTCOME, FALSE OUTCOME.

So Logic is

if report.type = 'p' 
    amount = amount 
else 
    amount = -1*amount 

SQL

SELECT 
    id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
FROM  report

You may skip abs() if all no's are +ve only

String vs. StringBuilder

StringBuilder reduces the number of allocations and assignments, at a cost of extra memory used. Used properly, it can completely remove the need for the compiler to allocate larger and larger strings over and over until the result is found.

string result = "";
for(int i = 0; i != N; ++i)
{
   result = result + i.ToString();   // allocates a new string, then assigns it to result, which gets repeated N times
}

vs.

String result;
StringBuilder sb = new StringBuilder(10000);   // create a buffer of 10k
for(int i = 0; i != N; ++i)
{
   sb.Append(i.ToString());          // fill the buffer, resizing if it overflows the buffer
}

result = sb.ToString();   // assigns once

jQuery - hashchange event

Here is updated version of @johnny.rodgers

Hope helps someone.

// ie9 ve ie7 return true but never fire, lets remove ie less then 10
if(("onhashchange" in window) && navigator.userAgent.toLowerCase().indexOf('msie') == -1){ // event supported?
    window.onhashchange = function(){
        var url = window.location.hash.substring(1);
        alert(url);
    }
}
else{ // event not supported:
    var storedhash = window.location.hash;
    window.setInterval(function(){
        if(window.location.hash != storedhash){
            storedhash = window.location.hash;
            alert(url);
        }
    }, 100);
}

How to style a div to be a responsive square?

Another way is to use a transparent 1x1.png with width: 100%, height: auto in a div and absolutely positioned content within it:

html:

<div>
    <img src="1x1px.png">
    <h1>FOO</h1>
</div>

css:

div {
    position: relative;
    width: 50%;
}

img {
    width: 100%;
    height: auto;
}

h1 {
    position: absolute;
    top: 10px;
    left: 10px;
}

Fidle: http://jsfiddle.net/t529bjwc/

How Big can a Python List Get?

12000 elements is nothing in Python... and actually the number of elements can go as far as the Python interpreter has memory on your system.

Why is width: 100% not working on div {display: table-cell}?

Just add min-height:100% and min-width:100% and it will work. I had the same problem. You don't need a 3th wrapper

Call async/await functions in parallel

TL;DR

Use Promise.all for the parallel function calls, the answer behaviors not correctly when the error occurs.


First, execute all the asynchronous calls at once and obtain all the Promise objects. Second, use await on the Promise objects. This way, while you wait for the first Promise to resolve the other asynchronous calls are still progressing. Overall, you will only wait for as long as the slowest asynchronous call. For example:

// Begin first call and store promise without waiting
const someResult = someCall();

// Begin second call and store promise without waiting
const anotherResult = anotherCall();

// Now we await for both results, whose async processes have already been started
const finalResult = [await someResult, await anotherResult];

// At this point all calls have been resolved
// Now when accessing someResult| anotherResult,
// you will have a value instead of a promise

JSbin example: http://jsbin.com/xerifanima/edit?js,console

Caveat: It doesn't matter if the await calls are on the same line or on different lines, so long as the first await call happens after all of the asynchronous calls. See JohnnyHK's comment.


Update: this answer has a different timing in error handling according to the @bergi's answer, it does NOT throw out the error as the error occurs but after all the promises are executed. I compare the result with @jonny's tip: [result1, result2] = Promise.all([async1(), async2()]), check the following code snippet

_x000D_
_x000D_
const correctAsync500ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 500, 'correct500msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const correctAsync100ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 100, 'correct100msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const rejectAsync100ms = () => {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    setTimeout(reject, 100, 'reject100msError');_x000D_
  });_x000D_
};_x000D_
_x000D_
const asyncInArray = async (fun1, fun2) => {_x000D_
  const label = 'test async functions in array';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    const p1 = fun1();_x000D_
    const p2 = fun2();_x000D_
    const result = [await p1, await p2];_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
const asyncInPromiseAll = async (fun1, fun2) => {_x000D_
  const label = 'test async functions with Promise.all';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    let [value1, value2] = await Promise.all([fun1(), fun2()]);_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
(async () => {_x000D_
  console.group('async functions without error');_x000D_
  console.log('async functions without error: start')_x000D_
  await asyncInArray(correctAsync500ms, correctAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, correctAsync100ms);_x000D_
  console.groupEnd();_x000D_
_x000D_
  console.group('async functions with error');_x000D_
  console.log('async functions with error: start')_x000D_
  await asyncInArray(correctAsync500ms, rejectAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, rejectAsync100ms);_x000D_
  console.groupEnd();_x000D_
})();
_x000D_
_x000D_
_x000D_

How to get the list of files in a directory in a shell script?

Just enter this simple command:

ls -d */

Printing list elements on separated lines in Python

Use the splat operator(*)

By default, * operator prints list separated by space. Use sep operator to specify the delimiter

print(*sys.path, sep = "\n")

sed with literal string--not input file

Works like you want:

echo "A,B,C" | sed s/,/\',\'/g

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

How is __eq__ handled in Python and in what order?

When Python2.x sees a == b, it tries the following.

  • If type(b) is a new-style class, and type(b) is a subclass of type(a), and type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If type(a) has overridden __eq__ (that is, type(a).__eq__ isn't object.__eq__), then the result is a.__eq__(b).
  • If type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If none of the above are the case, Python repeats the process looking for __cmp__. If it exists, the objects are equal iff it returns zero.
  • As a final fallback, Python calls object.__eq__(a, b), which is True iff a and b are the same object.

If any of the special methods return NotImplemented, Python acts as though the method didn't exist.

Note that last step carefully: if neither a nor b overloads ==, then a == b is the same as a is b.


From https://eev.ee/blog/2012/03/24/python-faq-equality/

Custom circle button

With the official Material Components library you can use the MaterialButton applying a Widget.MaterialComponents.Button.Icon style.

Something like:

   <com.google.android.material.button.MaterialButton
            android:layout_width="48dp"
            android:layout_height="48dp"
            style="@style/Widget.MaterialComponents.Button.Icon"
            app:icon="@drawable/ic_add"
            app:iconSize="24dp"
            app:iconPadding="0dp"
            android:insetLeft="0dp"
            android:insetTop="0dp"
            android:insetRight="0dp"
            android:insetBottom="0dp"
            app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Rounded"
            />

Currently the app:iconPadding="0dp",android:insetLeft,android:insetTop,android:insetRight,android:insetBottom attributes are needed to center the icon on the button avoiding extra padding space.

Use the app:shapeAppearanceOverlay attribute to get rounded corners. In this case you will have a circle.

  <style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
  </style>

The final result:

enter image description here

How to convert array values to lowercase in PHP?

array_change_value_case

by continue

    function array_change_value_case($array, $case = CASE_LOWER){
        if ( ! is_array($array)) return false;
        foreach ($array as $key => &$value){
            if (is_array($value))
            call_user_func_array(__function__, array (&$value, $case ) ) ;
            else
            $array[$key] = ($case == CASE_UPPER )
            ? strtoupper($array[$key])
            : strtolower($array[$key]);
        }
        return $array;
    }


    $arrays = array ( 1 => 'ONE', 2=> 'TWO', 3 => 'THREE',
                     'FOUR' => array ('a' => 'Ahmed', 'b' => 'basem',
                     'c' => 'Continue'),
                      5=> 'FIVE',
                      array('AbCdeF'));


    $change_case = array_change_value_case($arrays, CASE_UPPER);
    echo "<pre>";
    print_r($change_case);
Array
(
 [1] => one
 [2] => two
 [3] => three
 [FOUR] => Array
  (
   [a] => ahmed
   [b] => basem
   [c] => continue
  )

 [5] => five
 [6] => Array
  (
   [0] => abcdef
  )

)

How can I check what version/edition of Visual Studio is installed programmatically?

Put this code somewhere in your C++ project:

#ifdef _DEBUG
TCHAR version[50];
sprintf(&version[0], "Version = %d", _MSC_VER);
MessageBox(NULL, (LPCTSTR)szMsg, "Visual Studio", MB_OK | MB_ICONINFORMATION);
#endif

Note that _MSC_VER symbol is Microsoft specific. Here you can find a list of Visual Studio versions with the value for _MSC_VER for each version.

Checking something isEmpty in Javascript?

If you're looking for the equivalent of PHP's empty function, check this out:

function empty(mixed_var) {
  //   example 1: empty(null);
  //   returns 1: true
  //   example 2: empty(undefined);
  //   returns 2: true
  //   example 3: empty([]);
  //   returns 3: true
  //   example 4: empty({});
  //   returns 4: true
  //   example 5: empty({'aFunc' : function () { alert('humpty'); } });
  //   returns 5: false

  var undef, key, i, len;
  var emptyValues = [undef, null, false, 0, '', '0'];

  for (i = 0, len = emptyValues.length; i < len; i++) {
    if (mixed_var === emptyValues[i]) {
      return true;
    }
  }

  if (typeof mixed_var === 'object') {
    for (key in mixed_var) {
      // TODO: should we check for own properties only?
      //if (mixed_var.hasOwnProperty(key)) {
      return false;
      //}
    }
    return true;
  }

  return false;
}

http://phpjs.org/functions/empty:392

How to enable Logger.debug() in Log4j

Here's a quick one-line hack that I occasionally use to temporarily turn on log4j debug logging in a JUnit test:

Logger.getRootLogger().setLevel(Level.DEBUG);

or if you want to avoid adding imports:

org.apache.log4j.Logger.getRootLogger().setLevel(
      org.apache.log4j.Level.DEBUG);

Note: this hack doesn't work in log4j2 because setLevel has been removed from the API, and there doesn't appear to be equivalent functionality.

How can I run code on a background thread on Android?

Simple 3-Liner

A simple way of doing this that I found as a comment by @awardak in Brandon Rude's answer:

new Thread( new Runnable() { @Override public void run() { 
  // Run whatever background code you want here.
} } ).start();

I'm not sure if, or how , this is better than using AsyncTask.execute but it seems to work for us. Any comments as to the difference would be appreciated.

Thanks, @awardak!

What's the difference between import java.util.*; and import java.util.Date; ?

The toString() implementation of java.util.Date does not depend on the way the class is imported. It always returns a nice formatted date.

The toString() you see comes from another class.

Specific import have precedence over wildcard imports.

in this case

import other.Date
import java.util.*

new Date();

refers to other.Date and not java.util.Date.

The odd thing is that

import other.*
import java.util.*

Should give you a compiler error stating that the reference to Date is ambiguous because both other.Date and java.util.Date matches.

Inline SVG in CSS

On Mac/Linux, you can easily convert a SVG file to a base64 encoded value for CSS background attribute with this simple bash command:

echo "background: transparent url('data:image/svg+xml;base64,"$(openssl base64 < path/to/file.svg)"') no-repeat center center;"

Tested on Mac OS X. This way you also avoid the URL escaping mess.

Remember that base64 encoding an SVG file increase its size, see css-tricks.com blog post.

Like Operator in Entity Framework?

Update: In EF 6.2 there is a like operator

Where(obj => DbFunctions.Like(obj.Column , "%expression%")

How to use `subprocess` command with pipes

command = "ps -A | grep 'process_name'"
output = subprocess.check_output(["bash", "-c", command])

Display loading image while post with ajax

Let's say you have a tag someplace on the page which contains your loading message:

<div id='loadingmessage' style='display:none'>
  <img src='loadinggraphic.gif'/>
</div>

You can add two lines to your ajax call:

function getData(p){
    var page=p;
    $('#loadingmessage').show();  // show the loading message.
    $.ajax({
        url: "loadData.php?id=<? echo $id; ?>",
        type: "POST",
        cache: false,
        data: "&page="+ page,
        success : function(html){
            $(".content").html(html);
            $('#loadingmessage').hide(); // hide the loading message
        }
    });

How can I get the current stack trace in Java?

For people, who just want to get the current stacktrace to their logs, I would go with:

getLogger().debug("Message", new Throwable());

Cheers

Split comma separated column data into additional columns

If the number of fields in the CSV is constant then you could do something like this:

select a[1], a[2], a[3], a[4]
from (
    select regexp_split_to_array('a,b,c,d', ',')
) as dt(a)

For example:

=> select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
 a | a | a | a 
---+---+---+---
 a | b | c | d
(1 row)

If the number of fields in the CSV is not constant then you could get the maximum number of fields with something like this:

select max(array_length(regexp_split_to_array(csv, ','), 1))
from your_table

and then build the appropriate a[1], a[2], ..., a[M] column list for your query. So if the above gave you a max of 6, you'd use this:

select a[1], a[2], a[3], a[4], a[5], a[6]
from (
    select regexp_split_to_array(csv, ',')
    from your_table
) as dt(a)

You could combine those two queries into a function if you wanted.

For example, give this data (that's a NULL in the last row):

=> select * from csvs;
     csv     
-------------
 1,2,3
 1,2,3,4
 1,2,3,4,5,6

(4 rows)

=> select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
 max 
-----
   6
(1 row)

=> select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
 a | a | a | a | a | a 
---+---+---+---+---+---
 1 | 2 | 3 |   |   | 
 1 | 2 | 3 | 4 |   | 
 1 | 2 | 3 | 4 | 5 | 6
   |   |   |   |   | 
(4 rows)

Since your delimiter is a simple fixed string, you could also use string_to_array instead of regexp_split_to_array:

select ...
from (
    select string_to_array(csv, ',')
    from csvs
) as dt(a);

Thanks to Michael for the reminder about this function.

You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.

Quoting backslashes in Python string literals

You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

Incidentally, there's another string form which might be a bit clearer:

>>> print(r'baz "\"')
baz "\"

How to see tomcat is running or not

for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running

IF a == true OR b == true statement

Comparison expressions should each be in their own brackets:

{% if (a == 'foo') or (b == 'bar') %}
    ...
{% endif %}

Alternative if you are inspecting a single variable and a number of possible values:

{% if a in ['foo', 'bar', 'qux'] %}
    ...
{% endif %}

How to use EOF to run through a text file in C?

One possible C loop would be:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        /*
        ** Do something with c, such as check against '\n'
        ** and increment a line counter.
        */
    }
}

For now, I would ignore feof and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.

Pitfall to avoid: using char for the type of c. getchar returns the next character cast to an unsigned char and then to an int. This means that on most [sane] platforms the value of EOF and valid "char" values in c don't overlap so you won't ever accidentally detect EOF for a 'normal' char.

Call a stored procedure with parameter in c#

The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.

A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :

  CREATE PROCEDURE SPCOUNTRY
  @COUNTRY VARCHAR(20)
  AS
  SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY
  GO

The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.

  command.CommandType = CommandType.StoredProcedure;
  param = new SqlParameter("@COUNTRY", "Germany");
  param.Direction = ParameterDirection.Input;
  param.DbType = DbType.String;
  command.Parameters.Add(param);

The above code passing country parameter to the stored procedure from C# application.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection ;
            SqlDataAdapter adapter ;
            SqlCommand command = new SqlCommand();
            SqlParameter param ;
            DataSet ds = new DataSet();

            int i = 0;

            connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
            connection = new SqlConnection(connetionString);

            connection.Open();
            command.Connection = connection;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "SPCOUNTRY";

            param = new SqlParameter("@COUNTRY", "Germany");
            param.Direction = ParameterDirection.Input;
            param.DbType = DbType.String;
            command.Parameters.Add(param);

            adapter = new SqlDataAdapter(command);
            adapter.Fill(ds);

            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
            }

            connection.Close();
        }
    }
}

Reading a UTF8 CSV file with Python

Worth noting that if nothing worked for you, you may have forgotten to escape your path.
For example, this code:

f = open("C:\Some\Path\To\file.csv")

Would result in an error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

To fix, simply do:

f = open("C:\\Some\\Path\\To\\file.csv")

HTML.ActionLink method

I think what you want is this:

ASP.NET MVC1

Html.ActionLink(article.Title, 
                "Login",  // <-- Controller Name.
                "Item",   // <-- ActionMethod
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string controllerName,
                                string actionName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC2

two arguments have been switched around

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC3+

arguments are in the same order as MVC2, however the id value is no longer required:

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This avoids hard-coding any routing logic into the link.

 <a href="/Item/Login/5">Title</a> 

This will give you the following html output, assuming:

  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. you still have the following route defined

. .

routes.MapRoute(
    "Default",     // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

text-align: right on <select> or <option>

The best solution for me was to make

select {
    direction: rtl;
}

and then

option {
    direction: ltr;
}

again. So there is no change in how the text is read in a screen reader or and no formatting-problem.

MySQL: Error dropping database (errno 13; errno 17; errno 39)

in linux , Just go to "/var/lib/mysql" right click and (open as adminstrator), find the folder corresponding to your database name inside mysql folder and delete it. that's it. Database is dropped.

Setting a log file name to include current date in Log4j

As a response to the two answers which mention DailyRollingFileAppender (sorry, I don't have enough rep to comment on them directly, and I think this needs to be mentioned), I would warn that unfortunately the developers of that class have documented that it exhibits synchronization and data loss, and recommend that alternatives should be pursued for new deployments.

DailyRollingFileAppender JavaDoc

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How large should my recv buffer be when calling recv in the socket library

There is no absolute answer to your question, because technology is always bound to be implementation-specific. I am assuming you are communicating in UDP because incoming buffer size does not bring problem to TCP communication.

According to RFC 768, the packet size (header-inclusive) for UDP can range from 8 to 65 515 bytes. So the fail-proof size for incoming buffer is 65 507 bytes (~64KB)

However, not all large packets can be properly routed by network devices, refer to existing discussion for more information:

What is the optimal size of a UDP packet for maximum throughput?
What is the largest Safe UDP Packet Size on the Internet

Global javascript variable inside document.ready

JavaScript has Function-Level variable scope which means you will have to declare your variable outside $(document).ready() function.

Or alternatively to make your variable to have global scope, simply dont use var keyword before it like shown below. However generally this is considered bad practice because it pollutes the global scope but it is up to you to decide.

$(document).ready(function() {
   intro = null; // it is in global scope now

To learn more about it, check out:

Android OnClickListener - identify a button

The best way is by switch-ing between v.getId(). Having separate anonymous OnClickListener for each Button is taking up more memory. Casting View to Button is unnecessary. Using if-else when switch is possible is slower and harder to read. In Android's source you can often notice comparing the references by if-else:

if (b1 == v) {
 // ...
} else if (b2 == v) {

I don't know exactly why they chose this way, but it works too.

Why does .json() return a promise?

Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:

if the handler function:

  • returns a value, the promise returned by then gets resolved with the returned value as its value;
  • throws an error, the promise returned by then gets rejected with the thrown error as its value;
  • returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
  • returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
  • returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.

Difference between a virtual function and a pure virtual function

For a virtual function you need to provide implementation in the base class. However derived class can override this implementation with its own implementation. Normally , for pure virtual functions implementation is not provided. You can make a function pure virtual with =0 at the end of function declaration. Also, a class containing a pure virtual function is abstract i.e. you can not create a object of this class.

Need to combine lots of files in a directory

copy *.txt all.txt

This will concatenate all text files of the folder to one text file all.txt

If you have any other type of files, like sql files

copy *.sql all.sql

What is the garbage collector in Java?

Garbage collection refers to the process of automatically freeing memory on the heap by deleting objects that are no longer reachable in your program. The heap is a memory which is referred to as the free store, represents a large pool of unused memory allocated to your Java application.

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.

Basics

The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.

The common interfaces

The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:

  • CrudRepository - CRUD methods
  • PagingAndSortingRepository - methods for pagination and sorting (extends CrudRepository)

Store-specific interfaces

The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…) of JpaRepository which is different from delete(…) as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).

We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository.

Custom repository base interfaces

The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:

  1. Depending on a Spring Data repository interface couples your repository interface to the library. I don't think this is a particular issue as you'll probably use abstractions like Page or Pageable in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.
  2. By extending e.g. CrudRepository, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository that doesn't include the save(…) and delete(…) methods of CrudRepository.

The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:

interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }

interface ReadOnlyRepository<T> extends Repository<T, Long> {

  // Al finder methods go here
}

The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long for consistency. The second interface usually has all the find…(…) methods copied from CrudRepository and PagingAndSortingRepository but does not expose the manipulating ones. Read more on that approach in the reference documentation.

Summary - tl;dr

The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.

Iterating over dictionaries using 'for' loops

I have a use case where I have to iterate through the dict to get the key, value pair, also the index indicating where I am. This is how I do it:

d = {'x': 1, 'y': 2, 'z': 3} 
for i, (key, value) in enumerate(d.items()):
   print(i, key, value)

Note that the parentheses around the key, value are important, without them, you'd get an ValueError "not enough values to unpack".

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

png has a wider color pallete than gif and gif is properitary while png is not. gif can do animations, what normal-png cannot. png-transparency is only supported by browser roughly more recent than IE6, but there is a Javascript fix for that problem. Both support alpha transparency. In general I would say that you should use png for most webgraphics while using jpeg for photos, screenshots, or similiar because png compression does not work too good on thoose.

iOS9 Untrusted Enterprise Developer with no option to trust

Changes to Enterprise App Distribution Coming in iOS 9

iOS 9 introduces a new feature to help protect users from installing in-house apps from untrusted sources. While no new app signing or provisioning methods are required, the way your enterprise users manage in-house apps installed on their iOS 9 devices will change.

In-house apps installed using an MDM solution are explicitly trusted and will no longer prompt the user to trust the developer that signed and provisioned the app. If your enterprise app does not use an MDM solution, users who install your app for the first time will be prompted to trust the developer. All users who install your app for the first time will need an internet connection.

Using a new restriction, organizations can limit the apps installed on their devices to the in-house apps that they create. And a new interface in Settings allows users to see all enterprise apps installed from their organization.

Changes to Enterprise App Distribution Coming in iOS 9

Source: Official email sent from [email protected] to existing enterprise app developers.

Powershell 2 copy-item which creates a folder if doesn't exist

I have stumbled here twice, and this last time was a unique situation and even though I ditch using copy-item I wanted to post the solution I used.

Had a list of nothing but files with the full path and in majority of the case the files have no extensions. the -Recurse -Force option would not work for me so I ditched copy-item function and fell back to something like below using xcopy as I still wanted to keep it a one liner. Initially I tied with Robocopy but it is apparently looking for a file extension and since many of mine had no extension it considered it a directory.

$filelist = @("C:\Somepath\test\location\here\file","C:\Somepath\test\location\here2\file2")

$filelist | % { echo f | xcopy $_  $($_.Replace("somepath", "somepath_NEW")) }

Hope it helps someone.

How do I auto-resize an image to fit a 'div' container?

<style type="text/css">
    #container{
        text-align: center;
        width: 100%;
        height: 200px; /* Set height */
        margin: 0px;
        padding: 0px;
        background-image: url('../assets/images/img.jpg');
        background-size: content; /* Scaling down large image to a div */
        background-repeat: no-repeat;
        background-position: center;
    }
</style>

<div id="container>
    <!-- Inside container -->
</div>

Background color on input type=button :hover state sticks in IE

There might be a fix to <input type="button"> - but if there is, I don't know it.

Otherwise, a good option seems to be to replace it with a carefully styled a element.

Example: http://jsfiddle.net/Uka5v/

.button {
    background-color: #E3E1B8; 
    padding: 2px 4px;
    font: 13px sans-serif;
    text-decoration: none;
    border: 1px solid #000;
    border-color: #aaa #444 #444 #aaa;
    color: #000
}

Upsides include that the a element will style consistently between different (older) versions of Internet Explorer without any extra work, and I think my link looks nicer than that button :)

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

How to get the type of T from a member of a generic class or method?

Consider this: I use it to export 20 typed list by same way:

private void Generate<T>()
{
    T item = (T)Activator.CreateInstance(typeof(T));

    ((T)item as DemomigrItemList).Initialize();

    Type type = ((T)item as DemomigrItemList).AsEnumerable().FirstOrDefault().GetType();
    if (type == null) return;
    if (type != typeof(account)) //account is listitem in List<account>
    {
        ((T)item as DemomigrItemList).CreateCSV(type);
    }
}

exceeds the list view threshold 5000 items in Sharepoint 2010

SharePoint lists V: Techniques for managing large lists :

Tutorial By Microsoft

Level: Advanced

Length: 40 - 50 minutes

When a SharePoint list gets large, you might see warnings such as, “This list exceeds the list view threshold,” or “Displaying the newest results below.” Find out why these warnings occur, and learn ways to configure your large list so that it still provides useful information.

After completing this course you will be able to:

  • Learn what the List View Threshold is, and understand its benefits.
  • Create an index so that you can see more information in a view.
  • Create folders to better organize your large list.
  • Use Datasheet view for fast filtering and sorting of a large list.
  • Learn what the Daily Time Window for Large Queries is.
  • Use Key Filters for fast filtering within Standard view.
  • Sync a large list to SharePoint Workspace.
  • Export a large list to Excel. Link a large list in Access.

How to Determine the Screen Height and Width in Flutter

How to access screen size or pixel density or aspect ratio in flutter ?

We can access screen size and other like pixel density, aspect ration etc. with helps of MediaQuery.

syntex : MediaQuery.of(context).size.height

Class has no member named

I had a similar problem. It turned out, I was including an old header file of the same name from an old folder. I deleted the old file changed the #include directive to point to my new file and all was good.

Adding files to java classpath at runtime

You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;

public class ClassPathHacker {

  private static final Class[] parameters = new Class[]{URL.class};

  public static void addFile(String s) throws IOException {
    File f = new File(s);
    addFile(f);
  }//end method

  public static void addFile(File f) throws IOException {
    addURL(f.toURL());
  }//end method


  public static void addURL(URL u) throws IOException {

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class sysclass = URLClassLoader.class;

    try {
      Method method = sysclass.getDeclaredMethod("addURL", parameters);
      method.setAccessible(true);
      method.invoke(sysloader, new Object[]{u});
    } catch (Throwable t) {
      t.printStackTrace();
      throw new IOException("Error, could not add URL to system classloader");
    }//end try catch

   }//end method

}//end class

The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.

Write to rails console

I think you should use the Rails debug options:

logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"

https://guides.rubyonrails.org/debugging_rails_applications.html

Get Value From Select Option in Angular 4

    //in html file
    <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">Country</label>
                        <select class="form-control" formControlName="country" (change)="onCountryChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select Country  -- </option>
                            <option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
                            <div *ngIf="isEdit">
                                <option></option>
                            </div>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('country').invalid && studentForm.get('country').touched">
                <div *ngIf="studentForm.get('country').errors.required">*country is required</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">State</label>
                        <select class="form-control" formControlName="state" (change)="onStateChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select State -- </option>
                            <option *ngFor="let state of states" [value]="state.id">{{state.state_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('state').invalid && studentForm.get('state').touched">
                <div *ngIf="studentForm.get('state').errors.required">*state is enter code hererequired</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">City</label>
                        <select class="form-control" formControlName="city">
                            <option disabled selected value [ngValue]="null"> -- Select City -- </option>
                            <option *ngFor="let city of cities" [value]="city.id" >{{city.city_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('city').invalid && studentForm.get('city').touched">
                <div *ngIf="studentForm.get('city').errors.required">*city is required</div>
            </div>
    //then in component
    onCountryChange(countryId:number){
   this.studentServive.getSelectedState(countryId).subscribe(resData=>{
    this.states = resData;
   });
  }
  onStateChange(stateId:number){
    this.studentServive.getSelectedCity(stateId).subscribe(resData=>{
     this.cities = resData;
    });
   }`enter code here`

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

How to redirect to a 404 in Rails?

I wanted to throw a 'normal' 404 for any logged in user that isn't an admin, so I ended up writing something like this in Rails 5:

class AdminController < ApplicationController
  before_action :blackhole_admin

  private

  def blackhole_admin
    return if current_user.admin?

    raise ActionController::RoutingError, 'Not Found'
  rescue ActionController::RoutingError
    render file: "#{Rails.root}/public/404", layout: false, status: :not_found
  end
end

How do I determine the current operating system with Node.js

var isWin64 = process.env.hasOwnProperty('ProgramFiles(x86)');

Relation between CommonJS, AMD and RequireJS?

AMD

  • introduced in JavaScript to scale JavaScript project into multiple files
  • mostly used in browser based application and libraries
  • popular implementation is RequireJS, Dojo Toolkit

CommonJS:

  • it is specification to handle large number of functions, files and modules of big project
  • initial name ServerJS introduced in January, 2009 by Mozilla
  • renamed in August, 2009 to CommonJS to show the broader applicability of the APIs
  • initially implementation were server, nodejs, desktop based libraries

Example

upper.js file

exports.uppercase = str => str.toUpperCase()

main.js file

const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')

Summary

  • AMD – one of the most ancient module systems, initially implemented by the library require.js.
  • CommonJS – the module system created for Node.js server.
  • UMD – one more module system, suggested as a universal one, compatible with AMD and CommonJS.

Resources:

How to convert DataTable to class Object?

Initialize DataTable:

DataTable dt = new DataTable(); 
dt.Columns.Add("id", typeof(String)); 
dt.Columns.Add("name", typeof(String)); 
for (int i = 0; i < 5; i++)
{
    string index = i.ToString();
    dt.Rows.Add(new object[] { index, "name" + index });
}

Query itself:

IList<Class1> items = dt.AsEnumerable().Select(row => 
    new Class1
        {
            id = row.Field<string>("id"),
            name = row.Field<string>("name")
        }).ToList();

Search for "does-not-contain" on a DataFrame in pandas

I was having trouble with the not (~) symbol as well, so here's another way from another StackOverflow thread:

df[df["col"].str.contains('this|that')==False]

Python Finding Prime Factors

If you are looking for pre-written code that is well maintained, use the function sympy.ntheory.primefactors from SymPy.

It returns a sorted list of prime factors of n.

>>> from sympy.ntheory import primefactors
>>> primefactors(6008)
[2, 751]

Pass the list to max() to get the biggest prime factor.

In case you want the prime factors of n and also the multiplicities of each of them, use sympy.ntheory.factorint.

Given a positive integer n, factorint(n) returns a dict containing the prime factors of n as keys and their respective multiplicities as values.

>>> from sympy.ntheory import factorint
>>> factorint(6008)   # 6008 = (2**3) * (751**1)
{2: 3, 751: 1}

The code is tested against Python 3.6.9 and SymPy 1.1.1.

jQuery: selecting each td in a tr

You can simply do the following inside your TR loop:

$(this).find('td').each (function() {
  // do your cool stuff
});                          

How do I use NSTimer?

Something like this:

NSTimer *timer;

    timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
                     target: self
                     selector: @selector(handleTimer:)
                     userInfo: nil
                     repeats: YES];

How to unzip a file in Powershell?

Hey Its working for me..

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("put ur zip file path here")
foreach ($item in $zip.items()) {
  $shell.Namespace("destination where files need to unzip").CopyHere($item)
}

Lightbox to show videos from Youtube and Vimeo?

I've had a LOT of trouble with pretty photo and IE9. I also had issues with fancybox in IE.

For youtube.com, I'm having a lot of luck with CeeBox.

http://catcubed.com/2008/12/23/ceebox-a-thickboxvideobox-mashup/

Using command line arguments in VBscript

If you need direct access:

WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...

Install IPA with iTunes 12

Do not use any service similar to https://www.diawi.com/ as it can potentially have huge security implications. Using this kind of process and with some clever coding skills, a third party can inject extra stuff in you application. And they are basically charging you for something that you can do yourself.

In iTunes 12.7.x, it is still possible to install an ipa directly on a device with a simple drag-n-drop. Look at @ganesh ubale' solution here or the other answers at https://stackoverflow.com/a/46520816/609862 or https://stackoverflow.com/a/46229114/609862.

The Apple developer web site also have detailed information about how to configure a web site for installing an IPA wirelessly (by simply sharing the download link).

Eclipse error: "The import XXX cannot be resolved"

If you are working with Maven and have this problem, check the repository server (for example nexus server), if the artifact is there. Sometimes, they can change the name of the artifact and you try to get the artifact with its old name.

How to do the Recursive SELECT query in MySQL?

The accepted answer by @Meherzad only works if the data is in a particular order. It happens to work with the data from the OP question. In my case, I had to modify it to work with my data.

Note This only works when every record's "id" (col1 in the question) has a value GREATER THAN that record's "parent id" (col3 in the question). This is often the case, because normally the parent will need to be created first. However if your application allows changes to the hierarchy, where an item may be re-parented somewhere else, then you cannot rely on this.

This is my query in case it helps someone; note it does not work with the given question because the data does not follow the required structure described above.

select t.col1, t.col2, @pv := t.col3 col3
from (select * from table1 order by col1 desc) t
join (select @pv := 1) tmp
where t.col1 = @pv

The difference is that table1 is being ordered by col1 so that the parent will be after it (since the parent's col1 value is lower than the child's).

Ant task to run an Ant target only if a file exists?

Since Ant 1.8.0 there's apparently also resourceexists

From http://ant.apache.org/manual/Tasks/conditions.html

Tests a resource for existance. since Ant 1.8.0

The actual resource to test is specified as a nested element.

An example:

<resourceexists>
  <file file="${file}"/>
</resourceexists>

I was about rework the example from the above good answer to this question, and then I found this

As of Ant 1.8.0, you may instead use property expansion; a value of true (or on or yes) will enable the item, while false (or off or no) will disable it. Other values are still assumed to be property names and so the item is enabled only if the named property is defined.

Compared to the older style, this gives you additional flexibility, because you can override the condition from the command line or parent scripts:

<target name="-check-use-file" unless="file.exists">
    <available property="file.exists" file="some-file"/>
</target>
<target name="use-file" depends="-check-use-file" if="${file.exists}">
    <!-- do something requiring that file... -->
</target>
<target name="lots-of-stuff" depends="use-file,other-unconditional-stuff"/>

from the ant manual at http://ant.apache.org/manual/properties.html#if+unless

Hopefully this example is of use to some. They're not using resourceexists, but presumably you could?.....

What is the hamburger menu icon called and the three vertical dots icon called?

We call it the "ant" menu. Guess it was a good time to change since everyone had just gotten used to the hamburger.

Formula to check if string is empty in Crystal Reports

if {le_gur_bond.gur1}="" or IsNull({le_gur_bond.gur1})   Then
    ""
else 
 "and " + {le_gur_bond.gur2} + " of "+ {le_gur_bond.grr_2_address2}

Work on a remote project with Eclipse via SSH

I had the same problem 2 years ago and I solved it in the following way:

1) I build my projects with makefiles, not managed by eclipse 2) I use a SAMBA connection to edit the files inside Eclipse 3) Building the project: Eclipse calles a "local" make with a makefile which opens a SSH connection to the Linux Host. On the SSH command line you can give parameters which are executed on the Linux host. I use for that parameter a makeit.sh shell script which call the "real" make on the linux host. The different targets for building you can give also by parameters from the local makefile --> makeit.sh --> makefile on linux host.

Registry key Error: Java version has value '1.8', but '1.7' is required

After the latest automatic Java update, I could not run Java from the command prompt.

My path variable had 'C:\ProgramData\Oracle\Java\javapath;'

I could not cd into 'C:\ProgramData\Oracle\Java\javapath;' from the command prompt window, since it did not exist.

I removed C:\ProgramData\Oracle\Java\javapath;' from the path variable and replaced it with 'C:\Program Files\Java\jre1.8.0_141\bin;'

Run a Command Prompt command from Desktop Shortcut

Yes, make the shortcut's path

%comspec% /k <command>

where

  • %comspec% is the environment variable for cmd.exe's full path, equivalent to C:\Windows\System32\cmd.exe on most (if not all) Windows installs
  • /k keeps the window open after the command has run, this may be replaced with /c if you want the window to close once the command is finished running
  • <command> is the command you wish to run

How to uncompress a tar.gz in another directory

Extracts myArchive.tar to /destinationDirectory

Commands:

cd /destinationDirectory
pax -rv -f myArchive.tar -s ',^/,,'

Webpack how to build production code and how to use it

Use these plugins to optimize your production build:

  new webpack.optimize.CommonsChunkPlugin('common'),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin(),
  new webpack.optimize.AggressiveMergingPlugin()

I recently came to know about compression-webpack-plugin which gzips your output bundle to reduce its size. Add this as well in the above listed plugins list to further optimize your production code.

new CompressionPlugin({
      asset: "[path].gz[query]",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
})

Server side dynamic gzip compression is not recommended for serving static client-side files because of heavy CPU usage.

How to create a connection string in asp.net c#

add this in web.config file

           <configuration>
              <appSettings>
                 <add key="ConnectionString" value="Your connection string which contains database id and password"/>
            </appSettings>
            </configuration>

.cs file

 public ConnectionObjects()
 {           
    string connectionstring= ConfigurationManager.AppSettings["ConnectionString"].ToString();
 }

Hope this helps.

How to exit from the application and show the home screen?

Here's what i did:

SomeActivity.java

 @Override
    public void onBackPressed() {
            Intent newIntent = new Intent(this,QuitAppActivity.class);
            newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(newIntent);
            finish();
    }

QuitAppActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      finish();
}

Basically what you did is cleared all activities from the stack and launch QuitAppActivity, that will finish the task.

How to edit the legend entry of a chart in Excel?

The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.

Column headers become data series titles in graph legend

HTTP POST using JSON in Java

I found this question looking for solution about how to send post request from java client to Google Endpoints. Above answers, very likely correct, but not work in case of Google Endpoints.

Solution for Google Endpoints.

  1. Request body must contains only JSON string, not name=value pair.
  2. Content type header must be set to "application/json".

    post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
                       "{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
    
    
    
    public static void post(String url, String json ) throws Exception{
      String charset = "UTF-8"; 
      URLConnection connection = new URL(url).openConnection();
      connection.setDoOutput(true); // Triggers POST.
      connection.setRequestProperty("Accept-Charset", charset);
      connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
    
      try (OutputStream output = connection.getOutputStream()) {
        output.write(json.getBytes(charset));
      }
    
      InputStream response = connection.getInputStream();
    }
    

    It sure can be done using HttpClient as well.

How to provide a mysql database connection in single file in nodejs

var mysql = require('mysql');

var pool  = mysql.createPool({
    host     : 'yourip',
    port    : 'yourport',
    user     : 'dbusername',
    password : 'dbpwd',
    database : 'database schema name',
    dateStrings: true,
    multipleStatements: true
});


// TODO - if any pool issues need to try this link for connection management
// https://stackoverflow.com/questions/18496540/node-js-mysql-connection-pooling

module.exports = function(qry, qrytype, msg, callback) {

if(qrytype != 'S') {
    console.log(qry);
}

pool.getConnection(function(err, connection) {
    if(err) {
        if(connection)
            connection.release();
        throw err;
    } 

    // Use the connection
    connection.query(qry, function (err, results, fields) {
        connection.release();

        if(err) {
            callback('E#connection.query-Error occurred.#'+ err.sqlMessage);    
            return;         
        }

        if(qrytype==='S') {
            //for Select statement
            // setTimeout(function() {
                callback(results);      
            // }, 500);
        } else if(qrytype==='N'){
            let resarr = results[results.length-1];
            let newid= '';
            if(resarr.length)               
                newid = resarr[0]['@eid'];
            callback(msg + newid);
        } else if(qrytype==='U'){
            //let ret = 'I#' + entity + ' updated#Updated rows count: ' + results[1].changedRows;
            callback(msg);                      
        } else if(qrytype==='D'){
            //let resarr = results[1].affectedRows;
            callback(msg);
        }
    });

    connection.on('error', function (err) {
        connection.release();
        callback('E#connection.on-Error occurred.#'+ err.sqlMessage);   
        return;         
    });
});

}

Full Page <iframe>

This is what I have used in the past.

html, body {
  height: 100%;
  overflow: auto;
}

Also in the iframe add the following style

border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%

How to extract a string between two delimiters

If you have just a pair of brackets ( [] ) in your string, you can use indexOf():

String str = "ABC[ This is the text to be extracted ]";    
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

Cannot open include file: 'unistd.h': No such file or directory

If you're using ZLib in your project, then you need to find :

#if 1

in zconf.h and replace(uncomment) it with :

#if HAVE_UNISTD_H /* ...the rest of the line

If it isn't ZLib I guess you should find some alternative way to do this. GL.

C# get string from textbox

When using MVC, try using ViewBag. The best way to take input from textbox and displaying in View.

What is an instance variable in Java?

Instance variable is the variable declared inside a class, but outside a method: something like:

class IronMan {

    /** These are all instance variables **/
    public String realName;
    public String[] superPowers;
    public int age;

    /** Getters and setters here **/
}

Now this IronMan Class can be instantiated in another class to use these variables. Something like:

class Avengers {

    public static void main(String[] a) {
        IronMan ironman = new IronMan();
        ironman.realName = "Tony Stark";
        // or
        ironman.setAge(30);
    }

}

This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.

Getting year in moment.js

The year() function just retrieves the year component of the underlying Date object, so it returns a number.

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

How to show imageView full screen on imageView click?

Yes I got the trick.

public void onClick(View v) {

            if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ){
                imgDisplay.setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION );

            }
            else if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB )
                imgDisplay.setSystemUiVisibility( View.STATUS_BAR_HIDDEN );
            else{}

    }

But it didn't solve my problem completely. I want to hide the horizontal scrollview too, which is in front of the imageView (below), which can't be hidden in this.

How to find a text inside SQL Server procedures / triggers?

-- Declare the text we want to search for
DECLARE @Text nvarchar(4000);
SET @Text = 'employee';

-- Get the schema name, table name, and table type for:

-- Table names
SELECT
       TABLE_SCHEMA  AS 'Object Schema'
      ,TABLE_NAME    AS 'Object Name'
      ,TABLE_TYPE    AS 'Object Type'
      ,'Table Name'  AS 'TEXT Location'
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%'+@Text+'%'
UNION
 --Column names
SELECT
      TABLE_SCHEMA   AS 'Object Schema'
      ,COLUMN_NAME   AS 'Object Name'
      ,'COLUMN'      AS 'Object Type'
      ,'Column Name' AS 'TEXT Location'
FROM  INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%'+@Text+'%'
UNION
-- Function or procedure bodies
SELECT
      SPECIFIC_SCHEMA     AS 'Object Schema'
      ,ROUTINE_NAME       AS 'Object Name'
      ,ROUTINE_TYPE       AS 'Object Type'
      ,ROUTINE_DEFINITION AS 'TEXT Location'
FROM  INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_DEFINITION LIKE '%'+@Text+'%'
      AND (ROUTINE_TYPE = 'function' OR ROUTINE_TYPE = 'procedure');

Call a function on click event in Angular 2

Component code:

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

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  public items: Array<string>;

  constructor() {
    this.items = ["item1", "item2", "item3"]
  }

  public open(event, item) {
    alert('Open ' + item);
  }

}

View:

<ion-header>
  <ion-navbar primary>
    <ion-title>
      <span>My App</span>
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-item *ngFor="let item of items" (click)="open($event, item)">
      {{ item }}
    </ion-item>
  </ion-list>
</ion-content>

As you can see in the code, I'm declaring the click handler like this (click)="open($event, item)" and sending both the event and the item (declared in the *ngFor) to the open() method (declared in the component code).

If you just want to show the item and you don't need to get info from the event, you can just do (click)="open(item)" and modify the open method like this public open(item) { ... }

Laravel Carbon subtract days from current date

You can always use strtotime to minus the number of days from the current date:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
           ->get();

get string from right hand side

SQL> select substr('999123456789', greatest (-9, -length('999123456789')), 9) as value from dual;

VALUE
---------
123456789

SQL> select substr('12345', greatest (-9,  -length('12345')), 9) as value from dual;

VALUE
----
12345

The call to greatest (-9, -length(string)) limits the starting offset either 9 characters left of the end or the beginning of the string.

Is java.sql.Timestamp timezone specific?

It is specific from your driver. You need to supply a parameter in your Java program to tell it the time zone you want to use.

java -Duser.timezone="America/New_York" GetCurrentDateTimeZone

Further this:

to_char(new_time(sched_start_time, 'CURRENT_TIMEZONE', 'NEW_TIMEZONE'), 'MM/DD/YY HH:MI AM')

May also be of value in handling the conversion properly. Taken from here

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

This is due to using obsolete mysql-connection-java version, your MySQl is updated but not your MySQL jdbc Driver, you can update your connection jar from the official site Official MySQL Connector site. Good Luck.

Find index of last occurrence of a sub-string using T-SQL

Some of the other answers return an actual string whereas I had more need to know the actual index int. And the answers that do that seem to over-complicate things. Using some of the other answers as inspiration, I did the following...

First, I created a function:

CREATE FUNCTION [dbo].[LastIndexOf] (@stringToFind varchar(max), @stringToSearch varchar(max))
RETURNS INT
AS
BEGIN
    RETURN (LEN(@stringToSearch) - CHARINDEX(@stringToFind,REVERSE(@stringToSearch))) + 1
END
GO

Then, in your query you can simply do this:

declare @stringToSearch varchar(max) = 'SomeText: SomeMoreText: SomeLastText'

select dbo.LastIndexOf(':', @stringToSearch)

The above should return 23 (the last index of ':')

Hope this made it a little easier for someone!

How do I update Node.js?

Some Linux distributions such as Arch Linux have Node.js in their package repositories. On such systems it is better to use a standard package update procedure, such as pacman -Suy or analogous apt-get or yum commands.

As of now (Nov 2016) EPEL7 offers a pretty recent version of Node.js (6.9.1 which is an up-to-date LTS version offered on the Node.js home page). So on CentOS 7 and derivatives you can just add EPEL repository by yum install epel-release and yum install nodejs.

CentOS 6/EPEL6 has 0.10.x which isn't supported upstream since Oct 2016.

How to remove multiple deleted files in Git repository

The best solution if you don't care about staging modified files is to use git add -u as said by mshameers and/or pb2q.

If you just want to remove deleted files, but not stage any modified ones, I think you should use the ls-files argument with the --deleted option (no need to use regex or other complex args/options) :

git ls-files --deleted | xargs git rm

catch specific HTTP error in python

For Python 3.x

import urllib.request
from urllib.error import HTTPError
try:
    urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
    print(err.code)

Error:java: invalid source release: 8 in Intellij. What does it mean?

You need to click to the project Open Module Settings and change the path of your JDK, if in the file POM you use jdk 1.8, configure jdk 1.8 with correct path.

How can I calculate the number of lines changed between two commits in Git?

git diff --stat commit1 commit2

EDIT: You have to specify the commits as well (without parameters it compares the working directory against the index). E.g.

git diff --stat HEAD^ HEAD

to compare the parent of HEAD with HEAD.

how to get the base url in javascript

in resources/views/layouts/app.blade.php file

<script type="text/javascript">
    var baseUrl = '<?=url('');?>';
</script>

CSS: On hover show and hide different div's at the same time?

if the other div is sibling/child, or any combination of, of the parent yes

_x000D_
_x000D_
    .showme{ _x000D_
        display: none;_x000D_
    }_x000D_
    .showhim:hover .showme{_x000D_
        display : block;_x000D_
    }_x000D_
    .showhim:hover .hideme{_x000D_
        display : none;_x000D_
    }_x000D_
    .showhim:hover ~ .hideme2{ _x000D_
        display:none;_x000D_
    }
_x000D_
    <div class="showhim">_x000D_
        HOVER ME_x000D_
        <div class="showme">hai</div> _x000D_
        <div class="hideme">bye</div>_x000D_
    </div>_x000D_
    <div class="hideme2">bye bye</div>
_x000D_
_x000D_
_x000D_

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

In my case, same error was coming with JSP. This is how I got to the root of this issue: I went to the Network tab and clearly saw that the browser request to fetch the css was returning response header having "Content-type" : "text/html". I opened another tab and manually hit the request to fetch the css. It ended up returning a html log in form. Turns out that my web application had a url mapping for path = / Tomcat servlet entry : (@WebServlet({ "/, /index", }). So, any unmatching request URLs were somehow being matched to / and the corresponding servlet was returning a Log in html form. I fixed it by removing the mapping to /

Also, the tomcat configuration wrt handling css MIME-TYPE was already present.

Convert a string to an enum in C#

You can extend the accepted answer with a default value to avoid exceptions:

public static T ParseEnum<T>(string value, T defaultValue) where T : struct
{
    try
    {
        T enumValue;
        if (!Enum.TryParse(value, true, out enumValue))
        {
            return defaultValue;
        }
        return enumValue;
    }
    catch (Exception)
    {
        return defaultValue;
    }
}

Then you call it like:

StatusEnum MyStatus = EnumUtil.ParseEnum("Active", StatusEnum.None);

If the default value is not an enum the Enum.TryParse would fail and throw an exception which is catched.

After years of using this function in our code on many places maybe it's good to add the information that this operation costs performance!

Append String in Swift

Its very simple:

For ObjC:

     NSString *string1 = @"This is";
     NSString *string2 = @"Swift Language";

ForSwift:

    let string1 = "This is"
    let string2 = "Swift Language"

For ObjC AppendString:

     NSString *appendString=[NSString stringWithFormat:@"%@ %@",string1,string2];

For Swift AppendString:

    var appendString1 = "\(string1) \(string2)"
    var appendString2 = string1+string2

Result:

    print("APPEND STRING 1:\(appendString1)")
    print("APPEND STRING 2:\(appendString2)")

Complete Code In Swift:

    let string1 = "This is"
    let string2 = "Swift Language"
    var appendString = "\(string1) \(string2)"
    var appendString1 = string1+string2
    print("APPEND STRING1:\(appendString1)")
    print("APPEND STRING2:\(appendString2)")

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

Automating running command on Linux from Windows using PuTTY

Code:

using System;
using System.Diagnostics;
namespace playSound
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(args[0]);

            Process amixerMediaProcess = new Process();
            amixerMediaProcess.StartInfo.CreateNoWindow = false;
            amixerMediaProcess.StartInfo.UseShellExecute = false;
            amixerMediaProcess.StartInfo.ErrorDialog = false;
            amixerMediaProcess.StartInfo.RedirectStandardOutput = false;
            amixerMediaProcess.StartInfo.RedirectStandardInput = false;
            amixerMediaProcess.StartInfo.RedirectStandardError = false;
            amixerMediaProcess.EnableRaisingEvents = true;

            amixerMediaProcess.StartInfo.Arguments = string.Format("{0}","-ssh username@"+args[0]+" -pw password -m commands.txt");
            amixerMediaProcess.StartInfo.FileName = "plink.exe";
            amixerMediaProcess.Start();


            Console.Write("Presskey to continue . . . ");
            Console.ReadKey(true);
    }
}

}

Sample commands.txt:

ps

Link: https://huseyincakir.wordpress.com/2015/08/27/send-commands-to-a-remote-device-over-puttyssh-putty-send-command-from-command-line/

SQL DELETE with JOIN another table for WHERE condition

Due to the locking implementation issues, MySQL does not allow referencing the affected table with DELETE or UPDATE.

You need to make a JOIN here instead:

DELETE  gc.*
FROM    guide_category AS gc 
LEFT JOIN
        guide AS g 
ON      g.id_guide = gc.id_guide
WHERE   g.title IS NULL

or just use a NOT IN:

DELETE  
FROM    guide_category AS gc 
WHERE   id_guide NOT IN
        (
        SELECT  id_guide
        FROM    guide
        )

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

What i did was to uninstall and install the "^0.13.0". I confirm/ support this last answer. It worked for me as well. I had uninstall version "^0.800.0" and installed the "^0.13.0". rebuild your project it will work fine.

How to get a List<string> collection of values from app.config in WPF?

You could have them semi-colon delimited in a single value, e.g.

App.config

<add key="paths" value="C:\test1;C:\test2;C:\test3" />

C#

var paths = new List<string>(ConfigurationManager.AppSettings["paths"].Split(new char[] { ';' }));

How to convert JSON string into List of Java object?

StudentList studentList = mapper.readValue(jsonString,StudentList.class);

Change this to this one

StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

Angular 2: Get Values of Multiple Checked Checkboxes

create a list like :-

this.xyzlist = [
  {
    id: 1,
    value: 'option1'
  },
  {
    id: 2,
    value: 'option2'
  }
];

Html :-

<div class="checkbox" *ngFor="let list of xyzlist">
            <label>
              <input formControlName="interestSectors" type="checkbox" value="{{list.id}}" (change)="onCheckboxChange(list,$event)">{{list.value}}</label>
          </div>

then in it's component ts :-

onCheckboxChange(option, event) {
     if(event.target.checked) {
       this.checkedList.push(option.id);
     } else {
     for(var i=0 ; i < this.xyzlist.length; i++) {
       if(this.checkedList[i] == option.id) {
         this.checkedList.splice(i,1);
      }
    }
  }
  console.log(this.checkedList);
}

How to find day of week in php in a specific timezone

Standard letter-based representations of date parts are great, except the fact they're not so intuitive. The much more convenient way is to identify basic abstractions and a number of specific implementations. Besides, with this approach, you can benefir from autocompletion.

Since we're talking about datetimes here, it seems plausible that the basic abstraction is ISO8601DateTime. One of the specific implementations is current datetime, the one you need when a makes a request to your backend, hence Now() class. Second one which is of some use for you is a datetime adjusted to some timezone. Not surprisingly, it's called AdjustedAccordingToTimeZone. And finally, you need a day of the week in a passed datetime's timezone: there is a LocalDayOfWeek class for that. So the code looks like the following:

(new LocalDayOfWeek(
    new AdjustedAccordingToTimeZone(
        new Now(),
        new TimeZoneFromString($_POST['timezone'])
    )
))
    ->value();

For more about this approach, take a look here.

Send POST data using XMLHttpRequest

The code below demonstrates on how to do this.

var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

In case you have/create an object you can turn it into params using the following code, i.e:

var params = new Object();
params.myparam1 = myval1;
params.myparam2 = myval2;

// Turn the data object into an array of URL-encoded key/value pairs.
let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {
 urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
}

How to Retrieve value from JTextField in Java Swing?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Swingtest extends JFrame implements ActionListener
{
    JTextField txtdata;
    JButton calbtn = new JButton("Calculate");

    public Swingtest()
    {
        JPanel myPanel = new JPanel();
        add(myPanel);
        myPanel.setLayout(new GridLayout(3, 2));
        myPanel.add(calbtn);
        calbtn.addActionListener(this);
        txtdata = new JTextField();
        myPanel.add(txtdata);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == calbtn) {
            String data = txtdata.getText(); //perform your operation
            System.out.println(data);
        }
    }

    public static void main(String args[])
    {
        Swingtest g = new Swingtest();
        g.setLocation(10, 10);
        g.setSize(300, 300);
        g.setVisible(true);
    }
}

now its working

Select the values of one property on all objects of an array in PowerShell

I think you might be able to use the ExpandProperty parameter of Select-Object.

For example, to get the list of the current directory and just have the Name property displayed, one would do the following:

ls | select -Property Name

This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm).

ls | select -Property Name | gm

So, to expand the object to be that of the type of property you're looking at, you can do the following:

ls | select -ExpandProperty Name

In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:

$objects = ls | select -ExpandProperty Name

How can I calculate the difference between two ArrayLists?

In Java, you can use the Collection interface's removeAll method.

// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
    add("apple");
    add("orange");
}};

Collection secondList = new ArrayList() {{
    add("apple");
    add("orange");
    add("banana");
    add("strawberry");
}};

// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);

// Remove all elements in firstList from secondList
secondList.removeAll(firstList);

// Show the "after" list
System.out.println("Result: " + secondList);

The above code will produce the following output:

First List: [apple, orange]
Second List: [apple, orange, banana, strawberry]
Result: [banana, strawberry]

What does .class mean in Java?

It's a generics literal. It means that you don't know the type of class this Class instance is representing, but you are still using the generic version.

  • if you knew the class, you'd use Class<Foo>. That way you can create a new instance, for example, without casting: Foo foo = clazz.newInstance();
  • if you don't use generics at all, you'll get a warning at least (and not using generics is generally discouraged as it may lead to hard-to-detect side effects)

How can I remove non-ASCII characters but leave periods and spaces using Python?

Your question is ambiguous; the first two sentences taken together imply that you believe that space and "period" are non-ASCII characters. This is incorrect. All chars such that ord(char) <= 127 are ASCII characters. For example, your function excludes these characters !"#$%&\'()*+,-./ but includes several others e.g. []{}.

Please step back, think a bit, and edit your question to tell us what you are trying to do, without mentioning the word ASCII, and why you think that chars such that ord(char) >= 128 are ignorable. Also: which version of Python? What is the encoding of your input data?

Please note that your code reads the whole input file as a single string, and your comment ("great solution") to another answer implies that you don't care about newlines in your data. If your file contains two lines like this:

this is line 1
this is line 2

the result would be 'this is line 1this is line 2' ... is that what you really want?

A greater solution would include:

  1. a better name for the filter function than onlyascii
  2. recognition that a filter function merely needs to return a truthy value if the argument is to be retained:

    def filter_func(char):
        return char == '\n' or 32 <= ord(char) <= 126
    # and later:
    filtered_data = filter(filter_func, data).lower()
    

How to set max_connections in MySQL Programmatically

How to change max_connections

You can change max_connections while MySQL is running via SET:

mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 5000  |
+-----------------+-------+
1 row in set (0.00 sec)

To OP

timeout related

I had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.

I suggest that you increase this value to 100k or disable connection pooling Pooling=false

UPDATED

he has two questions.

Q1 - what happens if I disable pooling Slow down making DB connection. connection pooling is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool

Q2 - Can the value of pooling be increased or the maximum is 100?

you can increase but I'm sure what is MAX value, maybe max_connections in my.cnf

My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.

If you have Stress Test tool like JMeter you can test youself.

How can I use Oracle SQL developer to run stored procedures?

There are two possibilities, both from Quest Software, TOAD & SQL Navigator:

Here is the TOAD Freeware download: http://www.toadworld.com/Downloads/FreewareandTrials/ToadforOracleFreeware/tabid/558/Default.aspx

And the SQL Navigator (trial version): http://www.quest.com/sql-navigator/software-downloads.aspx

Center image in table td in CSS

<table style="width:100%;">
<tbody ><tr><td align="center">
<img src="axe.JPG" />
</td>
</tr>
</tbody>
</table>

or

td
{
    text-align:center;
}

in the CSS file

Apache redirect to another port

My apache listens to 2 different ports,

Listen 8080
Listen 80  

I use the 80 when i want a transparent URL and do not put the port after the URL useful for google services that wont allow local url?

But i use the 8080 for internal developing where i use the port as a reference for a "dev environment"

How do I change select2 box height

I came here looking for a way to specify the height of the select2-enabled dropdown. That what has worked for me:

.select2-container .select2-choice, .select2-result-label {
  font-size: 1.5em;
  height: 41px; 
  overflow: auto;
}

.select2-arrow, .select2-chosen {
  padding-top: 6px;
}

BEFORE:

enter image description here enter image description here

AFTER: select-2 enabled dropdown with css-defined height enter image description here

Swapping pointers in C (char, int)

You need to understand the different between pass-by-reference and pass-by-value.

Basically, C only support pass-by-value. So you can't reference a variable directly when pass it to a function. If you want to change the variable out a function, which the swap do, you need to use pass-by-reference. To implement pass-by-reference in C, need to use pointer, which can dereference to the value.

The function:

void intSwap(int* a, int* b)

It pass two pointers value to intSwap, and in the function, you swap the values which a/b pointed to, but not the pointer itself. That's why R. Martinho & Dan Fego said it swap two integers, not pointers.

For chars, I think you mean string, are more complicate. String in C is implement as a chars array, which referenced by a char*, a pointer, as the string value. And if you want to pass a char* by pass-by-reference, you need to use the ponter of char*, so you get char**.

Maybe the code below more clearly:

typedef char* str;
void strSwap(str* a, str* b);

The syntax swap(int& a, int& b) is C++, which mean pass-by-reference directly. Maybe some C compiler implement too.

Hope I make it more clearly, not comfuse.

What is correct media query for IPad Pro?

I can't guarantee that this will work for every new iPad Pro which will be released but this works pretty well as of 2019:

@media only screen and (min-width: 1024px) and (max-height: 1366px)
    and (-webkit-min-device-pixel-ratio: 1.5) and (hover: none) {
    /* ... */
}

Trigger event when user scroll to specific element - with jQuery

Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.

Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.

function elementInView(el) {
  // The vertical distance between the top of the page and the top of the element.
  var elementOffset = $(el).offset().top;
  // The height of the element, including padding and borders.
  var elementOuterHeight = $(el).outerHeight();
  // Height of the window without margins, padding, borders.
  var windowHeight = $(window).height();
  // The vertical distance between the top of the page and the top of the viewport.
  var scrollOffset = $(this).scrollTop();

  if (elementOuterHeight < windowHeight) {
    // Element is smaller than viewport.
    if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
      // Element is completely inside viewport, reveal the element!
      return true;
    }
  } else {
    // Element is larger than the viewport, handle visibility differently.
    // Consider it visible as soon as it's top half has filled the viewport.
    if (scrollOffset > elementOffset) {
      // The top of the viewport has touched the top of the element, reveal the element!
      return true;
    }
  }
  return false;
}

EditText underline below text property

You have to use a different background image, not color, for each state of the EditText (focus, enabled, activated).

http://android-holo-colors.com/

In the site above, you can get images from a lot of components in the Holo theme. Just select "EditText" and the color you want. You can see a preview at the bottom of the page.

Download the .zip file, and copy paste the resources in your project (images and the XML).

if your XML is named: apptheme_edit_text_holo_light.xml (or something similar):

  1. Go to your XML "styles.xml" and add the custom EditText style:

    <style name="EditTextCustomHolo" parent="android:Widget.EditText">
       <item name="android:background">@drawable/apptheme_edit_text_holo_light</item>
       <item name="android:textColor">#ffffff</item>
    </style>
    
  2. Just do this in your EditText:

    <EditText
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       style="@style/EditTextCustomHolo"/>
    

And that's it, I hope it helps you.

How do I check if a list is empty?

The truth value of an empty list is False whereas for a non-empty list it is True.

How do I choose the URL for my Spring Boot webapp?

You need to set the property server.contextPath to /myWebApp.

Check out this part of the documentation

The easiest way to set that property would be in the properties file you are using (most likely application.properties) but Spring Boot provides a whole lot of different way to set properties. Check out this part of the documentation

EDIT

As has been mentioned by @AbdullahKhan, as of Spring Boot 2.x the property has been deprecated and should be replaced with server.servlet.contextPath as has been correctly mentioned in this answer.

Get values from a listbox on a sheet

Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)

Dim StrSelection As String

Private Sub ListBox1_Change()
    If ListBox1.Selected(ListBox1.ListIndex) Then
        If StrSelection = "" Then
            StrSelection = ListBox1.List(ListBox1.ListIndex)
        Else
            StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
        End If
    Else
        StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
    End If
End Sub

Get current NSDate in timestamp format

If you'd like to call this method directly on an NSDate object and get the timestamp as a string in milliseconds without any decimal places, define this method as a category:

@implementation NSDate (MyExtensions)
- (NSString *)unixTimestampInMilliseconds
{
     return [NSString stringWithFormat:@"%.0f", [self timeIntervalSince1970] * 1000];
}

Binary search (bisection) in Python

Using a dict wouldn't like double your memory usage unless the objects you're storing are really tiny, since the values are only pointers to the actual objects:

>>> a = 'foo'
>>> b = [a]
>>> c = [a]
>>> b[0] is c[0]
True

In that example, 'foo' is only stored once. Does that make a difference for you? And exactly how many items are we talking about anyway?

SQL, Postgres OIDs, What are they and why are they useful?

OID's are still in use for Postgres with large objects (though some people would argue large objects are not generally useful anyway). They are also used extensively by system tables. They are used for instance by TOAST which stores larger than 8KB BYTEA's (etc.) off to a separate storage area (transparently) which is used by default by all tables. Their direct use associated with "normal" user tables is basically deprecated.

The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables.

Apparently the OID sequence "does" wrap if it exceeds 4B 6. So in essence it's a global counter that can wrap. If it does wrap, some slowdown may start occurring when it's used and "searched" for unique values, etc.

See also https://wiki.postgresql.org/wiki/FAQ#What_is_an_OID.3F

PHP Try and Catch for SQL Insert

You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:

// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;

// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}

function my_mysql_query($query, $conn=false) {
    $res = mysql_query($query, $conn);
    if (!$res) {
        $errno = mysql_errno($conn);
        $error = mysql_error($conn);
        switch ($errno) {
        case MYSQL_DUPLICATE_KEY_ENTRY:
            throw new MySQLDuplicateKeyException($error, $errno);
            break;
        default:
            throw MySQLException($error, $errno);
            break;
        }
    }
    // ...
    // doing something
    // ...
    if ($something_is_wrong) {
        throw new Exception("Logic exception while performing query result processing");
    }

}

try {
    mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
    // duplicate entry exception
    $e->getMessage();
}
catch (MySQLException $e) {
    // other mysql exception (not duplicate key entry)
    $e->getMessage();
}
catch (Exception $e) {
    // not a MySQL exception
    $e->getMessage();
}

iPhone system font

afaik iPhone uses "Helvetica" by default < iOS 10

On Duplicate Key Update same as insert

The UPDATE statement is given so that older fields can be updated to new value. If your older values are the same as your new ones, why would you need to update it in any case?

For eg. if your columns a to g are already set as 2 to 8; there would be no need to re-update it.

Alternatively, you can use:

INSERT INTO table (id,a,b,c,d,e,f,g)
VALUES (1,2,3,4,5,6,7,8) 
ON DUPLICATE KEY
    UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;

To get the id from LAST_INSERT_ID; you need to specify the backend app you're using for the same.

For LuaSQL, a conn:getlastautoid() fetches the value.

How to count the occurrence of certain item in an ndarray?

take advantage of the methods offered by a Series:

>>> import pandas as pd
>>> y = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
>>> pd.Series(y).value_counts()
0    8
1    4
dtype: int64

npm notice created a lockfile as package-lock.json. You should commit this file

It should also be noted that one key detail about package-lock.json is that it cannot be published, and it will be ignored if found in any place other than the top level package. It shares a format with npm-shrinkwrap.json(5), which is essentially the same file, but allows publication. This is not recommended unless deploying a CLI tool or otherwise using the publication process for producing production packages.

If both package-lock.json and npm-shrinkwrap.json are present in the root of a package, package-lock.json will be completely ignored.

Converting a string to JSON object

Simply use eval function.

var myJson = eval(theJsibStr);

Copy output of a JavaScript variable to the clipboard

For general purposes of copying any text to the clipboard, I wrote the following function:

function textToClipboard (text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

The value of the parameter is inserted into value of a newly created <textarea>, which is then selected, its value is copied to the clipboard and then it gets removed from the document.

Spring Boot Rest Controller how to return different HTTP status codes?

There are different ways to return status code, 1 : RestController class should extends BaseRest class, in BaseRest class we can handle exception and return expected error codes. for example :

@RestController
@RequestMapping
class RestController extends BaseRest{

}

@ControllerAdvice
public class BaseRest {
@ExceptionHandler({Exception.class,...})
    @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorModel genericError(HttpServletRequest request, 
            HttpServletResponse response, Exception exception) {
        
        ErrorModel error = new ErrorModel();
        resource.addError("error code", exception.getLocalizedMessage());
        return error;
    }

Matplotlib discrete colorbar

I have been investigating these ideas and here is my five cents worth. It avoids calling BoundaryNorm as well as specifying norm as an argument to scatter and colorbar. However I have found no way of eliminating the rather long-winded call to matplotlib.colors.LinearSegmentedColormap.from_list.

Some background is that matplotlib provides so-called qualitative colormaps, intended to use with discrete data. Set1, e.g., has 9 easily distinguishable colors, and tab20 could be used for 20 colors. With these maps it could be natural to use their first n colors to color scatter plots with n categories, as the following example does. The example also produces a colorbar with n discrete colors approprately labelled.

import matplotlib, numpy as np, matplotlib.pyplot as plt
n = 5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x % 11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)

which produces the image below. The n in the call to Set1 specifies the first n colors of that colormap, and the last n in the call to from_list specifies to construct a map with n colors (the default being 256). In order to set cm as the default colormap with plt.set_cmap, I found it to be necessary to give it a name and register it, viz:

cm = from_list('Set15', plt.cm.Set1(range(0,n)), n)
plt.cm.register_cmap(None, cm)
plt.set_cmap(cm)
...
plt.scatter(x, y, c=z)

scatterplot with disrete colors

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

You can try putting 'Access-Control-Allow-Origin':'*' in response.writeHead(, {[here]}).

"unrecognized selector sent to instance" error in Objective-C

On my case I solved the problem after 2 hours :

The sender (a tabBar item) wasn't having any Referencing Outlet. So it was pointing nowhere.

Juste create a referencing outlet corresponding to your function.

Hope this could help you guys.

Android, How to read QR code in my application?

Zxing is an excellent library to perform Qr code scanning and generation. The following implementation uses Zxing library to scan the QR code image Don't forget to add following dependency in the build.gradle

implementation 'me.dm7.barcodescanner:zxing:1.9'

Code scanner activity:

    public class QrCodeScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
        private ZXingScannerView mScannerView;

        @Override
        public void onCreate(Bundle state) {
            super.onCreate(state);
            // Programmatically initialize the scanner view
            mScannerView = new ZXingScannerView(this);
            // Set the scanner view as the content view
            setContentView(mScannerView);
        }

        @Override
        public void onResume() {
            super.onResume();
            // Register ourselves as a handler for scan results.
            mScannerView.setResultHandler(this);
            // Start camera on resume
            mScannerView.startCamera();
        }

        @Override
        public void onPause() {
            super.onPause();
            // Stop camera on pause
            mScannerView.stopCamera();
        }

        @Override
        public void handleResult(Result rawResult) {
            // Do something with the result here
            // Prints scan results
            Logger.verbose("result", rawResult.getText());
            // Prints the scan format (qrcode, pdf417 etc.)
            Logger.verbose("result", rawResult.getBarcodeFormat().toString());
            //If you would like to resume scanning, call this method below:
            //mScannerView.resumeCameraPreview(this);
            Intent intent = new Intent();
            intent.putExtra(AppConstants.KEY_QR_CODE, rawResult.getText());
            setResult(RESULT_OK, intent);
            finish();
        }
    }

Creating java date object from year,month,day

Make your life easy when working with dates, timestamps and durations. Use HalDateTime from

http://sourceforge.net/projects/haldatetime/?source=directory

For example you can just use it to parse your input like this:

HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate );   // will print in ISO format: 1988-12-25

You can also specify patterns for parsing and printing.

Extract XML Value in bash script

As Charles Duffey has stated, XML parsers are best parsed with a proper XML parsing tools. For one time job the following should work.

grep -oPm1 "(?<=<title>)[^<]+"

Test:

$ echo "$data"
<item> 
  <title>15:54:57 - George:</title>
  <description>Diane DeConn? You saw Diane DeConn!</description> 
</item> 
<item> 
  <title>15:55:17 - Jerry:</title> 
  <description>Something huh?</description>
$ title=$(grep -oPm1 "(?<=<title>)[^<]+" <<< "$data")
$ echo "$title"
15:54:57 - George:

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

Is it possible to have a default parameter for a mysql stored procedure?

If you look into CREATE PROCEDURE Syntax for latest MySQL version you'll see that procedure parameter can only contain IN/OUT/INOUT specifier, parameter name and type.

So, default values are still unavailable in latest MySQL version.

Python: Differentiating between row and column vectors

The excellent Pandas library adds features to numpy that make these kinds of operations more intuitive IMO. For example:

import numpy as np
import pandas as pd

# column
df = pd.DataFrame([1,2,3])

# row
df2 = pd.DataFrame([[1,2,3]])

You can even define a DataFrame and make a spreadsheet-like pivot table.

What is time_t ultimately a typedef to?

What is ultimately a time_t typedef to?

Robust code does not care what the type is.

C species time_t to be a real type like double, long long, int64_t, int, etc.

It even could be unsigned as the return values from many time function indicating error is not -1, but (time_t)(-1) - This implementation choice is uncommon.

The point is that the "need-to-know" the type is rare. Code should be written to avoid the need.


Yet a common "need-to-know" occurs when code wants to print the raw time_t. Casting to the widest integer type will accommodate most modern cases.

time_t now = 0;
time(&now);
printf("%jd", (intmax_t) now);
// or 
printf("%lld", (long long) now);

Casting to a double or long double will work too, yet could provide inexact decimal output

printf("%.16e", (double) now);

Is there a way to pass optional parameters to a function?

The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.

First, you can use special formal parameter syntax *. If the function definition has a formal parameter preceded by a single *, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.

For instance, here's a function opt_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "optional".

>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
...     if ('optional' in keyword_parameters):
...         print 'optional parameter found, it is ', keyword_parameters['optional']
...     else:
...         print 'no optional parameter, sorry'
... 
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is  yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry

Second, you can supply a default parameter value of some value like None which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.

Import text file as single character string

readChar doesn't have much flexibility so I combined your solutions (readLines and paste).

I have also added a space between each line:

con <- file("/Users/YourtextFile.txt", "r", blocking = FALSE)
singleString <- readLines(con) # empty
singleString <- paste(singleString, sep = " ", collapse = " ")
close(con)

Set Locale programmatically

There is a super simple way.

in BaseActivity, Activity or Fragment override attachBaseContext

 override fun attachBaseContext(context: Context) {
    super.attachBaseContext(context.changeLocale("tr"))
}

extension

fun Context.changeLocale(language:String): Context {
    val locale = Locale(language)
    Locale.setDefault(locale)
    val config = this.resources.configuration
    config.setLocale(locale)
    return createConfigurationContext(config)
}

MVC 4 Razor File Upload

The Upload method's HttpPostedFileBase parameter must have the same name as the the file input.

So just change the input to this:

<input type="file" name="file" />

Also, you could find the files in Request.Files:

[HttpPost]
public ActionResult Upload()
{
     if (Request.Files.Count > 0)
     {
         var file = Request.Files[0];

         if (file != null && file.ContentLength > 0)
         {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
            file.SaveAs(path);
         }
     }

     return RedirectToAction("UploadDocument");
 }