Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, September 22, 2015

愛老虎油

What is this?

This is a simple pseudo 3D rendering of a heart. The little buzzing pink dots will zip between points and choose a new direction at each point. Sweep your mouse across the heart to swivel the heart.

The Chinese phrase 『愛老虎油』 literally translates as "Love tiger oil",.. but then it's not supposed to be literally translated. This is a play on words, or sounds of the words to be more exact. The pinyin transliteration for the Chinese looks like "Ài lǎohǔ yóu". Sometimes when a Taiwanese speaker says these words in Chinese, using a very thick Taiwanese accent, it sounds remarkably similar to "I love you"! Google Translate does a very mediocre job of pronouncing it - Click through and click the speaker button on the grey translation box.

See the Pen I Love You by Pat Cullen (@patcullen) on CodePen.

Monday, July 27, 2015

Then & Now

Recently I stumbled across an excellent photo/postcard collection of Taiwan from yonder year. I am a big fan of Tainan, a city in the southern half of the island; So have decided to go to some of these locations to take current photos to compare against the historical counterparts. The first thing I wanted to do was download an mobile app that would facilitate this desire, only to find that there was either no free app to do so, or no such thing at all. Well here I present a prototype for such an app.

Example and/or Goal

Here is a photo I took in Tainan, and it's historical counterpart I found on the internet. I tried to get a close match, but unfortunately at the time the road was quite busy and wandering around in between speeding cars to find a perfect angle was not as a high priority as I initially imagined.

Demo on CodePen

(The app will ask to use your webcam if it is present. A similar question will be asked if using your mobile.)

See the Pen Then & Now by Pat Cullen (@patcullen) on CodePen.

If you're interested..

A full-page (unlike the pen above) linkable version can be found at http://cullen.co.za/project/thenAndNow. On my mobile I have created a shortcut to open this in my browser, which is the closest I am probably going to bundle this into any mobile-app form.

Friday, November 7, 2014

Copy to FTP in Classic ASP (JScript)

Recently I had the need to FTP some files in the old Classic ASP platform. The catch is that I need it to be in JScript (Javascript for IIS). In my experience most people use VB script in their ASP environment,. the past few years I have grown to prefer using JScript. If you'd like to use VBScript to FTP then might I suggest this great source. It is from this that I have adapted my JS version.

FTP in ASP (JScript)

In my current environment I never use serverside JScript to render HTML, rather only to serve in a JSON based API format. For the purposes of sharing, I trimmed down the scaffolding into the bare necessities and was left only needing a JSON polyfill: JSON polyfill that works in ASP JScript.

