Tuesday, December 10, 2013

Javascript ile Türkçe heceleme uygulaması

Eğer sayfalarınızdaki metinlerde Türkçe heceleme uygulaması ihtiyacınız varsa bu kod ile, düz metinlere heceleme karakteri eklemeniz mümkün.

// Hecleme
function Hecele(Sozcuk)
{
 var Sozcukler = Sozcuk.split(" ");
 
 for (var i2 = 0; i2 < Sozcukler.length; i2++) 
 {
  var i=-1;
  while (i < Sozcukler[i2].length)
  {
   i++;

   if ((Sozcukler[i2].charAt(i) == "a") || (Sozcukler[i2].charAt(i) == "ı") || (Sozcukler[i2].charAt(i) == "o") || (Sozcukler[i2].charAt(i) == "u") || (Sozcukler[i2].charAt(i) == "e") || (Sozcukler[i2].charAt(i) == "i") || (Sozcukler[i2].charAt(i) == "ö") || (Sozcukler[i2].charAt(i) == "ü"))
   {
    SonucVar = false;
    //sağ tarafındaki ilk harf sesli mi
    if (i < (Sozcukler[i2].length-1))
    {
     if ((Sozcukler[i2].charAt(i+1) == "a") || (Sozcukler[i2].charAt(i+1) == "ı") || (Sozcukler[i2].charAt(i+1) == "o") || (Sozcukler[i2].charAt(i+1) == "u") || (Sozcukler[i2].charAt(i+1) == "e") || (Sozcukler[i2].charAt(i+1) == "i") || (Sozcukler[i2].charAt(i+1) == "ö") || (Sozcukler[i2].charAt(i+1) == "ü"))
     {
      i++;
      Sozcukler[i2] = [Sozcukler[i2].slice(0, i), "-", Sozcukler[i2].slice(i)].join('');
      SonucVar = true;
     }
    }

    //sağ tarafındaki ikinci harf sesli mi
    if ( (i < (Sozcukler[i2].length-2)) && (!SonucVar) )
    {
     if ((Sozcukler[i2].charAt(i+2) == "a") || (Sozcukler[i2].charAt(i+2) == "ı") || (Sozcukler[i2].charAt(i+2) == "o") || (Sozcukler[i2].charAt(i+2) == "u") || (Sozcukler[i2].charAt(i+2) == "e") || (Sozcukler[i2].charAt(i+2) == "i") || (Sozcukler[i2].charAt(i+2) == "ö") || (Sozcukler[i2].charAt(i+2) == "ü"))
     {
      i++;
      Sozcukler[i2] = [Sozcukler[i2].slice(0, i), "-", Sozcukler[i2].slice(i)].join('');
      SonucVar = true;
     }
    }

    //sağ tarafındaki üçüncü harf sesli mi
    if ( (i < (Sozcukler[i2].length-3)) && (!SonucVar) )
    {
     if ((Sozcukler[i2].charAt(i+3) == "a") || (Sozcukler[i2].charAt(i+3) == "ı") || (Sozcukler[i2].charAt(i+3) == "o") || (Sozcukler[i2].charAt(i+3) == "u") || (Sozcukler[i2].charAt(i+3) == "e") || (Sozcukler[i2].charAt(i+3) == "i") || (Sozcukler[i2].charAt(i+3) == "ö") || (Sozcukler[i2].charAt(i+3) == "ü"))
     {
      i++;
      i++;
      Sozcukler[i2] = [Sozcukler[i2].slice(0, i), "-", Sozcukler[i2].slice(i)].join('');
      SonucVar = true;
     }
    }

   }
  }
 }

 var Sonuc = "";
 for (var i2 = 0; i2 < Sozcukler.length; i2++) 
 {
  Sonuc += Sozcukler[i2];
  if ( i2 < Sozcukler.length-1 ) { Sonuc += " "; }
 }
 
 return Sonuc;
}

Monday, October 28, 2013

Homemade Laptop

Dual Boot (Raspberry Pi, Android 4.0), WiFi, Wireless Keyboard&Mouse, Built-in Arduino, Battery (1 hour runtime)/ Cable Operated, On-board Premium Speakers, 1386x768 screen resolution. Can Run Screenless for 8 hours.








Saturday, January 5, 2013

Arduino CnC

Here is something I've been thinking about developing it, it is still on the drawing board :)

Arduino CnC

