Wednesday, April 18, 2012

How to configure node-mysql?

I've found a lot of tutorials explaining how to install "node-mysql" (basically: "npm install mysql" and that's it) and others explaining how to make queries but nothing in-between.



I mean: with no GUI, how do you configure node-mysql (Mysql login, Mysql password, first table,..) before using it?



OR: How to install a GUI to access mysql for edition (which would solve problem 1)?



I tried "Mysql Workbench" via its wizard but I get a "Cannot connect to Database Server" while the host and the port are ok. I searched the "MySQL Workbench" website but there's nothing about node-mysql.



Node-Mysql seems to be the first choice when it comes to use mysql with node.js but, surprisingly, there's absolutely nothing about my issues, anywhere.



Thank you for your help.





Add expire header to improve the performance of page using .htaccess

I have a great .htaccess code which really improve my page speed.



This one below I below I don't really know much but from looking at it is like to compress or something not really sure



<FilesMatch ".(js|css|html|htm|php|xml)$">
SetOutputFilter DEFLATE
</FilesMatch>


This one is really great which set the Expire header for everything to 10 years and text/html to one day



ExpiresActive On
ExpiresDefault "access plus 10 years"
ExpiresByType text/html "access plus 1 day"


So This one is use to unset ETag which is one of the requirement rules of YSlow



Header unset ETag
FileETag None


Now come to my question that I have problem with.



I can't really use w3 Total cache with my Wordpress blog because it gives me some random issue like only show one ramdom old post to my home page and to solve that is to delete the cache and then after a day it will happen again.



So I can't rely on that plugin, but with my 3 codes that I added in my .htaccess is really good with one exception and I don't know really how to fix that.



say for example I visit my site http://applesiam.com this morning and during the day I have 3 new posts. If I don't really do hard reload page I will still see the one from morning.



So this is really make me confuse.



What should I change to not to cache the actual home page so it will be updated except images and the rest.





NetBeans Development 7 - Windows 7 64-bit … JNI native calls ... a how to guide

I provide this for you to hopefully save you some time and pain.



As part of my expereince in getting to know NB Development v7 on my Windows 64-bit workstation I found another frustrating adventure in trying to get the JNI (Java Native Interface) abilities up and working in my project. As such, I am including a brief summary of steps required (as all the documentation I found was completely incorrect for these versions of Windows and NetBeans on how to do JNI). It took a couple of days of experimentation and reviewing every webpage I could find that included these technologies as keyword searches. Yuk!! Not fun.



To begin, as NetBeans Development is "all about modules" if you are reading this you probably have a need for one, or more, of your modules to perform JNI calls. Most of what is available on this site or the Internet in general (not to mention the help file in NB7) is either completely wrong for these versions, or so sparse as to be essentially unuseful to anyone other than a JNI expert.



Here is what you are looking for ... the "cut to the chase" - "how to guide" to get a JNI call up and working on your NB7 / Windows 64-bit box.



1) From within your NetBeans Module (not the host appliation) declair your native method(s) and make sure you can compile the Java source without errors.



Example:



package org.mycompanyname.nativelogic;

public class NativeInterfaceTest
{
static
{
try
{
if (System.getProperty( "os.arch" ).toLowerCase().equals( "amd64" ) )
System.loadLibrary( <64-bit_folder_name_on_file_system>/<file_name.dll> );
else
System.loadLibrary( <32-bit_folder_name_on_file_system>/<file_name.dll> );
}
catch (SecurityException se) {}
catch (UnsatisfieldLinkError ule) {}
catch (NullPointerException npe) {}
}

public NativeInterfaceTest() {}

native String echoString(String s);
}


Take notice to the fact that we only load the Assembly once (as it's in a static block), because othersise you will throw exceptions if attempting to load it again. Also take note of our single (in this example) native method titled "echoString". This is the method that our C / C++ application is going to implement, then via the majic of JNI we'll call from our Java code.



2) If using a 64-bit version of Windows (which we are here) we need to open a 64-bit Visual Studio Command Prompt (versus the standard 32-bit version), and execute the "vcvarsall" BAT file, along with an "amd64" command line argument, to set the environment up for 64-bit tools.