var ftp = (function() { /* * Copy a file(s) to a directory on a remote FTP server. * * Adapted from the very usefull post @ http://benmeg.com/code/asp/ftp.asp.html */ function copyTo(address, username, password, remote_directory, files_to_put, isBinary) { var objFSO = Server.CreateObject("Scripting.FileSystemObject"), oScript = Server.CreateObject("WSCRIPT.SHELL"), oFileSys = Server.CreateObject("Scripting.FileSystemObject"), objTextFile, oScriptNet, oFile, strCMD, strTempFile, strCommandResult = '', uniqueNumber = '__'; // This is for you to implement a random key on your system (if required). // Build our ftp-commands file objTextFile = objFSO.CreateTextFile(Server.MapPath('ftpCommand' + uniqueNumber + '.ftp')); objTextFile.WriteLine('lcd ' + Server.MapPath('.')); objTextFile.WriteLine('open ' + address); objTextFile.WriteLine(username); objTextFile.WriteLine(password); // Check to see if we need to issue a 'cd' command if (remote_directory != '') objTextFile.WriteLine('cd ' + remote_directory); objTextFile.WriteLine('prompt'); // If the file(s) is/are binary (i.e. .jpg, .mdb, etc..) if (isBinary) objTextFile.WriteLine('binary'); // If there are multiple files to put, we need to use the command 'mput', instead of 'put' if (files_to_put.indexOf('*') > -1) objTextFile.WriteLine('mput ' + files_to_put); else objTextFile.WriteLine('put ' + files_to_put); objTextFile.WriteLine('bye'); objTextFile.Close(); delete objTextFile; // Pipe output from cmd.exe to a temporary file strTempFile = Server.MapPath('ftpOutput-' + uniqueNumber + '.ftp'); // Use cmd.exe to run ftp.exe, parsing our newly created command file oScript.Run('cmd.exe /c ' + 'ftp.exe -s:' + Server.MapPath('ftpCommand' + uniqueNumber + '.ftp') + ' > ' + strTempFile, 0, true); oFile = oFileSys.OpenTextFile(strTempFile, 1, false, 0); // Grab output from temporary file strCommandResult = oFile.ReadAll(); oFile.Close(); // Delete the temporary & ftp-command files oFileSys.DeleteFile(strTempFile, true); objFSO.DeleteFile(Server.MapPath('ftpCommand' + uniqueNumber + '.ftp'), true); delete oFileSys; delete objFSO; return { result: strCommandResult.split('\r\n') }; } return { copyTo: copyTo }; })();

Which results in:

Friday, July 18, 2014

Chinese Javascript Tools - 中文Javascript的工具

A set of tools and functions for working with Chinese characters in the browser or NodeJS.

Features

  • Generating Pinyin or Zhuyin (Bopomofo) for strings of Chinese text - 翻譯中文到拼音或注音
  • Converting between Traditional and Simplified Chinese - 兌換傳統到簡體漢字而且反之亦然
  • Detecting Chinese characters in strings - 檢測中文字
  • UI elements/facilities for reading Chinese text in the browser - 用拼音和注音便利使用者讀中文字
  • Translating Chinese characters and common phrases to English - 翻譯成語和常見的字

Download

All source and examples can be downloaded from GitHub.

Examples

Tuesday, May 27, 2014

Reading Excel Files in Classic ASP

Recently I had the need to source data from Excel files in the old Classic ASP platform. There are some good resources online which can help you with this, but I thought I'd log my little experience here which may hopefully expedite the process for someone else someday :)

In my experience most people use VB script in their ASP environment,. the past few years I have grown to prefer using JScript. I'll provide my testing in both.

A Little Environment Preface

In my examples I will have a file called unlocodes.xlsx placed in the directory c:\temp\
The content of the Excel file looks like this:

ASP (VB)

Here is a barebones ASP sample connecting to the Excel file.

This resulted in:

ASP (JScript)

Here is a JScript sample connecting to the Excel file. In my current environment I never use serverside JScript to render HTML, rather only to serve in a JSON based API format. I trimmed down the scaffolding into the bare necessities: an Excel interface and a JSON polyfill that works in ASP JScript.

This resulted in:

Some Extra Notes

I crossed paths with two errors, both of which were resolved by simply choosing the correct connection string.
This error:
ADODB.Connection error '800a0e7a'

Provider cannot be found. It may not be properly installed.

and this error:
Microsoft JET Database Engine error '80004005'

External table is not in the expected format.

The ConnectionStrings.com website is a great resource for finding a connection string compatible with your installed version of Excel. I found that on my machine with Excel 2010 this connection string worked:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\somefile.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";

Whereas on our production server we have 2013 installed:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\somefile.xlsx;Extended Properties="Excel 8.0;HDR=YES;IMEX=1";

If you continue to have problems finding the correct driver, or it complaining it's not installed, then be sure to download and install the Microsoft Access Database Engine 2010 Redistributable. This includes the latest ACE drivers which come in 32 and 64 bit flavors. For posterity you may want to try install the 64bit version in command line using the follwoing syntax:
AccessDatabaseEngine_X64.exe /passive

Wednesday, May 7, 2014

Injecting CSS with Javascript

Why injectCSS? Why make it? What is it solving?

  • The primary goal was to create an easy way to include multi-line (lots) of CSS using Javascript.
  • Can reduce number of files in a JS plugin or project (My goal was one).
  • A test run at jsperf.com shows that injecting CSS rules for a vast number of elements is very fast.
There are already some existing CSS injection tools, but I wanted something dead-simple. There is a great library called VeinJS, which does so much more than mine in many different ways. But after perusing through the examples I knew that I would have to dismantle my CSS too much. What I wanted was something like what you will see in the example below.

Example Usage

With RequireJS

With no dependencies

Compatability

Tested successfully on:

  • Chrome (+mobile)
  • Firefox
  • Safari (+mobile)
  • IE 10+
Due to the older IE browsers not allowing the innerHTML property to be set on certain elements, this will not work in them.

Download

The code is on GitHub. Download, use and modify as you please.

Thursday, January 16, 2014

Javascript載入動畫的plugin

在從前當我想要在網頁中載入自己的javascript於標頭時,通常會將其包含於page load script中。然而隨著時代的轉移,我們有著AMD/CMD (異步載入)的組件了,例如:RequireJSSeaJS,CurlJS等等。因此現在我可以寫許多的JS組件並且僅在我需要它的時候將其異步載入。

在從前要在網頁內載入我們的JS時,通常我們需要某些UI控制器來指定何種資源是需要被載入的。當使用RequireJS後,此loading 時間是可以被分割到許多短暫的時間中的。 不過有時在載入JS resource 時仍然會花不少時間,也許是某些resource很大或複雜性比較高。然而理由到底為何,其實並不是很重要。最重要的是要讓用戶知道目前發生了什麼事, 故UI必須要可即時回應。

若用戶按某一個一個需要遠端載入resource的按鍵時,而RequireJS若只在resource完全載入後才回應使用者的話,當時間一久,使用者很可能會非常困惑且感到沮喪。因此,當然使用任何XHR 或遠端要求時,我也會希望如何UI 一樣的即時回應,來告知使用者目前發生了什麼事。

載入JS,當需要使用者等待時,你需要一個考慮周全的設備(device)用來顯示回應訊息於你的UI上。你可以從GitHub下載所有的程式碼,或是從下面另外一個分流的版本。

下載

使用範例

JQuery & SeaJS

Example Usage

JQuery & RequireJS

Mootools with no module loader

謝謝Hector Yeh幫我翻譯。
英文版

Tuesday, December 31, 2013

Javascript Loading Animation

Once upon a time I used to load all of my javascript in the head tag using script includes as the page loaded. Times are a changin', and now we have AMD devices such as RequireJS; Now I can write my JS in modules and load them as and when I need.

When loading all my JS on page load, I normally had some kind of UI control to indicate resources were being loaded. After having converted to RequireJS, this loading time has been divided into smaller more intermittent load times. The problem I've experienced is that sometimes a JS resource gets loaded really slowly, or perhaps it's just big or complicated. For whatever reason, it's not important.. The most important thing is to keep the user updated with whats happening, to have a responsive and active UI.

If a user clicks a button, which indirectly requires remote/new resources, then the response to that button click will only come to pass after RequireJS can download all the required resources. If this response time is too long, then this can confuse the user and/or lead to frustration. Actually,.. whenever I do any XHR or remote requests I want to have the same consistent active UI feedback telling the user what (or something) is happening.

Enter loading.js - A completely over-thought device to display feedback on your UI when it requires the user to wait. You can download all the code from GitHub or you can find a streamlined version of what you're looking for below.

I have tested in the current versions of Chrome (desktop & mobile), Firefox, IE, Safari (desktop & mobile). I don't have much intent in creating fixes for historical versions just yet,.. however I will happily accept pull requests.

Download

Example Usage

JQuery & RequireJS

JQuery & SeaJS

Mootools with no module loader

Tuesday, May 28, 2013

JSON Validator

For a while I have been developing a NodeJS web app ~ The entire app is service/ajax/socket driven and requires a lot of message passing. I quickly discovered I needed a convenient yet secure way to validate all messages arriving at the server. Enter JSONValidate.js
This one function can be used on both ends of my app to proactively (on the client) and reactively (on the server) bounce faulty data. I have been checking in on the JSON schema standard over the past three years, but I still wanted my schema to have a few more bells and whistles than what the standard was providing ~ So stick it for now, this works fine.

Download

If you're anything like me and don't want to read all my mumbo-jumbo, then you can just go ahead and view and download the code.

Schema Breakdown ~ Let's Build One

A schema is simply a JSON object with a set of properties appropriately named as desired object field names. Let's make a human schema.
var human = {
  name: { },
  birthday: { },
  weight: { },
  gender: { },
  deceased: { }
};
Now we can define type for each property.
var human = {
  name: { type: 'string' },
  birthday: { type: 'string' },
  weight: { type: 'number' },
  gender: { type: 'string' },
  deceased: { type: 'boolean' }
};
At this stage the schema would validate an object with four, non-null appropriately named properties. Let's throw in some extra boundaries and rules...
var human = {
  name: { type: 'string', min: 3, max: 120 },
  birthday: { type: 'string', regex: /^(19|20)\d\d([- \/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/ },
  weight: { type: 'number', null: true },
  gender: { type: 'string', min: 1, max: 1 },
  deceased: { type: 'boolean' }
};
  • All properties are assumed to be required (not null) unless so specified (like the weight property).
  • The regex property is used on string fields. The regex for birthday is simply a date regular expression in format yyyy-mm-dd.
  • min and max can be used on string and number types.
Next: we can define label and custom.
  • If a label property is defined and the object being validated fails, the validator will use the label property to describe the error.
  • The custom property allows for a custom function to be defined in the schema. The function will be given two parameters; the property value, and the object being validated, in that order. The custom function should return an array of strings in the event of data not passing validation; and simply return nothing if validation was successful.
var human = {
  name: { type: 'string', min: 3, max: 120, label: 'Full name' },
  birthday: { type: 'string', regex: /^(19|20)\d\d([- \/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/ },
  weight: { type: 'number', null: true },
  gender: { type: 'string', min: 1, max: 1
    custom: function(v) {
      if (['F', 'M'].indexOf(v.toUpperCase()) == -1) 
        return ['Gender must be set to F or M.'];
    } 
  },
  deceased: { type: 'boolean' }
};
The last two features worth mention: arrays and sub schemas are both supported as well. Let's add some pets to our human.
var animal = {
  name: { type: 'string', min: 3, max: 120 }
};

var human = {
  name: { type: 'string', min: 3, max: 120, label: 'Full name' },
  birthday: { type: 'string', regex: /^(19|20)\d\d([- \/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/ },
  weight: { type: 'number', null: true },
  gender: { type: 'string', min: 1, max: 1,
    custom: function(v) {
      if (['F', 'M'].indexOf(v.toUpperCase()) == -1) 
        return ['Gender must be set to F or M.'];
    } 
  },
  deceased: { type: 'boolean' },
  pets: { type: 'object', schema: animal, array: true, null: true }
};
* Recursive behavior is not yet supported. (sad face) The last code snippet above should validate positively on an object that looks like this:
{
  name: 'Victor Challis',
  birthday: '1982-12-14',
  weight: null,
  gender: 'M',
  deceased: false,
  pets: [
    { name: 'Alex' }, 
    { name: 'Pat' }
  ]
};
In case you didn't see it at the top, you can experiment with the validator on JSFiddle.net.

Monday, December 20, 2010

Facebook Chat Translation

I present to the world my latest invention, FBChatAT. A Facebook Chat Inline Auto Translation tool for Google Chrome. (If you don't use Chrome then click here, install, and be set free.)

Download FBChatAT Here

This extension acts/translates in two ways:

When you receive a message in Facebook Chat, the extension will automatically translate that message into your native language, then insert the translated text underneath the original message. This allows you to review/read the original messages and translation simultaneously while you chat.

Secondly.. To type in your native language and have it automatically translated out: An extra textbox is provided at the bottom left of the screen. Type into this box your text will be translated and shown in the space provided above. If/when you are happy with your outgoing message, press 'enter'. This will push the translated text into the current active chat flyout/window. Press 'enter' a second time to push the message into the chat stream.

The default native and foreign languages are English and Traditional Chinese respectively. You can set your preferred languages in the options page of the extension. (Right click FB button in toolbar and choose options).

You may find the full source for this extension on GitHub.

This extension uses Google Translate for the translation.

Sunday, October 31, 2010

ScannerKeystrokeObserver

A class to automatically detect entries from a hardware device that generates keystrokes (like a barcode scanner).

Demo

This class is designed on the assumption that your barcode scanner hardware will act like a keyboard. As a barcode is scanned a series of keypress events will be generated by the device. If these key events are in fast enough succession (the order of milliseconds), then it can be assumed that a scanner device pushed the series of key events. Otherwise it is just normal human input and will be ignored by the barcode reader class.

How to use

Include the following code in the head of your web page.

 <script src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js" language="JavaScript" type="text/javascript" ></script>
<script src="ScannerKeystrokeObserver.js" ></script>
<script>
new ScannerKeystrokeObserver({
onRead: function(v) {
$('txtGlobal').set('value', v).highlight();
}
});
</script>

Get It

Friday, October 29, 2010

ImageCarousel Mootools Plugin

An image carousel thats really easy to implement.

Demo

ImageCarousel was designed for those that might get a little intimidated with the Javascript side of web sites.

How to Use

  1. Copy your carousel images into their own folder inside your project.
  2. Copy ImageCarousel.php into the folder from step one.
  3. Download and unzip the ImageCarousel files into your project folder. They should unzip into a folder called 'ImageCarousel'.
  4. Copy the following code into the head tag of your website.
    <script src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js" language="JavaScript" type="text/javascript" ></script>
    <link href="ImageCarousel/ImageCarousel.css" rel="stylesheet" type="text/css">
    <script src="ImageCarousel/ImageCarousel.js" language="JavaScript" type="text/javascript"></script>
  5. Copy the following code into your webpage. This will act as the carousel element.
    <div class="ImageCarousel auto" rel="Images/Carousel/" styles="width: 500px; height: 375px;"></div>
    You need to change/check:
    • The 'rel' attribute should point to the folder where you have stored your images. The url should end with '/'.
    • Your images should all have the same dimensions; Check the Carousel 'width' and 'height' match your image dimensions.

Get It