Monday, May 14, 2012

In Yii,why and how to use Yii::app()->end() method?

In form validating,I find such codes

if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
echo CActiveForm::validate($model);

The manual says that the end() method will terminate the application.
Why to terminate the app? The following codes will not execute?

link_to blank space

I have changed the regular labels for view, edit and delete for background images for the corresponding <td> labels. But now the link don't work because I don't have text to click.

How can I make blank spaces clickable, or is there another approach to this problem?

This is what I got:

<td class="view"><%= link_to '', event %></td>
<td class="edit"><%= link_to ' ', edit_event_path(event) %></td>
<td class="delete"><%= link_to ' ', event, :confirm => 'Are you sure?', :method => :delete %></td>

I know a solution is to add the image as image_tag and create a link, but having the images declared in the style.css is much more cleaner and simple to implement.

thanks in advance

Jquery get id or class from dynamic element

Let say I have 5 element from PHP query (so it is dynamic)
Illustrated below:

element 1 class=element id=id_1

element 2 class=element id=id_2

element 3 class=element id=id_3

element 4 class=element id=id_4

element 5 class=element id=id_5

we ussulay use jquery event by knowing their class or id, but in this case, we don't know exactly their id

$("#id_3").click(function(){ //in this case we have known we want to add event when we click id_3


but how to deal with dynamic element from PHP query?

for example, how can we know that we click on element 3 with id_3?

What mus we fill in $(????).click(); ??

when I use class, how can I know which id I reference from the class clicked?

Download Attribute Overriding onClick <a>

I am using the download attribute to trigger a forced download of a song, but it seems to be overriding the onClick event. I can only do one or the other.

<input onclick="window.close()" type="button" value="Cancel"/>

var a = document.createElement("a"); = song + ".mp3"
a.href = url
a.onclick = function(e) {
var notification = webkitNotifications.createHTMLNotification(
document.getElementsByTagName("a")[0].innerHTML = "Download"

How do I both trigger the download, and fire the onClick event?

How to make a java gui in Jess as an applet?

I have an interface written in Jess (one of the java libraries) that has a panel and a combo box

I wanna make it run as applet. so I can embed it on the web!

Here is my,

package uges.applets;

import java.applet.Applet;
import jess.*;
public class JessApplet extends Applet
public void init()
Rete engine = new Rete();

} catch (JessException e)
// TODO Auto-generated catch block

The error was cannot open file ug-pro.clp .. should I put it in a specific folder? and Can I make my GUI in jess as an applet ?

Moq, TDD and multiple layers

I have a data assembly which defines my repositories.

I then have a service assembly which defines my services, each service has a repository injected into the constructor by Ninject.

When I'm unit testing my service methods, everything is fine:

public class UserTests
IQueryable<User> users;
int userID;

public UserTests()
users = new List<User>()
new User { EmailAddress = "", Password = "password", ID = 1}

public void Known_User_Can_Login()
// Arrange
var repository = new Mock<IUserRepository>();
var service = new UserService(repository.Object);

repository.Setup(r => r.GetAll())

// Act
bool loggedIn = service.UserLogin("", "password", out userID);

// Assert
Assert.AreEqual(1, userID);

public void Unknown_User_Cannot_Login()
// Arrange
var repository = new Mock<IUserRepository>();
var service = new UserService(repository.Object);

repository.Setup(r => r.GetAll())

// Act
bool loggedIn = service.UserLogin("", "password", out userID);


However, I'm running into problems when testing my controller (another level down).

My controller has dependencies on a service, and the service depends on a repository. I can't seem to get my controller tests to work. Here's what I have so far:

public class AccountTests
IQueryable<User> users;

public AccountTests()
users = new List<User>()
new User { CompanyId = 1, EmailAddress = "", Password = "password"},
new User { CompanyId = 1, EmailAddress = "", Password = "password"}

public void Known_User_Can_Login()
int userID = 0;

var repo = new Mock<IUserRepository>();

// Arrange
var service = new Mock<UserService>(repo);
var controller = new AccountController(service.Object);

// Act
var result = controller.Login(new LoginModel { EmailAddress = "", Password = "password" }) as RedirectToRouteResult;

// Assert
service.Verify(x => x.UserLogin("", "password", out userID), Times.Once());
Assert.AreEqual("Index", result.RouteValues["Action"]);

I keep getting an error about instantiating the UserService (i'm attempting to pass an instance of the UserRepository to it but it isn't working).

I must be doing something daft, but what?

Java - Framework for creating a TCP/HTTP/SOAP APIs from an existing, standalone, interface(s)

I would like to take one or more Java interfaces, and make them callable over a network with an API.

By taking an existing standalone Java interface, and being sure it's stateless, with such a framework I could easily create distributed network Java components callable remotely. Ideally thru TCP, SOAP/HTTP could be an option.

Is there a good framework, possibly lightweight, for doing it?

phpgmailer set from mail issue

I'm trying to use php mail class as shown in the example.

I'm using it my site's contact us form. Can I set the "$mail->From" address as the person who filled the form? When i reveive the mail it always shows that the "from address" as my gmail account. Any help would really helpful.

$mail = new PHPGMailer();
$mail->Username = '';
$mail->Password = 'gmailpassword';
$mail->From = ''; // Like to set this address as the address of the person who filled the form
$mail->FromName = 'User Name';
$mail->Subject = 'Subject';
$mail->AddAddress(''); // To which address the mail to be delivered
$mail->Body = 'Hey buddy, heres an email!';


Django: creating dynamic forms

I have these models and I want to build forms based on the data:

class Location(models.Model):

def __unicode__(self):

class Beverage(models.Model):

def __unicode__(self):

class Inventory(models.Model):

Here is what I want to happen, when a user goes to update inventory for a particular location, I want them to get a form that lists out all the possible beverages for that location (the beverages differ per location) and then create an Inventory form for it that will create a new line in the Inventory table for each Beverage for that Location. Each one needs a timestamp so we can have a history. I think I get that I need formsets, but I have not had any success figuring out how to implement them for this. So, this is kind of a two-parter: 1) is my model design right for this problem? 2) how can I make forms that depend on the number of beverages to build themselves?


Multiplying Product Via Loop in R

I want to multiply all the element in the fact vector,

final_prod = 0.01 * 0.05 * 0.02

This is how I do it in loop.

fact <- c(0.01,0.05,0.02)

final_prod <- 1;
for (i in 1:range(fact)){
all_prod <- all_prod * fact[i];


But the final product it gave is wrong. It should be
0.00001 instead of 0.01.

What's wrong with my approach above?

I understand there is R'ish way. But the reason
I want to do it in loop is because there is more complex
computation involved.

VB2010 Mutli-dimensional Arrays, mind-block

So I am trying to make the card game WAR in visual basic 2010. I have the following code and I kind of know what I need to do next but I just can't get to the next step.

due to how VB formats I can't post my code here,
here is a pastebin link:

What is the function of SetDefaultItem?

i just want to know what is the function of DefaultItem, what is the difference between general MenuItem and it, except bold-font... thank you...

where to start with eclipse plugin programming?

I am new to Java & Eclipse programming.

My work demands me to do Eclipe plugin programming using RTC server & client on RTCversion3.

Can anybody guide me where to start from?

managing Cookies in HttpPost

For using Cookie store In Application and

public class MyApplication extends Application {
public String cookie = null;
private static HttpURLConnection conn = null;
public static CookieStore cookieStore;
public static HttpContext localContext;

public void onCreate() {
// TODO Auto-generated method stub
cookie = null;
cookieStore = new BasicCookieStore();
localContext = new BasicHttpContext();


public HttpURLConnection getSingleConnection(){
return conn;


Using cookies In my multipart Requset Runnable

            DefaultHttpClient client = new DefaultHttpClient();

HttpPost post = new HttpPost(requestUrl);
HttpResponse resp;

MyApplication app = (MyApplication) mContext

try {
resp = client.execute(post,app.localContext);

but i can`t managing it.

i see How do I manage cookies with HttpClient in Android and/or Java?

this page but i can`t handle it...
is there problem in my code?

Facebook,twitter and email not share using share kit

I am a new ios developer and i have created an ios app where i want to share link in to the Facebook,twitter and mail.I am using Xcode 4.2 and ios 5. I browse lot of side and used lot of sample code. But i am not able to do this.Using sharekit library i am able to share image but not able to share link.

Can any one share me any link or any example source code by which i am able to do this. Thanks in advance and sorry for my bad English.

find hour or minute difference between 2 java.sql.Timestamps?

I store a java.sql.Timestamp in a postgresql database as Timestamp data type and I want to find out the difference in minutes or hours from the one stored in the DB to the current timestamp. What is the best way about doing this? are there built in methods for it or do I have to convert it to long or something?

startActivity() causing crash in Android

So I just started learning to develop Android apps, and I have a programming background (Python mainly), so I somewhat know what I'm doing. I'm having a problem with using startActivity(). I've commented code to figure out exactly where the error gets thrown, and it happens right as startActivity() is encountered. The error I get is from the emulator and it is just a popup window that says, "Unfortunately, Test has stopped." (Test is my program name) after I click my button. My code is this

public class DisplayMessageActivity extends Activity {
public void onCreate(Bundle savedInstanceState){

public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(;
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);

Now I know that won't do anything yet, but why is it crashing?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:orientation="horizontal" >

<EditText android:id="@+id/textBox1"
android:hint="@string/textBox1Hint" />
android:onClick="sendMessage" />


My manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="15" />

android:label="@string/app_name" >
android:label="@string/app_name" >
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

android:name=".DisplayMessageActivity" >


I saw that a lot of other people were having problems with this because they had not declared their activities in the manifest, but I think I have done so properly. Any help would be so greatly appreciated.

CGImage bug in 10.7.4?

In MacOS 10.7.3 I was able to save 1024px icns files using CGImage APIs. Now in 10.7.4 I get this error: "_CGImagePluginWriteIcns: unsupported image size (1024 x 1024)"

Is this a bug, isn't it?

How to access the value of username from htpasswd file using python script

I have created a username/ password in htpasswd file. In my python script file I would like to access the username value for further processing. How do I achieve that? I am using Linux OS.

WP Query to list posts published between two particular dates

I just want to List the posts published between two particular dates

I found a solution Here

and my code is Here, unfortunately This is not working !!

function filter_where($where = '') {
$where .= " AND post_date >= '2012-05-09' AND post_date <= '2012-05-11'";
//$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
add_filter('posts_where', 'filter_where');
<?php while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile; ?>

Determine number of bits in integral type at compile time

I have a C library with functions like

obj_from_int32(int32_t& i);
obj_from_int64(int64_t& i);
obj_from_uint32(uint32_t& i);
obj_from_uint64(uint64_t& i);

In this case the types int32_t etc are not the std ones - they are implementation defined, in this case an array of chars (in the following example I've omitted the conversion - it doesn't change the question which is about mapping intergral types to a particular function based on the number of bits in the integral type).

I have a second C++ interface class, that has constructors like

MyClass(int z);
MyClass(long z);
MyClass(long long z);
MyClass(unsigned int z);
MyClass(unsigned long z);
MyClass(unsigned long long z);

Note, I can't replace this interface with std::int32_t style types - if I could I wouldn't need to ask this question ;)

The problem is how to call the correct obj_from_ function based on the number of bits in the integral type. I have tried the following:

// Helper functions
objFromInt(boost::int_t<32>::exact z) { return obj_from_int32(z); }
objFromInt(boost::int_t<64>::exact z) { return obj_from_int64(z); }
objFromInt(boost::uint_t<32>::exact z) { return obj_from_int32(z); }
objFromInt(boost::uint_t<64>::exact z) { return obj_from_int64(z); }

// Interface Implementation
MyClass(int z) : _val(objFromInt(z)) {}
MyClass(long z): _val(objFromInt(z)) {}
MyClass(long long z): _val(objFromInt(z)) {}
MyClass(unsigned int z): _val(objFromInt(z)) {}
MyClass(unsigned long z): _val(objFromInt(z)) {}
MyClass(unsigned long long z): _val(objFromInt(z)) {}

The intent is the compiler will pick the correct overload for the integral type, and boost does the hard work behind the scenes mapping the number of bits to types for each architecture.

The problem is this fails on gcc (4.6.3) (but not of MSVC - so I've been given (false?) hope!). The error is:

In constructor 'MyClass(long int)':
error: call of overloaded 'objFromInt(long int&)' is ambiguous
note: candidates are:
note: objFromInt(boost::int_t<32>::exact)
note: objFromInt(boost::uint_t<64>::exact)
note: objFromInt(boost::int_t<32>::exact)
note: objFromInt(boost::uint_t<64>::exact)

This error is repeated for the long unsigned int& version of the constructor. So, the it appears only the long type causes the problem (although more errors unreported errors could be lurking).

I suspect the root of the problem is int and long are the same size on my architecture: 32 bits, but still would have thought both would just resolve to call obj_from_int32.

Any ideas how to solve this?

(This incorporates suggested solutions - thanks!!)

  • boost::int_t<32>::least instead of exact

  • Not having signed and unsigned in the same overload set (ie have 'objFromInt' and 'objFromUInt')

Delphi XE2: UTF16LE -> UTF8



procedure TForm1.FormCreate(Sender: TObject);


IdTCPClient.Host := '';

IdTCPClient.Port := 8080;


IdTCPClient.IOHandler.Write('Ag8m' + Char(0));

IdTCPClient.IOHandler.Write('LShady|###BBQ' + Char(0));

IdTCPClient.IOHandler.Write('#' + 'Some Text' + Char(0));




function UTF8FromUTF16_2(sUTF16: UnicodeString): UTF8String; 


Result := sUTF16;


procedure TForm1.FormCreate(Sender: TObject);


IdTCPClient.Host := '';

IdTCPClient.Port := 8080;


IdTCPClient.IOHandler.Write('Ag8m' + Char(0));

IdTCPClient.IOHandler.Write('LShady|###BBQ' + Char(0));

IdTCPClient.IOHandler.Write(UTF8FromUTF16_2('#' + '??' + Char(0)));



[1] : working

[2] : not working (string broken > Shady: ??)

See :

UTF8FromUTF16 function Original VB Code : VB 6.0 -> Delphi XE2 Conversion

Help me.. :(

UITabbar disappear when pushing

i'm having trouble with a navigation Controller, when i'm pushing my view controller to an xib a see a UITabbar but in mij xib where i'm pushing the view to i'm doing this to push the xib where i'm pushing to, to another file but when i use this line of code the UITabbar doesn't show up.

What i'm doing in view controller 1 i check if a JSON file contains 0,1 or 2 items when it's for example '1' item in the JSON i would like to push the view controller to a file special for the '2 item file' i'm pushing on this way:

   UIViewController *rootController = 
[[2ViewController alloc]
initWithNibName:@"2ViewController" bundle:nil];

navigationController = [[UINavigationController alloc]

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window addSubview:navigationController.view];
[self.window makeKeyAndVisible];

But when i do that the UITabbar disappear 'under' the view controller. Could somebody help me out solving this problem please?

How do I handle LoginStatus control click?

Am using ASP.NET 4.0 with a LoginStatus control in a Master page. When the status is 'Login' and I click the link, the current page is attempted to be reloaded. I can see that IsPostBack=True.

If I use "Set Next Statement" to avoid my code in Page.Load the redirect to Login.aspx goes without a hitch, otherwise the current page tries to reload and for some reason it fails.

From Page.Load, what is the best way to detect that LoginStatus has been clicked? A click event handler won't work since it fires too late. IsPostBack won't work either (on its own). I do have a BaseMasterPage class that is inherited by my Master page, but again, the Master page loads after Page.Load in all of my pages.

Do I have to handle this click in every one of the pages that use this Master page?

Btw, I also have a BasePage class that all of my pages inherit. I'm just not sure how to detect that LoginStatus has been clicked - and if it has, how to handle it. Would I force a Redirect? That seems like overkill...

Netbeans 7.0.1 acts weird, couldn't even edit the GUI in design mode

I'm experiencing a very weird problem in Netbeans 7.0.1 while designing a GUI.

At first it was all good, I could design and adjust all the swing components easily and normally. But today, for any reason, it turned to be faulty in which the whole JFrame is extended vertically way way way down (~37,000 in height!), and all the components mixed up messily. However, I couldn't do anything about this, since this happened it doesn't allow me to drag the frame's bottom side upward to minimize the height.

The worst thing is that I couldn't select (click on) some of the components, but some others can be. I don't know how to thoroughly explain this weird thing, just have a look at the Screen shot. Image

Tell me if you need any further info.


print a list of names in jsp

I'm trying to print out a list of names and i want to be the one down to another
I'm trying this code:

<td> Names: </td>

<c:forEach items="${names}" var="allnames">
<c:out value="${allnames} " ></c:out>


But it print the one next to the other. What should i change?

P.S: the result now is: Names: nick george john
and i want to be :

         Names: nick

Pin file excel 2010

Is it possible to get a list of recently pinned workbooks in excel 2010
Im trying and searching abt it but not getting a proper solutions

I am able to find recent files through
Application.RecentFiles but unable to find recently pinned files

Android Pitch and Roll Issue

I am working on a tilt app for Android. I am having an issue with Portrait & landscape mode. When the pitch = 90 degrees (phone on end) and even slightly before the roll value goes crazy when there has been no physical change in roll. I have not been able to find a solution to this problem. If anyone can point me in the right direction, it would be appreciated.

Here's a short code dump, so you know it is not an accelerometer error.

final SensorEventListener mEventListener = new SensorEventListener(){
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
setListners(sensorManager, mEventListener);

SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet);
SensorManager.getOrientation(mRotationMatrix, mValuesOrientation);

synchronized (this) {

switch (event.sensor.getType()){

System.arraycopy(event.values, 0, mValuesAccel, 0, 3);

long actualTime = System.currentTimeMillis();

//Sensitivity delay
if (actualTime - lastUpdate < 250) {
else {
sysAzimuth = (int)Math.toDegrees(mValuesOrientation[0]);
sysPitch = (int)Math.toDegrees(mValuesOrientation[1]);
sysRoll = (int)Math.toDegrees(mValuesOrientation[2]);

//invert direction with -1
pitch = (sysPitch - pitchCal)*-1;
roll = (sysRoll - rollCal);
azimuth = sysAzimuth;

lastUpdate = actualTime;

Programmatically assign access control list (ACL) permission to 'this folder, subfolders and files'

I have to assign permission on a folder and it's child folder and files programmatically using C#.NET. I'm doing this as below:

var rootDic = @"C:\ROOT";
var identity = "NETWORK SERVICE"; //The name of a user account.
var accessRule = new FileSystemAccessRule(identity,
fileSystemRights: FileSystemRights.Modify,
inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
propagationFlags: PropagationFlags.InheritOnly,
type: AccessControlType.Allow);

var directoryInfo = new DirectoryInfo(rootDic);

// Get a DirectorySecurity object that represents the current security settings.
DirectorySecurity dSecurity = directoryInfo.GetAccessControl();

// Add the FileSystemAccessRule to the security settings.

// Set the new access settings.
catch (Exception ex)

It does assign permission on my 'C:\ROOT' folder. But it assign permission to the Subfolders and Files only but not the 'ROOT' folder.
enter image description here

Q: How can I define the FileSystemAccessRule instance to assign permission to the ROOT folder, Subfolders and files?

Unexpected end of file in BASH

Writing a simple bash script to do some checks for me in the morning:
One part is pulling down some html files and making sure that they exist.
The other part is ensuring some local files are present, and emailing if they are not.
The problem I am facing is that I am receiving a "syntax error: unexpected end of file" and I can't really understand why it i occuring.
Here is a simplified version of the code:

for myHost in $HOSTS
result=$(wget -T $TIMEOUT -t 1 $myHost -O /dev/null -o /dev/stdout)
result2=$(echo $result | grep "awaiting response")
connected=$(echo $result | grep "404");
if [ "$connected" != "" ]; then
for myEMAIL in $EMAIL
echo -e "$(date) - $myHost is down! \n This is an automated message." | mailx -r "" -s "$SUBJECT" $myEMAIL

numoffiles=`find . -maxdepth 1 -mtime -1 | grep -i .html | wc -l`
if [ "$numoffiles" -ne 5 ]; then
FILE=$(find . -maxdepth 1 -mtime -1 -print| grep -i .html)
mailx -r "" -s "FILE MISSIN" "$EMAIL" << EOF

from using sh -x I can see that it gets to assigning the number of reports to the var "numoffiles", but then it just believes that is the end of the file. has anyone got any suggestions?