Example:



<path_to_Microsoft_Visual_Studio_10.0>/VC/vcvarsall.bat amd64


Take note that you can use any version of the C / C++ compiler from Microsoft you wish. I happen to have Visual Studio 2005, 2008, and 2010 installed on my box so I chose to use "v10.0" but any that support 64-bit development will work fine. The other important aspect here is the "amd64" param.



3) In the Command Prompt change drives \ directories on your computer so that you are at the root of the fully qualified Class location on the file system that contains your native method declairation.



Example:
The fully qualified class name for my natively declair method is "org.mycompanyname.nativelogic.NativeInterfaceTest". As we successfully compiled our Java in Step 1 above, we should find it contained in our NetBeans Module something similar to the following:



"/build/classes/org/mycompanyname/nativelogic/NativeInterfaceTest.class"



We need to make sure our Command Prompt sets, as the current directly, "/build/classes" because of our next step.



4) In this step we'll create our C / C++ Header file that contains the JNI required statments. Type the following in the Command Prompt:



javah -jni org.mycompanyname.nativelogic.NativeInterfaceTest and hit enter. If you receive any kind of error that states this is an unrecognized command that simply means your Windows computer does not know the PATH to that command (it's in your /bin folder). Either run the command from there, or include the fully qualified path name when invoking this application, or set your computer's PATH environmental variable to include that path in its search.



This should produce a file called "org_mycompanyname_nativelogic_NativeInterfaceTest.h" ... a C Header file. I'd make a copy of this in case you need a backup later.



5) Edit the NativeInterfaceTest.h header file and include an implementation for the echoString() method.



Example:



JNIEXPORT jstring JNICALL Java_org_mycompanyname_nativelogic_NativeInterfaceTest_echoString
(JNIEnv *env, jobject jobj, jstring js)
{
return((*env)->NewStringUTF(env, "My JNI is up and working after lots of research"));
}


Notice how you can't simply return a normal Java String (because you're in C at the moment). You have to tell the passed in JVM variable to create a Java String for you that will be returned back. Check out the following Oracle web page for other data types and how to create them for JNI purposes.



6) Close and Save your changes to the Header file. Now that you've added an implementation to the Header change the file extention from ".h" to ".c" as it's now a C source code file that properly implements the JNI required interface.



Example:
NativeInterfaceTest.c



7) We need to compile the newly created source code file and Link it too. From within the Command Prompt type the following:



cl /I"path_to_my_jdks_include_folder" /I"path_to_my_jdks_include_win32_folder" /D:AMD64=1 /LD NativeInterfaceTest.c /FeNativeInterfaceTest.dll /link /machine:x64



Example:



cl /I"D:/Program Files/Java/jdk1.6.0_21/include" /I"D:/Program Files/java/jdk1.6.0_21/include/win32" /D:AMD64=1 /LD NativeInterfaceTest.c /FeNativeInterfaceTest.dll /link /machine:x64


Notice the quotes around the paths to the 'include" and 'include/win32' folders is required because I have spaces in my folder names ... 'Program Files'. You can include them if you have no spaces without problems, but they are mandatory if you have spaces when using a command prompt.



This will generate serveral files, but it's the DLL we're interested in. This is what the System.loadLirbary() java method is looking for.



8) Congratuations! You're at the last step. Simply take the DLL Assembly and paste it at the following location:



<path_of_NetBeansProjects_folder>/<project_name>/<module_name>/build/cluster/modules/lib/x64


Note that you'll probably have to create the "lib" and "x64" folders.



Example:
C:\Users\<user_name>\Documents\NetBeansProjects\<application_name>\<module_name>\build\cluster\modules\lib\x64\NativeInterfaceTest.dll


Java code ... notice how we don't inlude the ".dll" file extension in the loadLibrary() call?



System.loadLibrary( "/x64/NativeInterfaceTest" );


