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.





JavaScript Create function

How can i define following object properties of html and define as a function in javascript that would return some object.



HTML:



<object id="desktop" type="application/x-desktop" width="500" height="200">
<param name="client_type" value="VISTA" /> </object>


I want to acheive something like below in javascript.So that I can call GetDesktop() function from outside of javascript.



JavaScript:



 function GetDesktop()
{
object.id = "desktop;
object.type = "application/x-desktop"
....
...
...
}




jquery: how to loop a div

using jquery, how can i auto scroll a div continuously? like the news and features section of this website: http://animalsasia.org/. And also when you hover over the slider it stops the scrolling until you hover away.



is there a jquery plugin that will do that? Any help would be much appreciated.





MySQL Complex query not returning right results

I have the following query:



'SELECT * FROM posts LEFT JOIN taxi ON taxi.taxiID = posts.postID
WHERE (taxi.value = 1 AND taxi.userID ='.$userID.')
AND ??????????????
ORDER BY taxi.ID DESC
LIMIT 10'


The way the site works is the user can tag posts as being "liked". When a post is liked, the taxi table is given a new row with taxiID being the same as postID, userID to store the user that liked the post, and value which is set to 1. Disliking a post sets value to 0.



I want to display all posts where value is 1 and userID is $userID - check. However, I also want the query to display all the posts where the user hasn't liked a post yet. Thing is, if the user hasn't liked a post yet, userID is NULL with a corresponding value of NULL. If I query for that, I'll be skipping those posts that other users have liked but the user hasn't.



Here's the taxi table:



ID    taxiID    userID    value
1 1 1 1
2 1 6 1
3 1 4 0
4 2 1 0
5 2 6 1
6 2 4 0
7 3 6 1
8 3 4 0


