zwwcn

Just another WordPress.com site

JQuery notes

  1. How to add listener for html content loaded by ajax call?

    Bind on a non-dynamic parent container using .on()

    $('.some-parent-class').on('click', '.element', function() {
      // DO STUFF!
    });
  2. AddClass function

      AddClass function always check exisitng classes before adding new one, so we don’t need to check duplicate classes

     3. Find function

       The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree

     4. text() and textarea

       The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method

      5. checkbox and prop

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

      6. toggle

Quick way to switch show/hide, checked/unchecked state

$('#checkBoxId').click(function() {
    $("#otherCheckbox").toggle(this.checked);
});

       7. event.preventDefault()

Cancel the default action (navigation) of the click, this is used when we only want to trigger a js function but don’t want the page navagation.

 

Advertisements

access javascript object property using variable

I want to assign data to a js object as a property, but the new property name is dynamic.

The bracket notation should be used here:

var apiDynamicString = "dynamicStringFromOtherFunction";

var apiDynamicData ="somedata...";

example.data[apiDynamicString] = apiDynamicData ;

Then you can access the property this way:

console.log(example.data[apiDynamicString]);

OR (if you know the variable value)

console.log(example.data.dynamicStringFromOtherFunction);

javascript onclick event not working in chrome

The onclick event for select option is not triggered in chrome. We need to fire the onchange event on the select component.

<select class="select-one-group-select">
 <option class="select-one-group-option" value="option1">option 1</option>
 <option class="select-one-group-option"  value="option2">option 2</option>
 <option class="select-one-group-option"  value="option3">option 3</option>
</select>

This doesn’t work:

	$(".select-one-group-option").click(function() {
		showFilters(parseInt(this.value));
	});

 

This solve the problem:

	$(".select-one-group-select").change(function() {
		showFilters(parseInt(this.value));
	});

JPA native query with parameter

I tried ?name but couldn’t get it working. I end up with using number (?1 ,?2) to build up my dynamic query and it works properly.
Query query = em.createNativeQuery(“SELECT * FROM OP_CHECKLIST c WHERE c.DATE BETWEEN ?1 AND ?2 “);

Query query = em.createNativeQuery("SELECT * FROM OP_CHECKLIST c WHERE c.DATE BETWEEN ?1 AND ?2 ");
query.setParameter("1", sdf.format(fromDate));
query.setParameter("2", sdf.format(endDate));

Set Content Security Policy for Cordova app

I’m getting some error when debuging my cordova app on Android device.  The error msg is

Refused to load the image 'data:image/png;base64,....' because it violates the following Content Security Policy directive: "img-src 'self' data".

I googled it and found that I need to set content security policy meta tag.

This link gives detailed example and helped me solve the problem.

MySQL innodb file too large

We had problem when altering one of our largest table in MySQL server. Eventually we managed to apply the change, but MySQL wouldn’t release the disk space it took for temp table. MySQL mark the data as deleted, but it still holding the space. This link gives good answer on this problem:

Optimize innodb table when innodb_file_per_table disable

Read photo taken date from image

For Java, I use metadata-extractor:

Metadata metadata = ImageMetadataReader.readMetadata( item.getInputStream());
ExifSubIFDDirectory directory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
if(date != null){
    file.setPhotoTakenDate(date);
}

For front end, I use exif-js:

window.resolveLocalFileSystemURL(attachmentInfo.fileSource, (fileEntry) ->
                fileEntry.file((file) ->
                    EXIF.getData(file, ->
                    	
                        galleryPhotoTakenDate = EXIF.getTag(this,"DateTimeOriginal");
                      
                        cameraPhotoTakenDate = this.lastModifiedDate;

                        if photoFromCamera
                            if typeof cameraPhotoTakenDate != 'undefined'
                                #photo taken from camera
                                attachmentInfo.photoTakenDate = moment(cameraPhotoTakenDate).format("YYYY:MM:DD HH:mm:SS")
                        else
                            if typeof galleryPhotoTakenDate != 'undefined'
                                #photo taken from gallery
                                attachmentInfo.photoTakenDate = galleryPhotoTakenDate 
                            
                    )                    
                )
                    
            )

getting distinct row count in hibernate criteria

Projections.rowCount could return a wrong result when joining is used in the criteria. I used “setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)” in the criteria to get the distinct items but it  doesn’t work with Projections.rowCount.

 

 

 
This won’t work, it still contain duplicates:

	public Criteria countDefaultCriteria(){
		return getIncidentsDefaultCriteria().setProjection(Projections.rowCount());
	}

This give the correct row count:

	public Criteria countDefaultCriteria(){
		return getIncidentsDefaultCriteria().setProjection(Projections.countDistinct("objID"));
	}

Solution to MySQL server has gone away

Add max_allowed_packet into my.ini, e.g: max_allowed_packet=1073741824

Json mapping exception:

Exception: Can not construct instance of abc.bcd.def.entity from String value ‘NONE’: value not one of declared Enum instance names

Solution: add @JsonCreator to the enum getter method.

	    @JsonCreator
	    public static InvestigatedBy fromName(String optionName) {
			if (optionName == null) {
				return null;
			}
			for (InvestigatedBy entry: InvestigatedBy.values()) {
				if (entry.getName().equals(optionName)) {
					return entry;
				}
			}
			return null;
		}