Now, in your Java code you can create a NativeInterfaceTest object and call the echoString() method and it will return the String value you typed in the NativeInterfaceTest.c source code file.



Hopefully this will save you the brain damage I endured trying to figure all this out on my own. Good luck and happy coding!





Ocaml parsing string to make tree

I have a problem similar to this:



How to print a tree structure into a string fast in Ocaml?



But in an opposite way, that I already have a string and want to parse it back to be a tree.



For example, I have



type expr = 
Number of int
|Plus of expr*expr
|Minus of expr*expr


and I have a string like 1 2 + 3 4 + - (operator notations post-fixed, a little different from the link above)

Then I want my result to be a expr type Minus(Plus(1,2), Plus(3, 4))



I found another link that might talk about this, but not sure if it's a way of doing my problem:



Parsing grammars using OCaml



Please share some ideas, thank you.





MVC3 - The model item passed into the dictionary is of type ERROR

I've got a Controller/View called LedgerUser. I have a ViewModel called LedgerViewModel which contains an instance of LedgerUser and SelectList for instances of UserType and a property called UniqueId which i use for Images.



Now when i POST the form back from my Create View I get the following error:



The model item passed into the dictionary is of type 'Accounts.Models.LedgerUser', but this dictionary requires a model item of type 'Accounts.ViewModels.LedgerUserViewModel'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.



Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'Accounts.Models.LedgerUser', but this dictionary requires a model item of type 'Accounts.ViewModels.LedgerUserViewModel'.



Now my understanding is that you pass the Model back to the Action Method and not the ViewModel? Im using the following technologies:




  1. ASP.NET MVC3

  2. Entity Framework 4 Database First



My code is:



LedgerUserViewModel:



/// <summary>
/// ViewModel to represent the LedgerUser & its required fields.
/// </summary>
public class LedgerUserViewModel
{
public SelectList UserTypes { get; set; }
public string UserType { get; set; }
public LedgerUser LedgerUser { get; set; }
public string UniqueKey { get; set; } //--Used for the Images.
public bool Thumbnail { get; set; }

}


I have extended the LedgerUser Model to decorate with Data Annotations:



[MetadataType(typeof(LedgerUserMetaData))]
public partial class LedgerUser
{
public class LedgerUserMetaData
{

[Required(ErrorMessage = "Date Of Birth Required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = " {0:dd/MM/yyyy}")]
[DataType(DataType.Date)]
public object DateOfBirth { get; set; }
}
}


My GET Action Method for LedgerUser:



    // GET: /LedgerUser/Create
/// <summary>
/// Action Method to create the LedgerUser. Usually this will be once a user has registered
/// and will be directed from the AccountController.
/// </summary>
/// <param name="id">id</param>
/// <returns></returns>
public ActionResult Create(string id)
{
var uniqueKey = new Guid(id);
var userTypes = new SelectList(db.UserTypes, "id", "Description");

var ledgerUser = new LedgerUser()
{
id = uniqueKey,
RecordStatus = " ",
CreatedDate = DateTime.Now,
DateOfBirth = DateTime.Today
};

var viewModel = new LedgerUserViewModel()
{
UserTypes = userTypes,
LedgerUser = ledgerUser
};

return View(viewModel);
}


My POST Action Method for LedgerUser:



[HttpPost]
public ActionResult Create(bool Thumbnail,LedgerUser ledgeruser, HttpPostedFileBase imageLoad2)
{
///---code to do stuff..
}


My Create View:



@model Accounts.ViewModels.LedgerUserViewModel
@using Accounts.Models
@using (Html.BeginForm("Create", "LedgerUser", new { Thumbnail = true}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Ledger User</legend>

<div class="editor-field">
@Html.HiddenFor(model => model.LedgerUser.id)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.LedgerUser.AccountNumber,"Account Number")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LedgerUser.AccountNumber)
@Html.ValidationMessageFor(model => model.LedgerUser.AccountNumber)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.LedgerUser.FirstName,"First Name")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LedgerUser.FirstName)
@Html.ValidationMessageFor(model => model.LedgerUser.FirstName)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.LedgerUser.LastName,"Last Name")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LedgerUser.LastName)
@Html.ValidationMessageFor(model => model.LedgerUser.LastName)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.LedgerUser.DateOfBirth,"D.O.B.")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LedgerUser.DateOfBirth)
@Html.ValidationMessageFor(model => model.LedgerUser.DateOfBirth)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.LedgerUser.UserType, "User Type")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.LedgerUser.UserType,Model.UserTypes)
</div>