Assuming $userID is 1, my query ought to display taxiID 1 and 3 (because user 1 liked ID 1 AND hasn't liked or disliked taxiID 3.



The code I've posted will only result in displaying taxiID 1.



The question is, what is my missing line in my query supposed to be given the above?





How to query price with different date

I am currently making a hotel reservation system and wondering how can I query price column in my tbl_prices table.



Here's how my table looks like:



id          date_from          date_to         price          is_default
1 00-00-0000 00-00-0000 $95 1
2 05-25-2012 05-29-2012 $100 0
3 06-20-2012 06-24-2012 $90 0


The first row is a default price. So if somebody reserve a date that is not in row 2 and 3 the price is $95. But if the reservation date fall on 2nd and 3rd row then the price should be $100 or $90.



Example if guest want to check in from 5-24-2012 to 5-26-2012 then the price should be



1st day = $95
2nd day = $100



5-26-2012 will not be charge because it is a checkout date.





How to toggle required fields using jQuery Validation plugin?

My application has a dynamic form that uses jQuery to toggle the display of follow up questions, and make certain questions required using the jQuery Validation plugin. My problem is that when the form loads, with previously answered questions, the correct classes are not displaying.



The "follow up" questions display a textarea if 'yes' is answered. If 'yes' is selected, and the textarea is displayed, the textarea should be a required field (class="required"). If 'no' is selected, and the textarea is hidden, the textarea should not be required.



If you look at a working example, http://jsfiddle.net/GKATm/, and review the source code or use Firebug, the hidden textarea is set as required:



<span class="details" style="display: none;">
<textarea id="followup_1_details" maxlength="1000" class="required"></textarea>
</span>


Any ideas on what I am doing wrong. Everything works when the form loads blank. But my application allows users to return to their saved answers, and when they do this the Validation plugin is flagging this as invalid, because a required field has not been answered.



Please help!



HTML:



<div>    
<label>Question #1</label>
<span class="options">
No <input type="radio" class="toggle_group required" value="0" id="restrictions_no" name="restrictions">
Yes <input type="radio" class="toggle_group required" value="1" id="restrictions_yes" name="restrictions" checked="checked">
</span>
</div>

<div class="details_group">
<div>
<label>Follow Up #1</label>
<span>
No <input type="radio" class="toggle" value="0" id="followup_1_no" name="followup_1" checked="checked">
Yes <input type="radio" class="toggle" value="1" id="followup_1_yes" name="followup_1">
</span>
<span class="details">
<textarea maxlength="1000" id="followup_1_details"></textarea>
</span>
</div>

<div>
<label>Follow Up #2</label>
<span>
No <input type="radio" class="toggle" value="0" id="followup_2_no" name="followup_2">
Yes <input type="radio" class="toggle" value="1" id="followup_2_yes" name="followup_2" checked="checked">
</span>
<span class="details">
<textarea maxlength="1000" id="followup_2_details"></textarea>
</span>
</div>
</div>


Javascript:



$('.toggle').on('change', function() {

var showOrHide = false;

$(this).siblings('input[type=radio]').andSelf().each(function() {
if ($(this).val() == 1 && $(this).prop("checked")) showOrHide = true;
})

$(this).parent().next('.details').toggle(showOrHide);
$(this).parent().next('.details').find('textarea').addClass('required');

if (showOrHide == false) {
$(this).parent().next('.details').find('textarea').val('');
$(this).parent().next('.details').find('textarea').removeClass('required');
}

}).change()


$('.toggle_group').on('change', function() {

var showOrHide = false;

$(this).siblings('input[type=radio]').andSelf().each(function() {
if ($(this).val() == 1 && $(this).prop("checked")) showOrHide = true;
})

$(this).parent().parent().next('.details_group').toggle(showOrHide)
$(this).parent().parent().next('.details_group').find('input:radio').addClass('required');
$(this).parent().parent().next('.details_group').find('textarea').addClass('required');

if (showOrHide == false) {
$(this).parent().parent().next('.details_group').find('input:radio').removeAttr('checked')
$(this).parent().parent().next('.details_group').find('input:radio').removeClass('required');
$(this).parent().parent().next('.details_group').find('textarea').val('');
$(this).parent().parent().next('.details_group').find('textarea').removeClass('required');

}

}).change()




Is it possible to make IEnumerable<char> implement IComparable?

As titled.



We all know if we want a class to be comparable and use in sorting i.e DataGrid, we will implement IComparable.



But for IEnumerable how can I do that?



I have a collection of a IEnumerable, we want to compare each IEnumerable to each other and do a sorting.



So say a collection List<IEnumerable<char>> that contains:



IEnumerable<char> EnumableA contains: "d", "e", "f"



IEnumerable<char> EnumableB contains: "d", "e", "c"



If we bind the collection List<IEnumerable<char>> to a DataGrid,
when we sort them in acs order, the order will be EnumableB 1st, then EnumableA the 2nd.



I do think of solution such as store the EnumableA into an object whichs implment IComparable, but then this would require to create another collection of objects, which will be expensive.



So is it possible or anyway to APPEND a IComparable interface and my sorting implmentation to the IEnuerable<char> so it will be sortable?





Want to have my textarea format it's readonly text like html

I have a read-only textarea that I display which acts as my old blog posts (which are editable in a field below it) and I'd like to be able to format it's contents somewhat. Ideally, I'd like it to look like HTML code, but at the very least, I'd like when the entered a URL, I'd like to display it as a href link.



Are there any best practices for this? Or do I have to process each and look for and format the items I want?



Thanks in advance.





undefined local variable or method `blog'?

I am working on a rails application and I have a Dashboard::user(dashboard/user) controller and I would like for users to update their blog post through the backend of the site. That works fine but when I am trying to get a list of the latest blog post a user has created I get an error.



dashboard/users_controller



def content
@blog = Blog.new
render ('content')
end


dashboard/blogs/_blog_list.html.erb



<%= div_for(:dashboard ,blog) do %>
<%= link_to image_tag(blog.preview.url(:thumb)), dashboard_blog_path(blog) %>
<h1><%= link_to (blog.title),dashboard_blog_path(blog) %></h1>
<p><%= truncate blog.excerpt, length: 160 %></p>
<%= blog.published_at %>
<%= blog.site_id %>
<% end %>


Any reason why this is not working?





Mamp 1045 Error

I am getting a 1045 error :



/Applications/MAMP/Library/bin/mysqlcheck: Got error: 1045: Access denied for user 'root'@'localhost' (using password: YES) when trying to connect



When MAMP starts, but I am able to access the database fine, and the home screen show up fine. I just can't view any of the documents within the folder. If I type in localhost/ I get 'Could not connect to remote server.' Both the Apache and MySql servers say that they are on.



Not sure what is wrong.





How to print data from Android Tablet to a Bluetooth printer

I am developing an application for Android Tablet,now in my application if i select print option then data should be print in the Bluetooth printer.to achieve this first i want to know how to recognize nearest Bluetooth devices and also how to print data in a Bluetooth printer.





Make 3D perlin noise function from 2D function

So, I am trying to plot abstract shapes that change with time using openGL. For that, I want to use the Perlin noise funtion. This code (http://www.sorgonet.com/linux/noise_textures/) is a just perfect start for me, except for the fact that the function found here takes only two coordinates. I want one that takes two spacial coordinates, and a third one, that will change with time.



My question is: is it possible to adaptate this function to work with one more coordinate?





Iteration, find

Please help! How would i find and remove leading underscores by iterating through looking at the characters and counting the number of underscores before a valid character occurs. As well as iterating backwards from the end of the string to find any trailing underscores.



I can use the following method, to erase the underscore, but how would is iterate to find underscores.



resultF.erase(resultF.length()- trailingCount);
resultF.erase(0,leadingCount);


If user enters a string of ___twenty_three__, the end result should be twenty_three. So only the leading and trailing underscore are deleted.





Does proguard work to obfuscate static string constants?

Will proguard work to obfuscate static string constants?





for loop in jquery?

I have a photo gallery, images are named from 0 to 170 and I am inserting them like so:



> <div id="galleria">
> <a href="images/0.jpg">
> <img src="images/0.jpg">
> </a>
> <a href="images/1.JPG">
> <img src="images/1.JPG">
> </a>
> <a href="images/2.JPG">
> <img src="images/2.JPG">
> </a>
> <a href="images/3.JPG">
> <img src="images/3.JPG">
> </a>


can i use a for loop to go from 0-170 instead of doing 1 at a time





How would you implement a navigation like this?

How would you implement a navigation like this?



http://i.stack.imgur.com/cyuJz.png



I'm a bit stuck and wondered if anybody could point me toward a good way to accomplish this.



Here's a transparent PNG of one of the hover states.



http://i.stack.imgur.com/cROAg.png





asp.net mvc 3 - sending an email and getting the return for validation a task (registration, form validation...)

I am having a register form that user fill in, once the form fill in, the registration is postponed till the user recieve an email to check that his email is ok, then when he reply the email, the registration is fully proceed.



I would like also the process to be automatic, without the need for the user to entered any number ect, just the need for him to click on the email to confirm, and automatic on my side too.



I want the process to be available to some others task than the registration process as well if possible.



Do I need to do all way check/123456 with the 123456 generated or is there a better way to do, a component, nuget that can do the job ? you experiences return would be helpful



thanks





Does flash.now work in Ruby on Rails 3+?

Currently I am on Rails 3.0.3 and I am trying to render a 'new' action in my user controller but when I get an error I get the initial flash on the new user page, but also get a repeat of the flash message when I go to another page.

From the research I've done, you use flash.now[:notice] for renders but it isn't working. Its not clearing the flash after showing it.



Here is my code:
users_controller.rb



def create
flash.now[:notice] = "flash test."
render :new
end




Conditionally adding Context Menu Item in Outlook 2010

In my outlook 2010 AddIn, I want to add context menu Item when user right click on Appointment Item. However I don't want to add context menu item blindly, instead context menu Item will differ if user belong to different user group. How can I achieve this functionality with XML configuration file. I can add context menu item with native code but don't know how it can be done using config file.





Firing context menu from user control does not work

I try to use a context menu from a user control's list view but the command is not firing (neither enabling/disabling when needed).



Code:



<UserControl ....
<UserControl.Resources>
<ContextMenu x:Key="SharedInstanceContextMenu">
<MenuItem Header="Edit" Command="{Binding ElementName=UC, Path=DataContext.EditSelectedItemCommand}" CommandParameter="{Binding}"/>
</ContextMenu>

<Grid ...>
<ListView ....>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected}"/>
<Setter Property="ContextMenu" Value="{StaticResource SharedInstanceContextMenu}"/>
</Style>
</ListView.ItemContainerStyle>


How can I make the command firing (and enabling/disabling, part of the command behavior)?



(btw, this questions seems similar to Treeview context menu command not firing but after trying all solutions there it still does not work.)





Create and Rotate a Rectangle using Draw method iPhone?

i am working on a cocos2d project in which i draw a rectangle with the help of draw method as following



-(void)draw
{
glEnable(GL_LINE_SMOOTH);
glColor4ub(255, 255, 255, 255);
glLineWidth(2);

CGPoint verticesAll[] = { vertices1, vertices2,vertices3, vertices4 };

ccDrawPoly(verticesAll, 4, YES);

}


now i need to rotate the rectangle when user moves his finger on screen. how can i change all the four cordinates so as to rotate the rectangle according to touches moved .



if i calculate the angle from the center of the screen to one of the axis of rectangle and then accordingly change that particular coordinate but the change in other coordinates won't be the same so how can i achieve that?



vertices1,2,3.. are cgpoints



also on a ccmenu click i need to draw more rectangle .. i am not sure how to call draw method to create more rectangles with different vertices??





What are the functions of the Transport layer?

I have a homework question which asks what the four functions of the Transport layer are. It doesn't mean what the functions of TCP or UDP are, but the layer itself.





Windows Azure caching cshtml files?

I'm evaluating Windows Azure for an MVC application I'm working on. I ported the app a little while ago and uploading without any issues. I've come back about 4 weeks later to upload the next version and now I'm getting an exception being thrown.



Source: System.Web.WebPages
Message: Section not defined: "main".
Stack trace: at System.Web.WebPages.WebPageBase.RenderSection(String name, Boolean required) at ASP._Page_Views_Shared__Layout_cshtml.Execute() in e:\sitesroot\Views\Shared_Layout.cshtml:line 77 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) at System.Web.WebPages.WebPageBase.PopContext() at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c_DisplayClass25.b_22(IAsyncResult asyncResult) at System.Web.Mvc.Controller.<>c_DisplayClass1d.b_18(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.<>c_DisplayClass4.b_3(IAsyncResult ar) at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.<>c_DisplayClass4.b_3(IAsyncResult ar) at System.Web.Mvc.MvcHandler.<>c_DisplayClass6.<>c_DisplayClassb.b_4(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.<>c_DisplayClass4.b__3(IAsyncResult ar) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)



The only reason that I can think that this would happening is that either the _layout.cshtml file is not updating or the Home/Index.cshtml file is not updating. The MVC application works correctly both running in the Windows Azure emulator or running stand alone in IIS.



I have completely deleted the role and redeployed as well as upgraded. I have not configured CDN or the Azure Cache and I can confirm files that have been added to the project since the last successful deployment are available.



Right now I'm out of ideas...





How to open the options menu programmatically?

I would like to open the optionsMenu programmatically without a click on the menu key from the user. How would I do that?