Arduino CnC is complete solution that acts as a gateway between your Arduino and the internet. Using Arduino CnC you will be able to communicate with your Arduino using any device connected to the internet. You can monitor and process sensory data from your Tablet. Use your phones browser to turn LEDs on and off, change RGB color, drive motors and servos. Opening a whole new world to Arduino Developers.

Diagram of how Arduino CnC works:


 
Terms:

Slave Client: The PC that the Arduino is connect to.
Arduino: The Arduino connected to the Slave Client.
Control Page: The html5 and javascript code that is used to monitor and control the Arduino.
Arduino CnC: The cloud server running jabber, the online IDE, and the host for the Control Pages.
Control Client: Tablet, Laptop, Phone, etc. that open the Control Pages that are hosted on the Arduino CnC using their web browsers.
Base Sketch: The original sketch that can read and write to all pins on the Arduino. The Base Sketch also includes code that allows the Control Page to initialize the pins as well as set the update frequencies for the Arduino.


How it works:

From the Arduino
1) The Slave Client is started, after which it logs into the Arduino CnC using its username and password.
2) The Slave Client then establishes a serial communication to the Arduino.
3) A heat sensor connected to the Arduino is read by the Base Sketch.
4) The Base Sketch then writes this data using the USB serial communication to the Slave Client. The message also includes userID of the receiving Control Client.
5) The Slave Client sends this message string to Arduino CnC. (Only the Control Page that the message was sent to will be able to see and respond to it.)
6) The Arduino CnC stores the message and waits for the Control Client  to come online to send the message.
7) The Control Client uses the Control Page to receiving and print the message to the screen.

To the Arduino
1) The Slave Client is started, after which it logs into Arduino CnC using its username and password.
2) The Slave Client then establishes a serial communication to the Arduino.
3) A Control Client opens a Control Page.
4) User press a HTML button on the Control Client.
5) The Control Page running on the Control Client, authenticates with Arduino CnC and passes the message string along with the recipient.
6) Arduino CnC stores the message waiting for the Slave Client to come online. If the Slave Client is already online the message is forwarded without any delay.
7) The receiving Slave Client uses the already established USB connection to pass the message string along to the Arduino.
8) The Base Sketch on the Arduino receives the message and turns a LED on.


Base Sketch

Using the Base Sketch it will be possible to read and write and perform most common function with the Arduino without having to write and upload any custom sketch.

The Base Sketch will allow to get analog feedback, set pins to input/output. Read pin values and set PWM on digital pins. You can also program the Arduino to continuously send data using the Base Sketch. This would allow for receiving heat and humidity data every second without having to make a request for each read.

Advanced Development

The Base Sketch can be used as a template to include other functions such as servo control, I2C data reading, etc. The authors will be encouraged to share these sketches with the community using Arduino CnC or GIThub, etc.

We will be adding sketches derived from the Base Sketch for servo and step motor control. One-wire heat sensor communication, humidity and temperature sensors, LCD screen controls, etc.

Basic Client Development using Control Pages

The simplest way to build a client for your Arduino will be to study our one led example javascript code.

To run this sample you will have to:

1) Sign up to the cloud server.
2) Add two username and password pairs.
3) Download and Install the Desktop Client.
4) From the desktop client settings screen select your Arduino and enter one of the username password pairs you created using the cloud service.
5) Upload the C&C Base sketch to your Arduino
6) Click on the example.html in the cloud. You can load this from your phone or tablet as well.
7) Fill in the login information (the second username and password you created). Also type the username you created for your PC client as the receiving devices ID.
8) That’s it, now pressing the buttons on your tablet should blink and turn the status led connected to Pin 13 on your arduino board.

After completing the steps above you can try our one button example. For this you will need to attach a button to your Arduino. You can choose any pin you want to as this will be set from the HTML page. After completing the steps for the Led example you will see that when you press the button that you connected to your Arduino, a rectangle on your tablet will light up. And when you press this rectangle the status led on pin 13 on your Arduino will turn on.

The basic client uses jsonp to run. This way we have to sacrifice some speed for flexibility. The client has to establish and login for each request. However it allows for the html to run from any host or domain with pure HTML5 code, a single html file with embedded javascript is all you need.
For real-time communication please continue reading.


Advanced Client Development

Arduino CnC uses the well know jabber/GTalk XMPP protocol for communication. For more real-time communication you will need to keep your communication to the cloud server open all the time. This can be done using almost every language. You will find PHP, Android and iOS samples for this in the repository. Each sample runs a jabber chat client within. The client connects to the cloud server and keeps the connection open. When you press a button on the client the message is sent directly to your Arduino without a delay. Similarly any message coming from the arduino is received by the client device and displayed. The examples uses a pot on the analog pins that the Arduino samples 10 times each second and relays to the cloud and then to the client which in Turn draws this as a moving time graph on your screen.