<div class="editor-label">
@Html.Label("Avatar")
</div>
<div class="editor-field">
@Html.UploadImageFor(model => model.UniqueKey,thumbnail:true)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}


Now i have interrogated the POST using Fiddler and i have found that name is correctly being set to "LedgerUser."




Content-Disposition: form-data; name="LedgerUser.id"



d1cd8e85-700d-4462-aa95-7428dbf58deb
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.AccountNumber"



1
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.FirstName"



Gareth
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.LastName"



Bradley
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.DateOfBirth"



12 April 2012
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="LedgerUser.UserType"



b8502da9-3baa-4727-9143-49e33edc910c
-----------------------------7dc963b2304b4 Content-Disposition: form-data; name="imageLoad2"; filename="001.jpg" Content-Type:
image/jpeg




Im at a loss. Thanks guys





Lua Scripting and C#

this is quite tricky for me and i'm hoping someone can help me out.



The situation: I'm currently working an application in C# 3.5 .NET , it interfaces with a DLL written in C++ using DLL Imports, that all works fine. I also have a Lua script, this script is as follows:



Width           = XCamera():GetWidth()
Height = XCamera():GetHeight()
Img = XSensorImage()


then for example, there is a function that calculates the temperature from Img by:



function OnFrame()
local CoordsTable = { i, j }
local PixelTable = Img:GetPixels( CoordsTable )
PixelValue = FromLinearizedADU( PixelTable[1] or 0 )
end


what I want to be able to do, is return PixelValue to my application.



XCamera() & XSensorImage() are instances created when the camera filters are initialized and the Lua script is active.



Is there anyway of accessing Pixel Value from this script when it is running?
I'm sorry if I'm not being detailed enough, please ask if you require more, your feedback is much appreciated.





C#/XNA/HLSL: Need a formula for depth of field

After completing my Depth Of Field Shader, I noticed how horrible it actually looks due to the formulas I took from a tutorial. When the far plane is focused, the near plane is actually in focus too (which I don't want). It also makes a noticeable transition from in focus to out of focus at a particular point (haven't measured yet, but probably around 300-420 units away). It's also unmaintainable.



So, to counter this, I thought of my own formula that would solve this problem. Unfortunately, because of my horrible skills at making formulas from graphs, I don't actually know how to construct it.



So, for a function:
f(fl, fr, t, m, f);
Where:




  • FL is the Focal Length where pixels at this depth are in focus,

  • FR is the Focal Range, where pixels within this range FROM the Focal Length is in focus,

  • T is the pixel's depth, which is compared with the function's graph to return a result

  • M is the multiplicative factor, where anything greater than or less than the focal range is blurred. This is important, as it will be modified to make either a gradual blur transition or a hard transition.

  • F is the far plane distance; FL and FR will be divided by this



I need it to return a value from 0-1 to I can put this result into the lerp function.



The graph (with color-coded labels and points 'n' stuff [geomau5?]) is:
enter image description here



Clearing some things up, for the multiplicative factor, the absolute value of the slope of the line should equal the factor. The graph should be an approximate representation of f(500, 250, 175, 3, 1000). The value returned should be around 0.2 or so.



And if you read the focal range wrong, any pixels with a depth of the focal length ± the focal range will always return zero. So the graph should depict the focal range as split in half.



This also might be used to calculate fog percentages correctly.



EDIT: Solving, no need to do this. Clearing question once I succeed - I need it for references for exactly what I want.