I had a some Issue of font rendering with NotosansCJK(Google Opensource font) and freetype 2
My freetype version is 2.8.1 and here is a part of my code when I make bitmap from Ft to create opengl texture.
[Rendering alphabet with freetype library]
bool bRender = false;
FT_Error fError;
uint uCharIndex;
if(m_tFTFace == KD_NULL)
{
return bRender;
}
if( m_nCharFontSize != nCharFontSize )
{
if(SetCharSize(nCharFontSize) == KD_FALSE)
{
return bRender;
}
}
uCharIndex = FT_Get_Char_Index(m_tFTFace,(FT_ULong)uCharUnicode);
if(uCharIndex == 0)
{
return bRender;
}
fError = FT_Load_Glyph(m_tFTFace,uCharIndex, FT_LOAD_DEFAULT | FT_LOAD_NO_BITMAP );
if(fError)
{
return bRender;
}
if(m_nExtraBoldthick > 0)
{
FT_Outline_Embolden(&m_tFTFace->glyph->outline, (m_tFTFace->size->metrics.x_ppem*m_nExtraBoldthick/100)*64);
}
fError = FT_Render_Glyph(m_tFTFace->glyph,FT_RENDER_MODE_NORMAL);
if(fError)
{
return bRender;
}
else
{
bRender = KD_TRUE;
}
if( bRender == KD_TRUE )
{
m_uRenderedUnicode = uCharUnicode;
}
return bRender;
[Make an alpha bitmap]
FT_Face pFace = m_oTtfFont.GetFontFace();
int nBitmapWidth,nBitmapHeight;
nBitmapWidth = pFace->glyph->bitmap.width;
nBitmapHeight = pFace->glyph->bitmap.rows;
kdMemset( pBitmap->m_aBitmap, 0, sizeof(KDubyte)*32*32);
int nTX = pFace->glyph->bitmap_left + 32/2 - (pFace->glyph->advance.x>>6) ;
int nTY = 0;
int y = nBitmapHeight;
while( y-- > 0 )
{
nTX = pFace->glyph->bitmap_left;
if(nTX < 0)
{
nBitmapWidth = pFace->glyph->bitmap.width + nTX;
nTX = 0;
}
else
{
nBitmapWidth = pFace->glyph->bitmap.width;
}
for (int x = 0; x < nBitmapWidth; x++)
{
pBitmap->m_aBitmap[nTY][nTX] = pFace->glyph->bitmap.buffer[(y*nBitmapWidth)+x];
nTX++;
}
nTY++;
}
Almost all of alphabets are rendering correctly but some of results are abnormal especially English if I use a character size more than 15.
all of notosancjk font has similar problem when I test it
this is the result using NotoSansCJKkr-Bold.otf and the character size is 20
[result - normal] - alphabet O
[result - abnormal] - alphabet V
I think it's a problem of freetype library or NotosanCJK font because There has no problem when I use another fonts but I'm not sure it is the real reasons.
Do anyone guess the reason of this Issue?
Thanks
Related
This is a function if the endValueFixed is equal for example 12.0 I want to print the number without zero so I want it to be 12.
void calculateIncrease() {
setState(() {
primerResult = (startingValue * percentage) / 100;
endValue = startingValue + primerResult;
endValueFixe`enter code here`d = roundDouble(endValue, 2);
});
}
This may be an overkill but it works exactly as you wish:
void main() {
// This is your double value
final end = 98.04;
String intPart = "";
String doublePart = "";
int j = 0;
for (int i = 0; i < end.toString().length; i++) {
if (end.toString()[i] != '.') {
intPart += end.toString()[i];
} else {
j = i + 1;
break;
}
}
for (int l = j; l < end.toString().length; l++) {
doublePart += end.toString()[l];
}
if (doublePart[0] == "0" && doublePart[1] != "0") {
print(end);
} else {
print(end.toString());
}
}
You may use this code as a function and send whatever value to end.
if (endValueFixed==12) {
print('${endValueFixed.toInt()}');
}
conditionally cast it to an int and print it then :)
I don't know how convert java "continue" to scala.
I can use marker from bool + break, but its bad idea
Google did not help :(
It's my first program in scala... yep.. it's horrible
sort java
def sort(in: Array[Int], a:Int, b:Int)
{
var i,j,mode;
double sr=0;
if (a>=b) return; // size =0
for (i=a; i<=b; i++) sr+=in[i];
sr=sr/(b-a+1);
for (i=a, j=b; i <= j;)
{
if (in[i]< sr) { i++; continue; } // left > continue
if (in[j]>=sr) { j--; continue; } // right, continue
int c = in[i]; in[i] = in[j]; in[j]=c;
i++,j--; // swap and continue
}
if (i==a) return;
sort(in,a,j); sort(in,i,b);
}
sort scala...
def SortMerger(in:List[Int], a:Int, b:Int):Unit = {
var i = 0;
var j = 0;
var mode = 0;
var sr = 0.0;
if(a>=b) return;
i=a
while(i<=b)
{
sr+=in.ElementOf(i);
i += 1
}
sr=sr/(b-a+1)
i=a
j=b
while(i<=j)
{
if(in.ElementOf(i)<sr) {
i += 1;
// where continue??? ><
}
}
return
}
Scala has no continue statement, but what you are trying to do can be done with a simple if/else structure.
while(i<=j)
{
if(in(i) < sr) {
i += 1
} else if (in(j) >= sr) {
j -= 1
} else {
int c = in(i)
in(i) = in(j)
in(j) = c
i += 1
j -= 1
}
}
Note that the type of in here should be Array, not List
I believe this can be achieved by counting the instances for each character in that string. Even if a single character in that string is repeated at least twice, we can declare that string as a palindrome.
For example: bbcccc can be rewritten as bccccb or ccbbcc.
edified can be rewritten as deified.
Some book mentioned we should be using hash table. I think we can just use a list and check for the character count.
Do you think the logic is correct?
Yes, the main idea is to count the times of each char existing in the string. And it will be true if the string has at most one char occurs odd times and all others even times.
For example:
aabbcc => acbbca
aabcc => acbca
aabbb => abbba
No. You don't have to use a hash map (as some of the other answers suggest). But the efficiency of the solution will be determined by the algorithm you use.
Here is a solution that only tracks odd characters. If we get 2 odds, we know it can't be a scrambled palindrome. I use an array to track the odd count. I reuse the array index 0 over and over until I find an odd. Then I use array index 1. If I find 2 odds, return false!
Solution without a hash map in javascript:
function isScrambledPalindrome(input) {
// TODO: Add error handling code.
var a = input.split("").sort();
var char, nextChar = "";
var charCount = [ 0 ];
var charIdx = 0;
for ( var i = 0; i < a.length; ++i) {
char = a[i];
nextChar = a[i + 1] || "";
charCount[charIdx]++;
if (char !== nextChar) {
if (charCount[charIdx] % 2 === 1) {
if (charCount.length > 1) {
// A scrambled palindrome can only have 1 odd char count.
return false;
}
charIdx = 1;
charCount.push(0);
} else if (charCount[charIdx] % 2 === 0) {
charCount[charIdx] = 0;
}
}
}
return true;
}
console.log("abc: " + isScrambledPalindrome("abc")); // false
console.log("aabbcd: " + isScrambledPalindrome("aabbcd")); // false
console.log("aabbb: " + isScrambledPalindrome("aabbb")); // true
console.log("a: " + isScrambledPalindrome("a")); // true
Using a hash map, I found a cool way to only track the odd character counts and still determine the answer.
Fun javascript hash map solution:
function isScrambledPalindrome( input ) {
var chars = {};
input.split("").forEach(function(char) {
if (chars[char]) {
delete chars[char]
} else {
chars[char] = "odd" }
});
return (Object.keys(chars).length <= 1);
}
isScrambledPalindrome("aba"); // true
isScrambledPalindrome("abba"); // true
isScrambledPalindrome("abca"); // false
Any string can be palindrome only if at most one character occur odd no. of times and all other characters must occur even number of times.
The following program can be used to check whether a palindrome can be string or not.
vector<int> vec(256,0); //Vector for all ASCII characters present.
for(int i=0;i<s.length();++i)
{
vec[s[i]-'a']++;
}
int odd_count=0,flag=0;
for(int i=0;i<vec.size();++i)
{
if(vec[i]%2!=0)
odd_count++;
if(odd_count>1)
{
flag=1;
cout<<"Can't be palindrome"<<endl;
break;
}
}
if(flag==0)
cout<<"Yes can be palindrome"<<endl;
My code check if can it is palindrome or can be manipulated to Palindrome
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
//Tested on windows 64 bit arhc by using cygwin64 and GCC
bool isPalindrome (char *text);
int main()
{
char text[100]; // it could be N with defining N
bool isPal,isPosPal = false;
printf("Give me a string to test if it is Anagram of Palindrome\n");
gets(text);
isPal = isPalindrome(text);
isPosPal = isAnagramOfPalindrome(text);
if(isPal == false)
{
printf("Not a palindrome.\n");
}
else
{
printf("Palindrome.\n");
}
if(isPosPal == false)
{
printf("Not Anagram of Palindrome\n");
}
else
{
printf("Anagram of Palindrome\n");
}
return 0;
}
bool isPalindrome (char *text) {
int begin, middle, end, length = 0;
length = getLength(text);
end = length - 1;
middle = length/2;
for (begin = 0; begin < middle; begin++)
{
if (text[begin] != text[end])
{
return false;
}
end--;
}
if (begin == middle)
return true;
}
int getLength (char *text) {
int length = 0;
while (text[length] != '\0')
length++;
printf("length: %d\n",length);
return length;
}
int isAnagramOfPalindrome (char *text) {
int length = getLength(text);
int i = 0,j=0;
bool arr[26] = {false};
int counter = 0;
//char string[100]="neveroddoreven";
int a;
for (i = 0; i < length; i++)
{
a = text[i];
a = a-97;
if(arr[a])
{
arr[a] = false;
}
else
{
arr[a] = true;
}
}
for(j = 0; j < 27 ; j++)
{
if (arr[a] == true)
{
counter++;
}
}
printf("counter: %d\n",counter);
if(counter > 1)
{
return false;
}
else if(counter == 1)
{
if(length % 2 == 0)
return false;
else
return true;
}
else if(counter == 0)
{
return true;
}
}
as others have posted, the idea is to have each character occur an even number of times for an even length string, and one character an odd number of times for an odd length string.
The reason the books suggest using a hash table is due to execution time. It is an O(1) operation to insert into / retrieve from a hash map. Yes a list can be used but the execution time will be slightly slower as the sorting of the list will be O(N log N) time.
Pseudo code for a list implementation would be:
sortedList = unsortedList.sort;
bool oddCharFound = false;
//if language does not permit nullable char then initialise
//current char to first element, initialise count to 1 and loop from i=1
currentChar = null;
currentCharCount = 0;
for (int i=0; i <= sortedList.Length; i++) //start from first element go one past end of list
{
if(i == sortedList.Length
|| sortedList[i] != currentChar)
{
if(currentCharCount % 2 = 1)
{
//check if breaks rule
if((sortedList.Length % 2 = 1 && oddCharFound)
|| oddCharFound)
{
return false;
}
else
{
oddCharFound = true;
}
}
if(i!= sortedList.Length)
{
currentCharCount = 1;
currentChar = sortedList[i];
}
}
else
{
currentCharCount++;
}
}
return true;
Here is a simple solution using an array; no sort needed
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[256] = { 0 };
unsigned char i[] = {"aaBcBccc"};
unsigned char *p = &i[0];
int c = 0;
int j;
int flag = 0;
while (*p != 0)
{
a[*p]++;
p++;
}
for(j=0; j<256; j++)
{
if(a[j] & 1)
{
c++;
if(c > 1)
{
flag = 1;
break;
}
}
}
if(flag)
printf("Nope\n");
else
printf("yup\n");
return 0;
}
C#:
bool ok = s.GroupBy(c => c).Select(g => g.Count()).Where(c => c == 1).Count() < 2;
This solution, however, does use hashing.
Assuming all input characters are lower case letters.
#include<stdio.h>
int main(){
char *str;
char arr[27];
int j;
int a;
j = 0;
printf("Enter the string : ");
scanf("%s", str);
while (*str != '\0'){
a = *str;
a = a%27;
if(arr[a] == *str){
arr[a]=0;
j--;
}else{
arr[a] = *str;
j++;
}
*str++;
}
if(j==0 || j== -1 || j==1){
printf ("\nThe string can be a palindrome\n");
}
}
I'm building an App with actionscript 3.0 in my Flash builder. This is a followup question to this question, It works but when I take the picture, the image comes out rotated to the left. how can I check which way the user is holding the phone? and then what code do I use to rotate the image to it's corresponding place?
Thanks in advanced!
EDIT:
I'm using this code to rotate the image, but it seems to only rotate the image being displayed not the image file, any ideas?
var mat:Matrix = new Matrix();
mat.translate(-W/2, -H/2);
mat.rotate(Math.PI/2);
mat.translate(+W/2, +H/2);
mat.concat(myObj.transform.matrix);
myObj.transform.matrix = mat;
~Myy
You can't get stage.orientation data when you have the cameraUI view active, so here's how i solved the same issue, please note that this controller has many reusable functions, i first get the raw image data from media promise (this raw data has EXIF data that i will read to get image orientation from the camera) i then convert this byteArray to BitmapData and then resize and scale as i need. One thing to note is that if you convert the raw image data to Bitmap data you will lose EXIF data so read it before you modify the image, hope this helps and i posted it here late i know but there's no other solution in the web and maybe someone will need this sometime. Cheers
SnapshotController.as
package controllers
{
import flash.display.BitmapData;
import flash.display.JPEGEncoderOptions;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.events.MediaEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.media.CameraUI;
import flash.media.MediaPromise;
import flash.media.MediaType;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import mx.utils.Base64Encoder;
import classes.APIupload;
public class SnapshotController
{
private var cameraUI:CameraUI = new CameraUI();
private var dataSource:IDataInput;
private var tempDir:File = new File();
private var imageOrientation:int = 0 ;
public function SnapshotController()
{
}
public function LaunchCameraUI():void
{
if( CameraUI.isSupported ) {
trace( "Initializing camera..." );
cameraUI.addEventListener( MediaEvent.COMPLETE, imageSelected );
cameraUI.launch( MediaType.IMAGE );
} else {
trace( "CameraUI is not supported.");
}
}
private function imageSelected( event:MediaEvent ):void {
trace( "Media selected..." );
var imagePromise:MediaPromise = event.data;
dataSource = imagePromise.open();
if( imagePromise.isAsync ) {
trace( "Asynchronous media promise." );
var eventSource:IEventDispatcher = dataSource as IEventDispatcher;
eventSource.addEventListener( Event.COMPLETE, onMediaLoaded );
} else {
trace( "Synchronous media promise." );
readMediaData();
}
}
private function onMediaLoaded( event:Event ):void {
trace("Media load complete");
readMediaData();
}
private function readMediaData():void {
var imageBytes:ByteArray = new ByteArray();
dataSource.readBytes( imageBytes );
imageOrientation = getOrientation(imageBytes);
//saveImageFile(imageBytes);
//Saving this byteArray will save a big file with the EXIF in it.
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, onMediaPromiseLoaded);
loader.loadBytes(imageBytes);
}
private function onMediaPromiseLoaded(e:Event):void
{
trace("Media file loaded");
var base64Enc:Base64Encoder = new Base64Encoder();
var mpLoaderInfo:LoaderInfo = e.target as LoaderInfo;
mpLoaderInfo.removeEventListener(Event.COMPLETE, onMediaPromiseLoaded);
var scale:Number = 0.25;
var matrix:Matrix = new Matrix();
matrix.scale(scale, scale);
var jpgQuality:int = 80;
var bmd:BitmapData = new BitmapData(mpLoaderInfo.width*scale, mpLoaderInfo.height*scale);
bmd.draw(mpLoaderInfo.content,matrix,null,null,null,true);
var rotatedBMD:BitmapData = rotateBitmapData(bmd, imageOrientation);
var bytes:ByteArray = rotatedBMD.encode(new Rectangle(0,0, rotatedBMD.width , rotatedBMD.height), new JPEGEncoderOptions(jpgQuality), bytes);
saveImageFile(bytes); //this is the smaller file saved. it does not have EXIF data but you can write your own using AS3 eXIF class.
}
private function rotateBitmapData( bitmapData:BitmapData, degree:int = 0 ) :BitmapData
{
var newBitmap:BitmapData;
var matrix:Matrix = new Matrix();
matrix.rotate( degree * (Math.PI / 180) );
if ( degree == 90 ) {
newBitmap = new BitmapData( bitmapData.height, bitmapData.width, true );
matrix.translate( bitmapData.height, 0 );
} else if ( degree == -90 || degree == 270) {
newBitmap = new BitmapData( bitmapData.height, bitmapData.width, true );
matrix.translate( 0, bitmapData.width );
} else if ( degree == 180 ) {
newBitmap = new BitmapData( bitmapData.width, bitmapData.height, true );
matrix.translate( bitmapData.width, bitmapData.height );
}else if(degree == 0){
newBitmap = new BitmapData( bitmapData.width, bitmapData.height, true );
//matrix.translate( bitmapData.width, bitmapData.height );
}
newBitmap.draw( bitmapData, matrix, null, null, null, true )
return newBitmap;
}
private function saveImageFile(ba:ByteArray):void{
var now:Date = new Date();
var filename:String = "IMG" + now.fullYear + now.month + now.day + now.hours + now.minutes + now.seconds + ".jpg";
var temp:File = File.documentsDirectory.resolvePath( filename );
var stream:FileStream = new FileStream();
stream.open( temp, FileMode.WRITE );
stream.writeBytes( ba );
stream.close();
}
private function getOrientation(jpeg:ByteArray):int{
if (jpeg == null) {
return 0;
}
var offset:int = 0;
var length:int = 0;
while (offset + 3 < jpeg.length && (jpeg[offset++] & 0xFF) == 0xFF) {
var marker:int = jpeg[offset] & 0xFF;
// Check if the marker is a padding.
if (marker == 0xFF) {
continue;
}
offset++;
// Check if the marker is SOI or TEM.
if (marker == 0xD8 || marker == 0x01) {
continue;
}
// Check if the marker is EOI or SOS.
if (marker == 0xD9 || marker == 0xDA) {
break;
}
// Get the length and check if it is reasonable.
length = pack(jpeg, offset, 2, false);
if (length < 2 || offset + length > jpeg.length) {
trace("Invalid length");
return 0;
}
// Break if the marker is EXIF in APP1.
if (marker == 0xE1 && length >= 8 &&
pack(jpeg, offset + 2, 4, false) == 0x45786966 &&
pack(jpeg, offset + 6, 2, false) == 0) {
offset += 8;
length -= 8;
break;
}
// Skip other markers.
offset += length;
length = 0;
}
if (length > 8) {
// Identify the byte order.
var tag:int = pack(jpeg, offset, 4, false);
if (tag != 0x49492A00 && tag != 0x4D4D002A) {
trace("Invalid byte order");
return 0;
}
var littleEndian:Boolean = (tag == 0x49492A00);
// Get the offset and check if it is reasonable.
var count:int = pack(jpeg, offset + 4, 4, littleEndian) + 2;
if (count < 10 || count > length) {
trace( "Invalid offset");
return 0;
}
offset += count;
length -= count;
// Get the count and go through all the elements.
count = pack(jpeg, offset - 2, 2, littleEndian);
while (count-- > 0 && length >= 12) {
// Get the tag and check if it is orientation.
tag = pack(jpeg, offset, 2, littleEndian);
if (tag == 0x0112) {
// We do not really care about type and count, do we?
var orientation:int = pack(jpeg, offset + 8, 2, littleEndian);
switch (orientation) {
case 1:
return 0;
case 3:
return 180;
case 6:
return 90;
case 8:
return 270;
}
trace( "Unsupported orientation");
return 0;
}
offset += 12;
length -= 12;
}
}
trace( "Orientation not found");
return 0;
}
private function pack(bytes:ByteArray,offset:int,length:int,
littleEndian:Boolean):int {
var step:int = 1;
if (littleEndian) {
offset += length - 1;
step = -1;
}
var value:int = 0;
while (length-- > 0) {
value = (value << 8) | (bytes[offset] & 0xFF);
offset += step;
}
return value;
}
}
}
You can use Stage.deviceOrientation or Stage.orientation* to determine which way round the phone is.
*not sure if this one works on iOS
Is it the BitmapData result itself that you want to rotate (ie create a new BitmapData with rotated image) or just rotate a Bitmap on the display list?
Edit:
Ok, heres some code to rotate a BitmapData object:
function rotateBitmapData(angle:int, source:BitmapData):BitmapData
{
var newWidth:int = source.rect.width;
var newHeight:int = source.rect.height;
if (angle==90 || angle==270)
{
newWidth = source.rect.height;
newHeight = source.rect.width;
}
var newBmd:BitmapData = new BitmapData(newWidth, newHeight, source.transparent);
var tx:Number = 0;
var ty:Number = 0;
if (angle==90 || angle==180)
{
tx = newWidth;
}
if (angle==180 || angle==270)
{
ty = newHeight;
}
var matrix:Matrix = new Matrix();
matrix.createBox(1, 1, Math.PI*angle/180, tx, ty);
newBmd.draw(source, matrix);
return newBmd;
}
angle should be 0,90,180 or 270. It will return a new BitmapData object rotated by specified angle.
You can use StageOrientationEvent.ORIENTATION_CHANGING Event :
stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGING, OrientationChangeHandler);
private function OrientationChangeHandler(e:StageOrientationEvent):void
{
switch (e.afterOrientation)
{
case StageOrientation.DEFAULT :
break;
case StageOrientation.ROTATED_RIGHT :
break;
case StageOrientation.ROTATED_LEFT :
break;
case StageOrientation.UPSIDE_DOWN :
break;
}
}
this can help you.
I am reading a value sent over RS485 which is the value of an encoder I first check if it has returned an E character (the encoder is reporting an error) and if not then do the following
*position = atoi( buffer );
// Also tried *position = (s32) strtol(buffer,NULL,10);
The value in the buffer is 4033536 and position gets set to 33536 this does not happen every time in this function probably 1 in 1000 times maybe although I am not counting. Setting the program counter back and doing the line again if has failed returns the same result but starting the debugger again causes the value to convert correctly.
I am using keil uvision 4, its a custom board using an stm32f103vet6 and the stm32f10 library V2.0.1 This one has really got me stumped never come across something like this before any help would be much appreciated.
Thanks
As no one knows I will just post what I ended up doing which was to write my own function for convertion not ideal but it worked.
bool cdec2s32(char* text, s32 *destination)
{
s32 tempResult = 0;
char currentChar;
u8 numDigits = 0;
bool negative = FALSE;
bool warning = FALSE;
if(*text == '-')
{
negative = TRUE;
text++;
}
while(*text != 0x00 && *text != '\r') //while current character not null or carridge return
{
numDigits++;
if(*text >= '0' && *text <= '9')
{
currentChar = *text;
currentChar -= '0';
if((warning && ((currentChar > 7 && !negative) || currentChar > 8 && negative )) || numDigits > 10) // Check number not too large
{
tempResult = 2147483647;
if(negative)
tempResult *= -1;
*destination = tempResult;
return FALSE;
}
tempResult *= 10;
tempResult += currentChar;
text++;
if(numDigits >= 9)
{
if(tempResult >= 214748364)
{
warning = TRUE; //Need to check next digit as close to limit
}
}
}
else if(*text == '.' || *text == ',')
{
break;
}
else
return FALSE;
}
if(negative)
tempResult *= -1;
*destination = tempResult;
return TRUE;
}