If you have a servo connected to your Arduino you can also try rotating it using the onscreen controls found on the sample apps.

Saturday, December 1, 2012

MySQL Language names, native names and ISO 639-1 codes

Hello,

Recently I needed to make a language selection table. Didn't find it as an MySQL restore file so made one myself.

If you find yourself in need of most spoken languages with their native names and two-letter codes. Here it is:

DROP TABLE IF EXISTS `languages`;
CREATE TABLE `languagesx` (
  `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Name` varchar(145) NOT NULL,
  `NativeName` varchar(145) NOT NULL,
  `ISO639_1` varchar(45) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
 


Insert Into Languages (Name,NativeName,ISO639_1) VALUES ('Abkhazian','Аҧсуа','ab'),
('Afar','Afaraf','aa'),
('Afrikaans','Afrikaans','af'),
('Akan','Akan','ak'),
('Albanian','Shqip','sq'),
('Amharic','አማርኛ','am'),
('Arabic','العربية','ar'),
('Aragonese','Aragonés','an'),
('Assamese','অসমীয়া','as'),
('Armenian','Հայերեն','hy'),
('Avaric','авар мацӀ','av'),
('Avestan','avesta','ae'),
('Aymara','aymar aru','ay'),
('Azerbaijani','azərbaycan dili','az'),
('Bashkir','башҡорт теле','ba'),
('Bambara','bamanankan','bm'),
('Basque','euskara','eu'),
('Belarusian','Беларуская','be'),
('Bengali','বাংলা','bn'),
('Bihari','भोजपुरी','bh'),
('Bislama','Bislama','bi'),
('Bosnian','bosanski jezik','bs'),
('Breton','brezhoneg','br'),
('Bulgarian','български език','bg'),
('Burmese','ဗမာစာ','my'),
('Catalan; Valencian','Català','ca'),
('Chamorro','Chamoru','ch'),
('Chechen','нохчийн мотт','ce'),
('Chichewa','chinyanja','ny'),
('Chinese','"中文 (Zhōngwén), 汉语, 漢語"','zh'),
('Chuvash','чӑваш чӗлхи','cv'),
('Cornish','Kernewek','kw'),
('Corsican','corsu','co'),
('Cree','ᓀᐦᐃᔭᐍᐏᐣ','cr'),
('Croatian','hrvatski','hr'),
('Czech','česky','cs'),
('Danish','dansk','da'),
('Maldivian','ދިވެހި','dv'),
('Dzongkha','རྫོང་ཁ','dz'),
('English','English','en'),
('Esperanto','Esperanto','eo'),
('Estonian','eesti','et'),
('Ewe','Eʋegbe','ee'),
('Faroese','føroyskt','fo'),
('Fijian','vosa Vakaviti','fj'),
('Finnish','suomi','fi'),
('French','français','fr'),
('Fula','Pular','ff'),
('Galician','Galego','gl'),
('German','Deutsch','de'),
('Greek','Ελληνικά','el'),
('Guaraní','Avañe''ẽ','gn'),
('Gujarati','ગુજરાતી','gu'),
('Haitian','Kreyòl ayisyen','ht'),
('Hausa','"Hausa, هَوُسَ"','ha'),
('Hebrew','עברית','he'),
('Herero','Otjiherero','hz'),
('Hindi','हिन्दी, हिंदी"','hi'),
('Hiri Motu','Hiri Motu','ho'),
('Hungarian','Magyar','hu'),
('Indonesian','Bahasa Indonesia','id'),
('Irish','Gaeilge','ga'),
('Igbo','Igbo','ig'),
('Inupiaq','Iñupiaq','ik'),
('Ido','Ido','io'),
('Icelandic','Íslenska','is'),
('Italian','Italiano','it'),
('Inuktitut','ᐃᓄᒃᑎᑐᑦ','iu'),
('Japanese','日本語','ja'),
('Javanese','basa Jawa','jv'),
('Georgian','ქართული','ka'),
('Kongo','KiKongo','kg'),
('Kazakh','Қазақ тілі','kk'),
('Central Khmer','ភាសាខ្មែរ','km'),
('Kannada','ಕನ್ನಡ','kn'),
('Korean','韓國語','ko'),
('Kanuri','Kanuri','kr'),
('Kashmiri','"कश्मीरी, كشميري‎"','ks'),
('Kurdish','Kurdî','ku'),
('Komi','коми кыв','kv'),
('Kirghiz','кыргыз тили','ky'),
('Latin','latine','la'),
('Luxembourgish','Lëtzebuergesch','lb'),
('Luganda','Luganda','lg'),
('Lingala','Lingála','ln'),
('Lao','ພາສາລາວ','lo'),
('Lithuanian','lietuvių kalba','lt'),
('Luba-Katanga','','lu'),
('Latvian','latviešu valoda','lv'),
('Malagasy','Malagasy fiteny','mg'),
('Marshallese','Kajin M̧ajeļ','mh'),
('Manx','"Gaelg, Gailck"','gv'),
('Māori','te reo Māori','mi'),
('Macedonian','македонски јазик','mk'),
('Malayalam','മലയാളം','ml'),
('Mongolian','Монгол','mn'),
('Marathi','मराठी','mr'),
('Malay','"bahasa Melayu, بهاس ملايو‎"','ms'),
('Maltese','Malti','mt'),
('Nauru','Ekakairũ Naoero','na'),
('North Ndebele','isiNdebele','nd'),
('Nepali','नेपाली','ne'),
('Ndonga','Owambo','ng'),
('Dutch','Nederlands','nl'),
('Norwegian','Norsk','no'),
('South Ndebele','isiNdebele','nr'),
('Navajo','Diné bizaad','nv'),
('Oromo','Afaan Oromoo','om'),
('Oriya','ଓଡ଼ିଆ','or'),
('Ossetian','Ирон æвзаг','os'),
('Punjabi','"ਪੰਜਾਬੀ','pa'),
('Pāli','पाऴि','pi'),
('Persian','فارسی','fa'),
('Polish','polski','pl'),
('Portuguese','Português','pt'),
('Quechua','Kichwa','qu'),
('Kirundi','Rundi','rn'),
('Romanian','română','ro'),
('Russian','Русский язык','ru'),
('Kinyarwanda','Ikinyarwanda','rw'),
('Sanskrit','संस्कृतम्','sa'),
('Sardinian','sardu','sc'),
('Sindhi','"सिन्धी, سنڌي، سندھی‎"','sd'),
('Northern Sami','Davvisámegiella','se'),
('Samoan','gagana fa''a Samoa','sm'),
('Sango','yângâ tî sängö','sg'),
('Serbian','српски језик','sr'),
('Gaelic','Gàidhlig','gd'),
('Shona','chiShona','sn'),
('Sinhala','සිංහල','si'),
('Slovak','slovenčina','sk'),
('Slovene','slovenščina','sl'),
('Somali','Soomaaliga','so'),
('Southern Sotho','Sesotho','st'),
('Sundanese','Basa Sunda','su'),
('Swahili','Kiswahili','sw'),
('Swati','SiSwati','ss'),
('Swedish','svenska','sv'),
('Tamil','தமிழ்','ta'),
('Telugu','తెలుగు','te'),
('Tajik','toğikī','tg'),
('Thai','ไทย','th'),
('Tigrinya','ትግርኛ','ti'),
('Tibetan','བོད་ཡིག','bo'),
('Turkmen','Türkmen','tk'),
('Tagalog','Wikang Tagalog','tl'),
('Tswana','Setswana','tn'),
('Tonga','faka Tonga','to'),
('Turkish','Türkçe','tr'),
('Tsonga','Xitsonga','ts'),
('Tatar','tatarça','tt'),
('Twi','Twi','tw'),
('Tahitian','Reo Mā`ohi','ty'),
('Uighur','Uyƣurqə','ug'),
('Ukrainian','Українська','uk'),
('Urdu','اردو','ur'),
('Uzbek','O''zbek','uz'),
('Venda','Tshivenḓa','ve'),
('Vietnamese','Tiếng Việt','vi'),
('Volapük','Volapük','vo'),
('Walloon','Walon','wa'),
('Welsh','Cymraeg','cy'),
('Wolof','Wollof','wo'),
('Xhosa','isiXhosa','xh'),
('Yoruba','Yorùbá','yo'),
('Zhuang','Saw cuengh','za'),
('Zulu','isiZulu','zu');

Monday, July 9, 2012

using php to unzip only certain extensions while preserving folder structure

I recently asked a question on stackoverflow.com about unzipping only some file types (like images). Or similarly make sure the zip does not contain code that can harm the computer.

As this is not available as filter I had to write it.

For anyone who should need this here is the code:

 
$ZipFileName = dirname(__FILE__)."/test.zip";
$home_folder = dirname(__FILE__)."/unziped";

mkdir($home_folder);

$zip = new ZipArchive;
if ($zip->open($ZipFileName ) === true) 
{

    //make all the folders
    for($i = 0; $i < $zip->numFiles; $i++) 
    { 
        $OnlyFileName = $zip->getNameIndex($i);
        $FullFileName = $zip->statIndex($i);    
        if ($FullFileName['name'][strlen($FullFileName['name'])-1] =="/")
        {
            @mkdir($home_folder."/".$FullFileName['name'],0700,true);
        }
    }

    //unzip into the folders
    for($i = 0; $i < $zip->numFiles; $i++) 
    { 
        $OnlyFileName = $zip->getNameIndex($i);
        $FullFileName = $zip->statIndex($i);    

        if (!($FullFileName['name'][strlen($FullFileName['name'])-1] =="/"))
        {
            if (preg_match('#\.(jpg|jpeg|gif|png)$#i', $OnlyFileName))
            {
                copy('zip://'. $ZipFileName .'#'. $OnlyFileName , $home_folder."/".$FullFileName['name'] ); 
            } 
        }
    }
    $zip->close();
} else
{
    echo "Error: Can't open zip file";
}

If you need to flatten the zip file remove the part making the folders, and change the copy function using basename to this:

copy('zip://'. $ZipFileName .'#'. $OnlyFileName , $home_folder."/".basename($FullFileName['name'])); 

Saturday, June 30, 2012

HTML 5 Data Attributes usage with JQuery

Today I decided to switch part of my code to use the data- attribute found in HTML5. This way it would make it easier to store relevant data with elements and then pull that data together with events such as hover, click, mousemove, mouseup, mousedown, etc.

Till today I've always included the data in the ID attribute and done string parsing etc. to process the object being clicked.

But implementing data- property in Jquery took some time to figure out.

Sample code:

<div ID="myDiv" data-ID="12" data-Parent="1">node</node>


<li class="main-menu" data-MenuID="10">New</node>
  <ul>
    <li class="menu-items" data-MenuID="11">New</node>
    <li class="menu-items" data-MenuID="12">Open</node>
    <li class="menu-items" data-MenuID="13">Save</node>
    <li class="menu-items" data-MenuID="14">Save As...</node>
  </ul></li>


the key to reading is that even though I used upper case and lower case mixed in my HTML, when rendered everything is converted to lower case and so to read it we have to type it lower case as in the following code, also don't forget to not write the "data-" when you call for the variable:

$("#myDiv").click( 

  function(){ 
   alert("data id is"+$(this).data('id')+" and the parent is "+$(this).data('parent') ); 
  }
);
 

$(".menu-items").click( 
  function(){ 
    alert("click on "+$(this).data('listid') ); 
  }
);


and that's it, now you can store all your data in the HTML page that your PHP or .NET rendered.

Not to forget that storing sensetive data this way is not smart at all as viewing the source will show everything!!!

Thursday, June 28, 2012

Fire mouse move event less to prevent CPU drainage and get rid of menus closing because the mouse left it for 2 pixels!

Many times when we code and listen to the mousemove the result becomes too sensetive.


If I had a menu and wanted to turn it of when the user moved away from it fine. But I wanted this menu to open 2 pixels bellow the click item then inadvertently the mouse would float for a brief moment not on the calling button nor on the menu and thus the menu would close.


Another scenario would be when the user wants to select the last item but they ooppps went to far with their mouse and then the menu closed.


I don't want the menu to remain open until they click out of it either. So here comes the code that reducedes mouse sensitivity in:


var timer = null;
var mouseX = 0;
var mouseY = 0;
var enableHandler = false;
function DrawTo(e){
    mouseX = parseInt(e.pageX);
    mouseY = parseInt(e.pageY);

    console.log(mouseX+" "+mouseY);
}
$(document).mousemove(function (e) {
        if (enableHandler) {
            DrawTo(e);
            enableHandler = false;
        }
});

timer = window.setInterval(function(){
    enableHandler = true;
}, 50);


$(document).click(function () {
       enableHandler = true;
});
this code will let the mouse get engaged every 50ms. Also when clicked the enableHandler is set to true to not miss the first click. 


This is just an example if you were making a drawing application and didn't want to miss the first drawing point. 


Obviously if you were making a drawing application it would be smarter to tie a canDraw boolean to the events mousedown and mouseup but still enableHandler once onMouseDown would help with capturing the first drawing point.