Monday, April 30, 2012

Optimization algorithms that does not depend on initial solution

I know some optimization algorithms, such as hill-climbing, simulated-annealing, genetic algorithm.



All of the three I mentioned depend on the initial solutions, i.e., the initial solutions may have a great impact on the quality of the final optimal solution.



I wonder if there are any optimization algorithms that don't depend on initial solutions, at least not as much as these three.



Thanks.





Dividing a integer equally in X parts

I'm looking for a efficient way in PHP to divide a number in equal part. Number will always be integer (no float).



Let's say that I have an array $hours with values from "1" to "24" ($hours['1'], etc) and a variable $int containing an integer. What I want to acheive is spreading the value of $int equally in 24 parts so I can assing the value to each corresponding array entries. (Should the number be odd, the remaining would be added to the last or first values in the 24).



Regards,





JAVA ME Calendar displaying.

So I've been following this tutorial here Link to tutorial. I cant seem to get the application displaying properly though. When I run the application I get this



enter image description here



Here is my code, I'm using embedded classes.



import java.util.Date;
import java.util.Calendar;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;


public class CreateCalendar
{
/**
* Array of strings which holds data for the month and day
* for the calendar application.
*/
static final String[] month_labels = new String[]
{
"January", "Febuary", "March", "April", "May", "June", "July", "August", "Sepetember", "October", "November", "Decemeber"
};
static final String[] weekdays_labels = new String[]
{
"Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"
};

public int startWeekday = 0;
public int padding = 1;
public int borderWidth = 4;
public int borderColor = 0x009900;

/**
* Weekday Labels
*/
public Font weekdayFont = Font.getDefaultFont();
public int weekdayBackgroundColor = 0x009900;
public int weekdayColor = 0xffffff;

/**
* Month/Year Labels
*/
public Font headerFont = Font.getDefaultFont();
public int headerBackgroundColor = 0x009900;
public int headerColor = 0xffffff;

/**
* Cells Labels
*/
public Font font = Font.getDefaultFont();
public int foreColor = 0xffffff;
public int backgroundColor = 0x009900;
public int selectedBackgroundColor = 0xCCFF00;
public int selectedForegroundColor = 0xffffff;

/**
* Size properties
*/
int width = 0;
int height = 0;
int headerHeight = 0;
int weekHeight = 0;
int cellWidth = 0;
int cellHeight = 0;

/**
* Internal time properties
*/
long currentTimeStamp = 0;
Calendar calendar = null;
int weeks = 0;

public CreateCalendar(Date date)
{
calendar = Calendar.getInstance();
setDate(date);
initialize();
}

public Date getSelectedDate()
{
return calendar.getTime();
}

public void setDate(Date d)
{
currentTimeStamp = d.getTime();
calendar.setTime(d);
this.weeks = (int)Math.ceil(((double)getStartWeekday() + getMonthDays()) / 7);
}

public void setDate(long timestamp)
{
setDate(new Date(timestamp));
}

public void initialize()
{
this.cellWidth = font.stringWidth("MM") + 2 * padding;
this.cellHeight = font.getHeight() + 2 * padding;
this.headerHeight = headerFont.getHeight() + 2 * padding;
this.weekHeight = weekdayFont.getHeight() + 2 * padding;
this.width = 7 * (cellWidth + borderWidth) + borderWidth;
initHeight();
}

void initHeight()
{
this.height = headerHeight + weekHeight + this.weeks * (cellHeight + borderWidth) + borderWidth;
}

int getMonthDays()
{
int month = calendar.get(Calendar.MONTH);
switch (month)
{
case 3:
case 5:
case 8:
case 10:
return 30;
case 1:
int year = calendar.get(Calendar.YEAR);
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
default:
return 31;
}
}

int getStartWeekday()
{
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
c.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
c.set(Calendar.DAY_OF_MONTH, 1);
return (c.get(Calendar.DAY_OF_WEEK) + 5) % 7;
}

public void KeyPressed(int key)
{
switch(key)
{
case Canvas.UP:
go(-7);
break;
case Canvas.DOWN:
go(7);
break;
case Canvas.RIGHT:
go(1);
break;
case Canvas.LEFT:
go(-1);
break;
}
}

void go(int delta)
{
int prevMonth = calendar.get(Calendar.MONTH);
setDate(currentTimeStamp + 864000000 * delta);
if(calendar.get(Calendar.MONTH) != prevMonth)
{
initHeight();
}
}

public void paint(Graphics g)
{
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);
g.setFont(headerFont);
g.setColor(headerColor);
g.drawString(month_labels[calendar.get(Calendar.MONTH)] + " " + calendar.get(Calendar.YEAR), width / 2, padding, Graphics.TOP | Graphics.HCENTER);
g.translate(0, headerHeight);
g.setColor(weekdayBackgroundColor);
g.fillRect(0, 0, width, weekHeight);
g.setColor(weekdayColor);
g.setFont(weekdayFont);

for(int i = 0; i < 7; i++)
{
g.drawString(weekdays_labels[(i + startWeekday) % 7], borderWidth + i * (cellWidth + borderWidth) + cellWidth / 2, padding, Graphics.TOP | Graphics.HCENTER);
}

g.translate(0, weekHeight);
g.setColor(borderColor);

for(int i = 0; i <= weeks; i++)
{
g.fillRect(0, i * (cellHeight + borderWidth), width, borderWidth);
}
for(int i = 0; i <=7; i++)
{
g.fillRect(i * (cellWidth + borderWidth), 0, borderWidth, height - headerHeight - weekHeight);
}

int days = getMonthDays();
int dayIndex = (getStartWeekday() - this.startWeekday + 7) % 7;
g.setColor(foreColor);
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);

for(int i = 0; i < days; i++)
{
int weekday = (dayIndex + i) % 7;
int row = (dayIndex + i) / 7;
int x = borderWidth + weekday * (cellWidth + borderWidth) + cellWidth / 2;
int y = borderWidth + row * (cellHeight + cellWidth) + padding;

if(i + 1 == currentDay)
{
g.setColor(selectedBackgroundColor);
g.fillRect(borderWidth + weekday * (cellWidth + borderWidth), borderWidth + row * (cellHeight + borderWidth), cellWidth, cellHeight);
g.setColor(selectedForegroundColor);
}

g.drawString("" + (i + 1), x, y, Graphics.TOP | Graphics.HCENTER);

if(i + 1 == currentDay)
{
g.setColor(foreColor);
}
}
g.translate(0, - headerHeight - weekHeight);
}

private Date getTime() {
throw new UnsupportedOperationException("Not yet implemented"); //TODO get current Time
}

//=====================================================================================================================//

public class CalFrontEnd extends MIDlet
{

public CreateCalendar calendar;
protected Display display;
protected Form mainForm;

public CalFrontEnd()
{

}

public void startApp()
{
calendar = new CreateCalendar(new Date());
calendar.headerFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE);
calendar.weekdayFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
calendar.weekdayBackgroundColor = 0xccccff;
calendar.weekdayColor = 0x0000ff;
calendar.headerColor = 0xffffff;
calendar.initialize();


display.getDisplay(this).setCurrent(
new intCalendar(this));

}

public void pauseApp()
{
}

public void destroyApp(boolean destroy)
{
notifyDestroyed();
}
}}




jQuery dialog popup behind my blog content. How to fix

I have this problem I have dealing with for a while now. My dialog appears to pop up behind my blog content. here is a screenshot.
http://wsoplugins.com/wp-content/uploads/2012/04/Capture.png
can someone help me fix this?
It pops up behind the header content to be specific. The other content below seems fine.
thank you so much.



.ui-dialog{

position: fixed;
z-index: 99999;

}




How to tell if an out parameter was set already?

Is there a way to know if an out parameter was set already or not. This is the pseudocode for what I am looking for:



public virtual string blabla(long num, out bool bval)
{
if (!bval.HasValue)
{
//Do some default logic
bval = defaultValue;
}

return blabla2(num, bval);
}




JScript : How can i trigger Auto Play Slideshow for OnPageLoad Event ? Please Note down the code. Thanx in Advance

Following is The code i have used for playing slideshow of some pictures in my website background. You can check the site as well. www.vishalseth.in/home.html I want to play the slideshow on OnPageLoad event so the user can just pause the slideshow if they want else it will keep running automatically. Please help me with the code.



jQuery(document).ready(function($){

$('body').append('<span id="body_loader"></span>');
$('#body_loader').fadeIn();

//In our jQuery function, we will first cache some element and define some variables:
var $bg = $('#background'),
$bg_img = $bg.find('img'),
$bg_img_eq = $bg_img.eq(0),
total = $bg_img.length,
current = 0,
$next = $('#next'),
$prev = $('#prev')

$(window).load(function(){
//hide loader
$('#body_loader').fadeOut('fast', function(){
init();
}).remove();

});

var intervalID,
play = $('#play'),
titleItem = $('.title-item');

//shows the first image and initializes events
function init(){
//get dimentions for the image, based on the windows size
var dim = getImageDim($bg_img_eq);
//set the returned values and show the image
$bg_img_eq.css({
width : dim.width,
height : dim.height,
left : dim.left,
top : dim.top
}).fadeIn('normal');

//resizing the window resizes the $tf_bg_img
$(window).bind('resize',function(){
var dim = getImageDim($bg_img_eq);
$bg_img_eq.css({
width : dim.width,
height : dim.height,
left : dim.left,
top : dim.top
});
});

var activeTitle = $bg_img_eq.attr('title');
titleItem.html(activeTitle);
titleItem.html(function(){
var text= $(this).text().split(" ");
var last = text.pop();
return text.join(" ")+ (text.length > 0 ? " <span class='word-last'>"+ last + "</span>" : last);
});

play.bind('click', function() {
if($(this).hasClass('pause')) {
clearInterval(intervalID);
$(this).removeClass('pause').addClass('play');
} else {
$(this).addClass('pause').removeClass('play');
intervalID = setInterval("$('#next').trigger('click')", 2000);
}

});

//click the arrow down, scrolls down
$next.bind('click',function(){
if($bg_img_eq.is(':animated'))
return false;
scroll('tb');
});

//click the arrow up, scrolls up
$prev.bind('click',function(){
if($bg_img_eq.is(':animated'))
return false;
scroll('bt');
});
}




Pausing Javascript execution until button press

I'm creating a visualization of a Sudoku creator for my Algorithms class (in Javascript). The algorithm works great, but I'm having trouble finding a way to pause execution.



Currently, I'm using prompt() to pause, but that's bulky and annoying. Is there any way to pause until another function is run (via HTML button) other than a continuous while loop?



I can post code, but I don't think it's needed. I'm not currently using jQuery, but I can if needed.





extract 9 digit number from a string

I basically have an array in php which contains a string, I basically need to filter the string in order to get a 9 digit ID number (which is surrounded by brackets), im sure there could be a way to do this with regex but im clueless.



I know that regex returns its results as an array as there could be multiple results but I know that there will not be multiple results for each string and therefore I need to put the result straight in to my already existing array if possible



example:



function getTasks(){
//filter string before inserting into array
$str['task'] = "meeting mike (298124190)";

return $str;
}




What is the benefit of "using"

I want to understand the difference between



public DataTable ExectNonActQuery(string spname, SqlCommand command)
{
using (DataTable dt = new DataTable())
{
cmd = command;
cmd.Connection = GetConnection();
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
return (dt);
}
}


and



public DataTable ExectNonActQuery(string spname, SqlCommand command)
{
DataTable dt = new DataTable();
cmd = command;
cmd.Connection = GetConnection();
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
return (dt);
}
}


I actually want to understand what is the benefit of creating a new object using "using" instead of creating it directly like this



DataTable dt = new DataTable();




How to obfuscate java code quickly?

How to obfuscate code quickly. I have a very small Java App and I want to deliver the obfuscated code to my client. I have heard a lot about ProGuard to obfuscate code and have downloaded it but doesn't know how to obfuscate my "abc.jar" file.



I checked out its website but it contains a lot of material to read. I don't need heavy obfuscation. I just need a obfuscate that simply changes the name of variables, methods and classes to some unreadable ones. I know proguard provide all of this with a ton of other functionalities too.



Q1. So could anyone tell me please some simple obfuscators or some simple steps to use proguard so that I can just input "abc.jar" and it outputs "obfuscate_abc.jar" or something simple like that.



Q2. One more thing, as my java program uses external libraries, so should i need to obfuscate those libraries too?



Q3. Is there any eclipse or netbeans plugin availabe to this obfuscation?



I have also heard that we should retain the mapping table file with us so that in future we can debug or edit that obfuscated code by first de-obfuscating with the help of that mapping-table which was created at the time of obfuscation.



Q4. So, one more question is Why do we need to keep that mapping-table with us. We can simply retain a copy of un-obfuscated application so as to make changes in that (if required in future). Is there any reason to retain that mapping-table file with us?





I confused on the basic concept of database management system

Ada and Mike share a database file X and execute database queries, T1 and T2, respectively.



Which of the following activities should the database management system NOT do?



(1) When T1 is reading X, T2 is reading X.



(2) When T1 is writing records in X, T2 is writing records in X.



(3) When T1 is deleting records in X, T2 is reading X.




  • A. (1) only

  • B. (2) only

  • C. (1) and (3) only

  • D. (2) and (3) only

  • E. All activities can be done.



I chose B. Am I correct? Please Explain. Thanks so much.






An additional question



in situation (1), will T2 be pending when T1 is still reading??
if yes, why situation (2) and (3) are wrong??
or they can be executed at the same time??





How to check for dependencies before creating an RPM package?

As the title suggests, how do I check without having to compile the package myself? In my case, I am going to build a package from somewhere else.



EDIT: Sorry for being unclear. What I mean by "build a package from somewhere else" is that I have to create a RPM package from source code, not by installing it. Without having to run ./configure, is there other way to check? In the RPM spec file, I have to put in BuildRequire, but how do it know? In SFML source for example, it doesn't have a configure file.





Struts 2 List of List access

I wonder if someone can help.



Background Architecture:



I have an application which contians many areas which have many specific questions, where these questions contian progress



So at a high-level view there can be many applications. A user is associated to maybe many applications.



So I have a list of applications and I can quite easliy iterate my way through and get its relevant details. But when it comes to accessing each specific area to get question progress for some reason it does not work out form me.



So here is logic I want:




for the applications




display its details




for each area(applicaitonId)




display each its completion progress







so to translate to struts I have this



<s:iterator id="app" value="appList" status="row">
<s:iterator id="qsp" value="questionProgessList[%{#row.index}]" status="status">


so applist is the list of all applications with its own getter/setter && questionSetProgress is defined by:



List<ApplicationQuestionSetProgress> getQuestionProgressList(final int index)


or
List> getQuestionProgressList()



So trying in many ways to access the list has proved futile I have tried:



<s:iterator id="qsp" value="questionProgessList">
<s:property />
</s:iterator>


with this:



List<List<ApplicationQuestionSetProgress>> getQuestionProgressList()


but no joy



I've also tried using the iterator index to call the method but it just does not work out.



List<ApplicationQuestionSetProgress> getQuestionProgressList(final int index)


i.e.



<s:iterator id="qsp" value="questionProgessList[%{#row.index}]" status="status"> or <s:iterator id="qsp" value="questionProgessList(%{#row.index})" status="status">



any hints or tips??



TIA





Why are frequencies represented as complex numbers?

In a FFT, the resulting frequencies represent both magnitude and phase. Since each frequency element in the output array of an FFT essentially just describes the SIN wave at each frequency interval, shouldn't it just be magnitude that we need? What is the significance of the phase represented in the imaginary part of the complex number?



To clarify my question, to be able to put a meaning to the phase of a wave, I need a reference point or reference wave.



When an FFT reports the phase for each sin wave in the resulting frequency domain output, what is the reference wave with respect to which it is reporting the phase?





blob detection in C++

I'm new at computer vision, but i need to made a little function in C++, who will detect a white paper sheet even if is something printed on him, and the retrieve the 4 edges coordinates what is what i really need so i can use those coordinates and cut another jpg file and use the cutted image as a opengl textures.
I dont know how to detect the paper.
Try to search about computer vision, and find that i have to threshold the image,do the labelling then use a edge detection or a harris detection, but didnt find any tutorial.
Can any one help me with this, or show me some tutorial who can help me?





Can perl Config::Simple module with properties file with variable assignment

Can Config::Simple work with properties file with variable assignment, e.g.:



server_name=myapp.com
home_url=${server_name}/home/index.html
login_url=${server_name}/login/




replace not updating in database

I have a table with id which is the primary key and user_id which is a foreign key but the session is based on this in my code.
I have tried EVERYTHING, so I will post my full code.
The form should insert if there is not a user_id with the same session_id in the table. If there is, it should update.
At the moment, when the user has not visited the form before (no user_id in the table) and data is inserted in, the page returns to the location page: but the data is not inserted in the table. if the user changes the data once it is updated it doesn't change either.
This is the table structure:



`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
`complete` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)


The code I have been using (and failing):



$err = array();


$user_id = intval($_SESSION['user_id']);
// otherwise
if (isset($_POST['doThesis'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// check if current user is banned
$the_query = sprintf("SELECT COUNT(*) FROM users WHERE `banned` = '0' AND `id` = '%d'",
$user_id);

$result = mysql_query($the_query, $link);
$user_check = mysql_num_rows($result);
// user is ok
if ($user_check > 0) {

// required field name goes here...
$required_fields = array('thesis_Name','abstract');
// check for empty fields
foreach ($required_fields as $field_name) {
$value = trim($_POST[$field_name]);
if (empty($value)) {
$err[] = "ERROR - The $field_name is a required field" ;
}
} // no errors
if (empty($err)) {
$id = mysql_real_escape_string($_POST['id']);
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
//replace query
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query))
echo "the query failed";
else header ("location:myaccount.php?id=' . $user_id");
}}}

$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");


?>


<br>
<form action="thesis.php" method="post" name="regForm" id="regForm" >
class="forms">
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>

<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?> </textarea>
</tr>

<tr>
<td>Abstract<span class="required">*</span>
</td>
<td><textarea name="abstract" style="width:500px; height:150px"
type="text" id="abstract" size="600"><?php echo $row_settings['abstract']; ?>
</textarea></td>
</tr>


<?php }
} else { ?>

//shows fields again without echo


I've tried var_dum($query) but nothing appears



PS I know the code isn't perfect but I'm not asking about this right now





What is the 'pythonic' equivalent to the 'fold' function from functional programming?

What is the most idiomatic way to achieve something like the following, in Haskell:



foldl (+) 0 [1,2,3,4,5]
--> 15


Or its equivalent in Ruby:



[1,2,3,4,5].inject(0) {|m,x| m + x}
#> 15


Obviously, Python provides the 'reduce' function, which is an implementation of fold, exactly as above, however, I was told that the 'pythonic' way of programming was to avoid lambda terms and higher-order functions, preferring list-comprehensions where possible. Therefore, is there a preferred way of folding a list, or list-like structure in Python that isn't the reduce function, or is reduce the idiomatic way of achieving this?





Refactoring session check

I have this repetitive code in all the controllers:



        var user = Session["_User"] as User;

if (user== null)
{
return RedirectToAction("Index");
}


How can I refactor this? should i add this to an attribute or make a Session Wrapper?



What would be the best approach?





How would you decide if you will like the management policies when applying for a company?

Please feel free to close this if you think this is not the right place to ask this question.



However, I think this question is very relevant to every s/w engineer applying for jobs.



I've come to realize that when you join some company you should not only like the product they build, but you should also like the team and the the policies of the management.
Checking if you like the product is easy. You can Google for it. But, how should one decide if he would like the policies of the management. When you are interviewing with someone you get opportunities to ask questions to determine your fit. What are the questions that a candidate should ask to determine if they would like the management policies? Personally, I have also come to realize that management usually tries to be vague about things and tries to sell the team without giving away the entire truth. What are questions you would ask to determine this?
I hope people on this forum will have more experience than me at dealing with this.





Tuesday, April 24, 2012

OSX + Terminal.app + Emacs + make command key operate as meta

I'm on OSX Lion



I running emacs inside of Terminal.app



I want command-x to result in M-x (and in general, command -> M)



I have tried the following solution and they're not what I want:





What I want, is only inside of Terminal.app (or only inside of emacs), to bind the command key to meta. How do I achieve this?





Changing DIV colors using hover and click in JQuery

Could someone please help. I have these two:



I would like the text to change to lightgreen when hovering, white when not hovering, and red when clicked.



$(".music").hover(
function() {
$(this).css('color','lightgreen');
},
function() {
$(this).css('color', 'white');
}
);

$(".music").click(function () {
$('#result').load('album_list_index.php');
$(this).css({ 'color': 'red', 'font-size': '100%' });
});


Thank you in advance



AC



NOTE: ok im sorry i did not make myself clear.



I need the div to be white when not mousedover
I need it to be gree when mouseover
And i need it to be red when clicked, and remain red until another button is clicked.





java replaceAll(regex, replacement) regex command

Hello I would like to know if anyone knows the regex command to remove the following



 name = 


from the following



 name = wlr


leaving only



 wlr


these details are taken from a txt file but the name = part can appear multiple times



so I was thinking something like this would work but it doesnt work properly



 String file_name = newLine3.replaceAll("name = ", "");


Any help appreciated
Thanking You





Assigning Created Joomla User to the Current User

I've created a Joomla plugin for facebook which lets facebook users to login.
Also, I'm creating new user when they first login through faceobok.



I want to set the current user object to the created user.
is it possibile in Joomla? How?



Thanks





Cell Array appending

I have this doubt.. I need to append the array of string in Matlab. Please suggest me how to do it..



I would like to append the string column wise on each iteration..



Here is a small code snippet which i am handling



<CODE>:
for_loop
filename = 'string';
name=[name; filename]
end


Thanks
Kiran





lock screen sometime not display android

i created lock screen application.. Sometimes it give me a problem. problem is that some time default lock screen display rather than my lock screen and some time directly home screen display. i donot know where is the problem. please give me suggestion about this.



LockScreenActivity:
Use
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();



and create ScreenReceiver:
ACTION_SCREEN_OFF
ACTION_SCREEN_ON
ACTION_BOOT_COMPLETED



Refer this link: http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/



in manifeast file : declare service and receiver and permission



The problem is in BroadcastReceiver when
if (recievedIntent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//call activity
}else if (recievedIntent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
}
but the activity call after screen on.. so what is missing or what is problem.. why it is happn pls rply.





Cross Domain SSO with DotenetOpenAuth

I have integrated DotenetOpenAuth to login using google account.

Its working perfect.
Can i achieve this with it ?

Once user logged in site1.com if user browse to site2.com the user get automatically logged in.





how to get data from json?

I have controller



var subCategories = m_listsRepository.GetSubCategories(id);
var items = subCategories.Select(x=>new MyDataNameAndId(){Id = x.Value, Name = x.Text});
return Json(items);


And ajax:



$.ajax({
url: urlString,
type: 'POST',
data: JSON.stringify({ id: districtId }),
dataType: 'json',
contentType: 'application/json',
cache: 'false',
success: function (data) {
alert("success");
$.each(data, function (key, MyDataNameAndId) {
alert(key);//== 0
alert(MyDataNameAndId);// then throws
$('select#ChangeOnsubCategoryId').append('<option value="0">Select One</option>');

$.each(MyDataNameAndId, function (index, manager) {
$('select#ChangeOnsubCategoryId').append(
'<option value="' + manager.Id + '">'
+ manager.Name +
'</option>');
});
});
}
});


what am I doing wrong?



UPDATE:
Controller is worked.
alert("success"); - is show
alert(key); - is show 0
alert(MyDataNameAndId); - not show.
I need generate in 'select#ChangeOnsubCategoryId' options from select#ChangeOnsubCategoryId



How do this? this understand?



I do not know how to show what passed json



json string:



[{"Id":"53","Name":"??????"}]




Where is the webkit framework in lion

I am trying to add webkit framework to Xcode,
steps I followed is



selected the target,
went to the 'build phases' tab,
opened the 'Link binary with Libraries'
Use the + to add the library



But in MacOSX 10.7(Lion),I was not able to see webkit.framework in the framework list.



Any Ideas Where it resides?





Suggest a MySQL Query

I have a table with 3 fields.



ID    Name     ParentID     Active
1 A 0 1
2 B 0 1
3 C 2 1


Now, I want a query where if there is row with ParentID > 0 and active then the row with its parent id (2) is skipped.



Please suggest a single MySQL query to achieve this.



Thank you,
Khuram





Public action method 'undefined' could not be found on controller

I have a page with an ActionLink on it:



@Html.ActionLink(@UserResource.MoreResults, "RowList", routeValues, new { id = "LoadMoreLink", @class = "btn primary small" })


With the following jQuery:



$("#LoadMoreLink").live("click", function () {
// Ajax call to load new results
$.get($(this).attr("href"), function (response) {
...
});
return false;
});


So everytime the link is clicked, I intercept it and perform a GET with ajax. The first time (and only the first time), I got the error below:



enter image description here



Then the code is paused. If I press F5 I can continue without problem. I noticed also that if I breakpoint in this code, the code is processed 2 times. I mean every step (F10) execute each line of code 2 times.



This problem is very strange because I copy/paste this all the code from somewhere else where this problem didn't occurred.



Any idea? Thanks.





setting min date in jquery datepicker

Hi i want to set min date in my jquery datepicker to (1999-10-25) so i tried the below code its not working.



$(function () {
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
showButtonPanel: true,
changeMonth: true,
changeYear: true,
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
minDate: new Date(1999, 10 - 1, 25),
maxDate: '+30Y',
inline: true
});
});


** if i change the min year to above 2002 than it will work fine but if i specify min year less than 2002{like above eexample 1999} it will show only up to 2002.can someone help me. i am using jquery-1.7.1.min.js and jquery-ui-1.8.18.custom.min.js.





Stylesheet for printing, background-color ignored

I create a table where I cycle between giving each tr the class "odd" and "even". In my stylesheet I've got this:




table tbody tr.odd {
background-color: #cccccc;
}


This works from the browser but not when printing. Everything else in my media stylesheet works except this background-color.



I have colors enabled for printing, I can print images with colors... so?





Using WebApi as a standalone project in one solution

If i want to use WebAPI as a service to connect to multiple databases on different servers and retrieve the data that my MVC application will use what is the best way to do it? I don't want do have ApiController(s) in the same project as my MVC project.





How to convert flat data array collection into hierarchical data structure in as3/flex?

I don't want to use GroupCollection and GroupCollection2 due to some reason. I need to do manually.



Please follow Stackoverflow this link for my exact scenario. How can do same with as3 with efficient way.



Thanks,
Raja.J





SQL report error on where help please

I have a report to check for duplicate "vouchers" but have got a little lost and getting an error. Have a look!



Declare @StartDate as  Datetime
Declare @EndDate as Datetime

set @StartDate = GetDate()-14
set @EndDate = GetDate()


SELECT *
FROM (SELECT dupl.TerminalID, dupl.Location, dupl.Country, dupl.VoucherNumber,
MIN(realdupl.vsTransDate)

AS FirstVoucher, MAX(realdupl.vsTransDate) AS LastVoucher

FROM
(SELECT vs.vsTermID AS TerminalID, cfg.cfgLocation AS Location,

cfg.cfgLocationCountry AS Country, vs.vsVoucherNum AS VoucherNumber, COUNT(*) as
NoOfVouchers
FROM

(SELECT vsTermID, vsVoucherNum, vsTransDate, vsReversalIndicator FROM
ProBatchHostDbSec.dbo.vatVouchers (NOLOCK)
)
AS vs
INNER JOIN TermConfig AS cfg WITH (NOLOCK)
ON vs.vsTermID = cfg.cfgTerminalID
WHERE vs.vsReversalIndicator = 0
AND cfg.cfgProductionTerminal = 'Y'
AND cfg.cfgLocationCountry = 'SG'
GROUP BY vs.vsTermID, cfg.cfgLocation,
cfg.cfgLocationCountry, vs.vsVoucherNum
HAVING COUNT(*) > 1
) AS dupl
INNER JOIN
(SELECT vsTermID, vsVoucherNum, vsTransDate, vsReversalIndicator FROM
ProBatchHostDbSec.dbo.vatVouchers

AND dupl.VoucherNumber = realdupl.vsVoucherNum
GROUP BY dupl.TerminalID, dupl.Location, dupl.Country, dupl.VoucherNumber
) AS temp

WHERE temp.FirstVoucher != temp.LastVoucher
AND temp.LastVoucher BETWEEN @StartDate AND @EndDate
ORDER BY temp.TerminalID, temp.LastVoucherdbo.vatVouchers --WITH (NOLOCK)
GROUP BY dupl.TerminalID, dupl.Location, dupl.Country, dupl.VoucherNumber
) AS temp


When I run this I get an error "Incorrect syntax near the keyword 'WHERE'."
Wheres the incorrect syntax??



Thanks in advance!





Calling variable defined inside one function from another function. PYTHON 3.2.3

if I have this:



def oneFunction(lists):
category=random.choice(list(lists.keys()))
word=random.choice(lists[category])

def anotherFunction():
for letter in word: #problem is here
print("_",end=" ")


I have previously defined lists, so oneFunction(lists) works perfectly.



My problem is calling word in line 6. I have tried to define word outside the first function with the same word=random.choice(lists[category]) definition, but that makes word always the same, even if I call oneFunction(lists).



I want to be able to, every time I call the first function and then the second, have a different word.



Can I do this without defining that word outside the oneFunction(lists)?





Agile Vs Spiral Model for SDLC

I believe that Agile is nothing but another implementation of Spiral Model. I am a big supporter of Spiral (The spiral model is a software development process combining elements of both design and prototyping-in-stages, in an effort to combine advantages of top-down and bottom-up concepts) since its beginnings and have seen that lot of projects implement Spiral without knowing that they are operating in a Spiral world. Since the day Agile started gaining popularity the concept of spiral started getting overlooked a little bit. I am sure that for complex projects spiral is still the best alternative but I would like to get a better understanding of the similarities and differences between Agile and Spiral techniques. Can anyone explain their differences/similarities?





Is Port Redirection/Forwarding (i.e. 8443 -> 3389) for Windows Vista/Server 2008 possible with the built-in firewall?

Is it possible to execute port redirection/forwarding with the built-in firewall (or some other software) for Vista/Windows 2008?



I want to forward port 8443 to 3389 (HTTPS forwarded to Remote Desktop port) for RDP access to a server from places where the normal RDP port is blocked. I can do this with a hardware firewall at work, but I don't know if its possible to directly implement it with the built-in firewall for other computers without access to a hardware firewall.



I've tried a simple forwarding rule rinetd (http://www.boutell.com/rinetd) and PortTunnel (steelbytes.com) without success.



Any ideas/suggestions for how to implement this?





Firefox and Updatepanel

I have a problem with FireFox and ASP.NET UpdatePanel.
I have in a form a checkbox and an UpdatePanel. When I check the checkbox, an asp:panel which is into the UpdatePanel should become visible.



<asp:CheckBox ID="cbMoreOptions" runat="server" Text="plus d'options" AutoPostBack="True" OnCheckedChanged="cbOptions_CheckedChanged" /> 

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server" Visible="false">
sssssssss
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cbMoreOptions" EventName="CheckedChanged" />
</Triggers>
</asp:UpdatePanel>


Everything is working fine but not after I refresh the page while the checkbox is checked. If this is happening, the checkbox rest checked the page doesn't make postback more to the server. The firebug shows that the page gets a response and when I verify the its content I have en error 500 which tell that the information of the page is corrupt. All this is happening only in Firefox. In IE8 and Google Chrome everything is ok.



Does anybody have an idea how can I avoid this? It's a bug of Firefox?
All the weird comportment continues until I make enter into the URL textbox. Even if I make F5 nothing happens. What is the difference between F5 and enter into the URL? They shouldn't have the same result?



Thanks a lot.





Monday, April 23, 2012

Select count from each table from a list stored on a table

I have a table tbls with a field name containing names of tables.



I'm trying to form a statement to get the number of rows of each of this tables.



Should I use a stored procedure or is there a simpler way to do it?





How to mange big data on adroid app?

I have big database that I use on my website and I would like to use it on android application without internet connection.



My database can export to .db file. How should I do to use this file for my android app.



Regards





Embedded ActiveMQ broker in Spring/OSGi problems

I ran into a very disturbing issue that's been puzzling me for a while and I was wondering if anyone could give me some insight on this.



Basically, what I'm trying to do is set up an embedded ActiveMQ broker in the Spring context of one of my OSGi bundles (in Felix). I have downloaded the bundle and all dependencies listed in this page. They are all up and running. Here's what my Spring context xml file looks like:



<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:osgix="http://www.springframework.org/schema/osgi-compendium"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:amq="http://activemq.apache.org/schema/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/osgi-compendium http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-2.5.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

<!-- some uninteresting parts ommited -->

<!-- JMS Configurations -->

<amq:broker useJmx="false" start="true">
<amq:transportConnectors>
<amq:transportConnector uri="tcp://localhost:0"/>
</amq:transportConnectors>
</amq:broker>

<!-- other ActiveMQ configs such as destinations and whatnot -->




This looks pretty ok to me. However, during the startup I get the following message:



org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 41 in XML document from URL [bundle://121.0:0/META-INF/spring/bundle-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'amq:broker'.


I've found someone experiencing a similar issue in Eclipse (which I'm also using) and they apparently solved it by making Eclipse point to the bundled .xsd file in the ActiveMQ jar. I attempted to do the same, alas, to no avail.



Does anybody have any ideas on what i might be missing here?



Thanks in advance.





How can I print the contents of a link?

I want the contents of a link get printed by jQuery. How to do it?



Following is my code:

DEMO:



<a href="#" onclick="window.print(); return false;">Print</a> 
?
$(document).ready(function() {
$('ul#tools').prepend('<li class="print"><a href="#print">Click me to print</a></li>');
$('ul#tools li.print a').click(function() {
window.open('www.google.com');
window.print();
return false;
});
}); ?




C#: Array.Sort method for double?

I have an array ( double ) : ox_test with a known number of elements.



when I code :



Array.Sort(ox_test);



and then, just to see if the array it's sorted :



for (int y = 1; y <= ox_test.Length; y++)
MessageBox.Show(".x: " + ox_test[y]);


.. I get ... 0, 0, 0, 0, 0 ( if the number of elements was 5 ). Please help, thank you!



So i modified the both for loops:



for (int y = 0; y < ox_test.Length; y++)



            MessageBox.Show(".x: " + ox_test[y]);


// HERE i get the values not sorted but != 0



        Array.Sort(ox_test);


for (int y = 0; y < ox_test.Length; y++)



            MessageBox.Show(".x s: " + ox_test[y]);


// HERE i get only 0 values





pass NSMutableArray to UITableViewController

I have UIViewController that contains NSMutableArray , I want to pass this array to UITableViewController and view it on the table .. how can I do that ??



I mean I want to (pass) NSMutableArray or any Varilable from UIViewController to UITableViewController not (create) a table





iPhone app - Use pre populated database or rely on a web service?

I'm working on an iPhone app that allows the user to browse a product catalogue. Potentially, this catalogue could hold 1000+ items. Every product is related to a Brand, and have some attributes such as color, size etc.



I'm think of pre-populating a SQLlite DB and including it in my app's bundle, then, like in CoreDataBooks example, on the first launch I'll use the NSPersistentStoreCoordinatorto check if the database has been created, and if not copy the default database to the desired location and move on.



But the product catalogue needs to be updated, and since the database will hold other information that the user added - like add a product to favorite etc., I don't want to overwrite the database once it has been initialized (from the default).



So I was thinking about using the network, calling a webservice, but wouldn't that be way to heavy on the network? It should be fast to browse products, and I fear that relying on webservices will slow down things unacceptably?





Querying Solr via Solrj: Basics

I am trying to query solr via solrj in Eclipse.
I have tried the latest solrj wiki example:



import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.ModifiableSolrParams;

import java.net.MalformedURLException;

public class SolrQuery2 {
public static void main(String[] args) throws MalformedURLException, SolrServerException {
SolrServer solr = new CommonsHttpSolrServer("http://localhost:8080/solr");


// http://localhost:8080/solr/select/?q=outside
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("qt", "/select");
params.set("q", "outside");

QueryResponse response = solr.query(params);
System.out.println("response = " + response);
}
}


However, I cant get past this error no matter what I do:
Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.spi.LocationAwareLogger.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;[Ljava/lang/Object;Ljava/lang/Throwable;)V



Next, I tried the cookbook example:



import java.util.Iterator;
import org.apache.solr.client.solrj.SolrQuery; //Error: The import org.apache.solr.client.solrj.SolrQuery conflicts with a type defined in the same file
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;




public class SolrQuery {

public static void main(String[] args) throws Exception {

CommonsHttpSolrServer server = new CommonsHttpSolrServer("http://localhost:8080/solr");
server.setParser(new XMLResponseParser());
SolrQuery query = new SolrQuery();
query.setQuery("document"); //Error: The method setQuery(String) is undefined for the type SolrQuery
query.setStart(0); //Error: The method setStart(int) is undefined for the type SolrQuery
query.setRows(10); //Error: The method setRows(int) is undefined for the type SolrQuery
QueryResponse response = server.query(query); //Error: The method query(SolrParams) in the type SolrServer is not applicable for the arguments (SolrQuery)
SolrDocumentList documents = response.getResults();
Iterator<SolrDocument> itr = documents.iterator();
System.out.println("DOCUMENTS");
while(itr.hasNext()){
SolrDocument doc = itr.next();
System.out.println(doc.getFieldValue("id")+":"+doc.getFieldValue("content"));
}

}
}


However, that example might be dated for the current api as I cant even import the SolrQuery library.



Does anyone have a quick boilerplate example that works?



Thank you in advance.



PS. I am running windows7 with tomcat7 and solr 3.5. All I am trying to do at this point is a basic query and get the results back in some kind of list, array, whatever. When I query: http://localhost:8080/solr/select/?q=outside in firefox, the results come back just fine.





Collection<Collection<Person>> to Collection<Person> in one linq statment

i have List> i want it to copy all people in the previous collection to List collection.



i did it like:



        var people = new List<Person>();
People.ForEach(q => people.AddRange(q.People));
return people;


is there any better way to do this?





Need if / then statement for javascript validator

With Jquery validator I'm able to use the following if statement to be sure my form is valid before proceeding with Ajax:



var frm = $(this).closest('form');        
if($(frm).valid()){
AJAX JQUERY POST INFORMATION GOES HERE
};


Now I am using Javascript Form Validator from Javascript-Coder.com. The problem is none of the documentation describes a similar function to valid() or a way to check to see if the form is valid before proceeding. I am limited in javascript and could really use help from the community to build a similar if statement.



I am running the validation just fine but even when the validation fails my ajax script continues to run through to completion. In non ajax applications the validation works great and stops automatically before posting to php. But with ajax I can't seem to stop the script when validation fails to allow my user to correct their action.



I tried gleaning something from Here but it didn't get me close enough to do something useful. I tried some variations of what was offered there but I'm missing something.



My validation works great and is:



<script  type="text/javascript">
var frmvalidator = new Validator("send_message_frm");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("desc","alnum","Only numbers and letters are allowed");
frmvalidator.addValidation("desc","req","Please enter a description");
</script>


My ajax script works as well but I need it to not run if validation fails. It is:



$(document).ready(function(){
//Validate form....what can I put here to test if validation is completed properly????

//onclick handler send message btn
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');

$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"company_add.php",
data,
function(data){
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").prepend(data);
}
);
}
);
});
</script>




Two Different types of Arrays into the first Array

I have created a ArrayList<Student> in a object StudentList list1 that is saving[Serialization] a student's information (name,id,age,gpa,etc) into the list1, so that the list1[0] = 1st student's info, then the list1[1] = 2nd student's info and so on.



Also a new ArrayList<Subject> in a object SubjectList list2 for all subject of a student at index 0 example list2[0]=(java,math,etc) [for first student] list2[1]=(c++,english,etc) [for second student] saved in a file.



I want to add the subject next to the student info:



list1 index[0]=1st Student info, index[1]=1st Student's Subjects.

index[2]=1st Student info,index[3]=1st Student's Subjects.



I am stuck with this simple problem.Help please. My codes too much messy couldn't post, Sorry for that.





what is the difference to call performSelectorOnMainThread() between in viewDidLoad() and in eventmethod()? (ios)

//viewcontroller.m

-(void)viewdidLoad
{
self.theOneViewController= [[TheOneViewController alloc]init];
[contentsView addSubview:self.theOneViewController.view];
}


//theOneViewController

- (void)viewDidLoad
{ .
.
.
//UI WORK
.
.
//LONG WORK
[self performSelectorOnMainThread:@selector(initAppList) withObject:nil waitUntilDone:NO];


}



this code, view display UI WORK before LONG WORK is end.So I can have a thread effect.



//viewcontroller.m

-(void) buttonPressed:(id)sender -> event method
{
self.theOneViewController= [[TheOneViewController alloc]init];
[contentsView addSubview:self.theOneViewController.view];
}

//theOneViewController
- (void)viewDidLoad
{ .
.
.
//UI WORK
.
.
//LONG WORK
[self performSelectorOnMainThread:@selector(initAppList) withObject:nil waitUntilDone:NO];
}


In this code, view display UI WORK after LONG WORK is end.
So I can't have thread effect. why?
And I use (performSelectorInBackground:withObject:) instead of (performSelectorOnMainThread withObject:waitUntilDone:) . but this is slower than not using thread.



I want to have thread effect in event method call.
Is there a good way? help me please!





Is shifting bits faster than multiplying and dividing in Java? .NET?

Shifting bits left and right is apparently faster than multiplication and division operations on most (all?) CPUs if you happen to be using a power of 2. However, it can reduce the clarity of code for some readers and some algorithms. Is bit-shifting really necessary for performance, or can I expect the compiler/VM to notice the case and optimize it (in particular, when the power-of-2 is a literal)? I am mainly interested in the Java and .NET behavior but welcome insights into other language implementations as well.





Creating Many-2-Many reference with EF

In my current project (which is really small) i have 3 tables/POCO entities which i would like to manipulate using EF.



The Tables are:




  1. Status (contains status details)

  2. StatusStatusType (which is needed because of the many-2-many relationship)

  3. StatusType (A table which is used to group statuses by type)



I now want to create a new Status in the database and user code like you see below



//Create new status (POCO) entity
var newStatus = new Status {
StatusId = status.Id,
UserId = user.Id,
Text = status.text,
CreateDate = DateTime.Now
};

// Persist need status to database
using (var db = new demoEntities())
{
db.Statuses.AddObject(newStatus);
db.SaveChanges();
}


This code works fine but i want to also set StatusType of the status entity. All possible status types are already included in the StatusType table. I don't want to create new statuses only create a reference.



I figured i should use something like :



status.StatusTypes == "new";




the ball move to position action_down in android

I have a ball in the screen .I want When I implemented action_down , the ball will move to this position .This my code :
public boolean onTouchEvent(MotionEvent event){



    if(event.getAction()==MotionEvent.ACTION_DOWN){
x1 = (int) event.getX();
y1 = (int) event.getY();

float dx = x1-x;
float dy = y1-y;
float d = (float)Math.sqrt(dx*dx+dy*dy);
vx = dx*4/d;
vy = dy*4/d;
}


}
and onDraw:
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);



    Matrix matrix = new Matrix();
matrix2.postTranslate(x - bitmap.getWidth()/2, y - bitmap.getHeight()/2);
x = x+vx ;
y = y+vy ;

canvas.drawBitmap(bitmap, matrix, null);


}



When ,the ball will move to position action_down .But Why the ball was in the position action_down ,it don't stop ?



Please help me?
Thank you?





Is there a way to clone native functions in javascript like window.alert or document.write

What I want to do is change every alert in the code to a custom alert("you used alert");



var hardCodedAlert = alert; //I know this won't work.But what to do ?
window.alert=function(){
if(this.count == undefined)
this.count=0;
this.count=this.count+1;
if(this.count == 1)
hardCodedAlert("You used alert");
};




WP7 SOAP request to PHP server with no WSDL

I am trying to create Windows Phone app that comunicates with my PHP SOAP server that has no WSDL file. I am using this server in my Android app and It works like a charm. But I dont know how to create a SOAP client in C# for Windows Phone? Can anyone help? Thanks





Why TaskFactory.StartNew Task is not starting immediately?

As per the MSDN Documentation TaskFactory.StartNew it Creates and starts a Task. So, for the below code sample



class Program
{
public static void Main()
{
var t =Task.Factory.StartNew(
() => SomeLongRunningCalculation(10, Display)
);
var t1 = Task.Factory.StartNew(
() => SomeLongRunningCalculation(20, Display)
);
Console.WriteLine("Invoked tasks");
Task.WaitAll(t, t1);
Console.ReadLine();
}

public static void Display(int value)
{
Console.WriteLine(value);
}

public static void SomeLongRunningCalculation(int j, Action<int> callBack)
{
Console.WriteLine("Invoking calculation for {0}", j);
System.Threading.Thread.Sleep(1000);
if (callBack != null)
{
callBack(j + 1);
}
}
}


My expected output was




Invoking calculation for 10
Invoking calculation for 20
Invoked tasks
11
21



But, it is displaying




Invoked tasks
Invoking calculation for 20
Invoking calculation for 10
21
11



I would like to learn




  1. Why the tasks are not running immediately after StartNew?

  2. What should I do, to get the output in the expected format?





Python - get position in list

I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?



Example:



testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position




Silverlight site not loaded Completely

There is one site called http://hattrick.cognizant.com which is made up of silverlight application. This site is opening in all other systems except mine.



I am getting an exception called:




Uncaught Error: Unhandled Error in Silverlight Application String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.Convert.ToDateTime(String value, IFormatProvider provider)
at System.String.System.IConvertible.ToDateTime(IFormatProvider provider)
at System.Convert.ToDateTime(Object value)
at Hattrick.ViewModel.ScoreBoardViewModel.LoadMatchDetails(Object parameter)
at Hattrick.ViewModel.DelegateCommand.Execute(Object parameter)
at System.Windows.Interactivity.InvokeCommandAction.Invoke(Object parameter)
at System.Windows.Interactivity.TriggerBase.InvokeActions(Object parameter)
at System.Windows.Interactivity.EventTriggerBase.OnEvent(EventArgs eventArgs)
at System.Windows.Interactivity.EventTriggerBase.OnEventImpl(Object sender, EventArgs eventArgs)
at System.Windows.Controls.SelectionChangedEventHandler.Invoke(Object sender, SelectionChangedEventArgs e)
at System.Windows.Controls.Primitives.Selector.OnSelectionChanged(SelectionChangedEventArgs e)
at System.Windows.Controls.Primitives.Selector.InvokeSelectionChanged(List1 unselectedItems, List1 selectedItems)
at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(Int32 oldIndex, Int32 newIndex)
at System.Windows.Controls.Primitives.Selector.OnSelectedValuePropertyChanged(Object value)
at System.Windows.Controls.Primitives.Selector.OnSelectedValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.RaisePropertyChangeNotifications(DependencyProperty dp, Object oldValue, Object newValue)
at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation)
at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp)
at System.Windows.Data.BindingExpression.SendDataToTarget()
at System.Windows.Data.BindingExpression.SourcePropertyChanged(PropertyPathListener sender, PropertyPathChangedEventArgs args)
at System.Windows.PropertyPathListener.ReconnectPath()
at System.Windows.PropertyPathListener.RaisePropertyPathStepChanged(PropertyPathStep source)
at System.Windows.PropertyAccessPathStep.RaisePropertyPathStepChanged(PropertyListener source)
at System.Windows.CLRPropertyListener.SourcePropertyChanged(Object sender, PropertyChangedEventArgs args)
at System.Windows.Data.WeakPropertyChangedListener.PropertyChangedCallback(Object sender, PropertyChangedEventArgs args)
at System.ComponentModel.PropertyChangedEventHandler.Invoke(Object sender, PropertyChangedEventArgs e)
at Hattrick.ViewModel.ScoreBoardViewModel.RaisedPropertyChanged(String property)
at Hattrick.ViewModel.ScoreBoardViewModel.hattrickClient_GetMatchDatesCompleted(Object sender, GetMatchDatesCompletedEventArgs e)
at Hattrick.HattrickService.HattrickServiceClient.OnGetMatchDatesCompleted(Object state)




Remind you that I didn't not made this site. Is there any problem with my system configuration.
My Configuration



 OS         : Windows 7
Silverlight: Version 5 latest 64bit
Browser : Chrome (Not working in any browser)




Cast object pointer to char array

unsigned char *check = NULL;
check = (dynamic_cast<unsigned char *>( ns3::NetDevice::GetChannel() ));


This is what i am trying. but the error is:



"error: cannot dynamic_cast 'ns3::NetDevice::GetChannel() const()' (of type 'class ns3::Ptr') to type 'unsigned char*' (target is not pointer or reference to class)"



I also tried:
reinterpret_cast



Buti does'nt work at all. Stuck with it. Please HELP HELP HELP...





Tumblr jQuery Like (grabbing from rel)

I coded a html5 (boilerplate) theme with masonry and infinite-scroll which so far has worked pretty well. Now I want to include reblog and like buttons on each post. I've tried to add this but for some reason the like button doesn't work.



URL to theme: http://inspiration.patrikarvidsson.com/



In the bottom of my script.js, I added this like-code.



$('a.like').click(function() {
var post = $(this).closest('.post');
var id = post.attr('id');
var oath = post.attr('rel').slice(-8);
var like = 'http://www.tumblr.com/like/'+oath+'?id='+id;
$('#likeit').attr('src', like);
$(this).toggleClass( 'liked' );
});


Complete scripts.js can be found here:
http://static.tumblr.com/e8lbmds/WB5m2q1it/scripts.js



And if needed, here's plugins.js: http://static.tumblr.com/e8lbmds/NDPm14qu6/plugins.js



The last line of the code above makes the link red; which I suppose indicates that the script responds. But no like is generated. Right after the initializing body tag, I have the following code:



<iframe id="likeit"></iframe>


Appertained css is the following:



#likeit { display: none; }
.liked, .like:hover { color: red !important; }


Any ideas why it's not working?





variation in tower of hannoi puzzle

This is a modified version of tower of hanoi problem,it states



"A tower has n disks of various sizes ,you have to get them in sorted order.But theonly operation allowed is to pull out a set of disks,reverse the set of disks and put it back"



please does anyone know the solution?





Program/Approach to find max heap size and max perm gen size for any system configuration?

To Test the max heap size and max permgen space, As per reply suggested by Gilli at Max amount of memory per java process in windows?, i wrote a simple java class with main method just printing system out



when i ran the class from Console with below param it ran fine but with 2048 it gave the error could not reserve Could not reserve enough space for object heap. It means for my system max heap size is allowed somewhere between 1536 to 2048



 java -Xms1536m -Xmx1536m  TestJVMParam


Fine till here. Now i want to find max permgen size for my system. So i ran the same program with below paramters



 java -Xms1536m -Xmx1536m -XX:PermSize=128m -XX:MaxPermSize=128m TestJVMParam


but again it says Could not reserve enough space for object heap. How is that possible as i have
8GB RAM with windows7 64 bit os. And its not allowing even 128m for permgen?
i am sure i am missing something here but not able to figure it out?





run cygwin terminal using vb

i need a code to type and perform commands in cygwin terminal in hidden mode(background) using visual basic, i was using cmd but now i want to use a Linux source code so i must use linux.
i ran cmd in hidden mode successfully but it isn't working with cygwin, here is the cmd code:

Shell("cmd.exe /k tracert -h " & _h & " " & domain.Text & " > temp" & i + 1 & ".txt & exit", AppWinStyle.Hide, True)



so i have tried



Shell(""C:\cygwin\Cygwin.bat -k tracert -h " & _h & " " & domain.Text & " > temp" & i + 1 & ".txt & exit", AppWinStyle.Hide, True)



and



Shell("C:\cygwin\Cygwin.bat")
'SendKeys.Send("tracert -h " & _h & " " & domain.Text & " > temp" & i + 1 & ".txt"))



but this still didn't work where in the second code i still have to press enter in cygwin to process the traceroute and which should be automaticcaly processed, so i hope that i'll find help in here.





java 6 Thread interrupt

I have got this piece of code:



  public class ThreadInteraction {
public static void main(String[] argv) {
System.out.println("Create and start a thread t1, then going to sleep...");
Thread1 t1 = new Thread1();
t1.start();


try{
Thread.sleep(1000);
}
catch(InterruptedException e) {
System.out.println(e.toString());
}

//let's interrupt t1
System.out.println("----------- Interrupt t1");
t1.interrupt();

for(int i =0; i<100; i++)
System.out.println("Main is back");
}
}

class Thread1 extends Thread {
public void run() {
for(int i =0; i<10000; i++)
System.out.println(i + "thread1");
}
}


It seems like t1.interrupt() doesn't work as in my output all 10000 t1 print appears. Am I doing somethign wrong?





Iphone to control PIC microcontroller

I'm interested in writing an app that send messages over IP (using 3g, not neccesarily on the same WiFi network as the receiving end) to a PIC microcontroller connected to a router (via ethernet or wifi)



I saw some descriptions and examples on how to send messages on the same network, not sure if just by giving a different IP it would work outside the network it self. I was wondering how can it be received by the PIC (still hasn't decided which PIC, depends on the possibility to perform this)
and in turn, depends on the msg received, the PIC will perform an action, for example, light a certain LED in a LED array.



I have the sending side (the app sending over IP), and receiveing side (the PIC which lights the LEDs)
I'm just not quite sure what to send, or if such "translation" is even possible.



I've searched the web but couldn't find any such thing except for made kit (for RC cars for example)
Thanks.
Carmel





git clone never completes

I am trying to use git clone on Mac OS Snow Leopard. All I do is "git clone https://*/project.git" from documents/projects directory. For some reason operation never completes and stops at random points somewhere at the "Receiving Files:" stage(different % of copied files each time). Am I doing something wrong?





Send JSON request - JQuery analog

I need to send a JSON request similar to jQuery's ajax method.



The official documentation quote on the data parameter says:




If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting




So I have the same situation - a key that maps to an array "parameters":[123123, {"category":"123"}]



The complete data parameter looks like



$.ajax({
url: "/api/",
data: {"parameters":[123123, {"category":"123"}], "anotherParameter":"anotherValue"}


Would you mind telling how to achieve the same functionality in Java ?





Center header in menu control

How do I vertically center a header in the menu control?



This was my try:



<MenuItem Header="File" StaysOpenOnClick="True" FontFamily="Arial" VerticalAlignment="Center">
<MenuItem Header="Open" Click="Open_Click" IsEnabled="True"/>
</MenuItem>
</Menu>


But its aligned to the Top-left.



What am I doing wrong?



[EDIT]



My whole menu now looks like this:



<Menu Canvas.Left="0" Canvas.Top="0" Name="menu1" Margin="0,0,0,384">
<MenuItem Header="File" StaysOpenOnClick="True" FontFamily="Arial" VerticalAlignment="Center">
<MenuItem Click="Open_Click" IsEnabled="True">
<MenuItem.Header>
<TextBlock Text="Open" VerticalAlignment="Center"/>
</MenuItem.Header>
</MenuItem>
</MenuItem>
</Menu>


The header text 'file' still isn't vertically centered (which is what i want to center).
What exactly is this code centering? Is it the text 'open'?



[/EDIT]





Friday, April 20, 2012

Consistent grid headers with Flexigrid for jQuery

So I'm trying to use the flexigrid plugin. It looks like it's going to work great aside from the fact that it looks like you have to manually set the column widths. Otherwise, the column headers do not match up with the body columns.



Is there any way of automatically matching these up, while still allowing the column widths to be defined by the length of the content in the columns (as is the normal table behavior).



Thanks!





"Lazy initialization" of jdbc connections from jndi datasource/connection pool: feasibility

I have a main controller servlet in which i instantiate a datasource. The servlet opens and closes the connections. Mainly, the servlet instantiates a command from the application using the "factory pattern". here is some code to explain:



public void init() throws ServletException {
super.init();
try {
datasource =(DataSource) getServletContext().getAttribute("DBCPool");
}
catch (Exception e) {

}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//some code...
connection = getConnection();//where getConnection is a method: datasource.getconnection();
//now a command (a java class) is instantied, to which the CONNECTION obj is passed as parameter
cmdFactory.getInstance().getCommand(Cmd).execute(tsk,connection);

//Then wherever there is catch exception i close() the connection
// and it is always closed in finally
finally {
if(connection!=null)
connection.close()
}

}


Now , this works fine However now i got some new cases where some commands might not need to open a db connection because the data it is seeking for are cached in an identity map.



I tried to pass the "Connection" obj as a "null" parameter in the .execute(tsk,connection); and then in the corresponding java class to open a connection if needed



--> it did open the connection, however when process goes back to servlet : "Connection" is null as thus not closed.

What can i do to make the "Connection" obj's value get updated so that when back in servlet it is not "Null" anymore and i'd be able to close it?



I generally prefer to use a controller servlet that opens/close db connections, so what would be the best way to deal this kind of scenario where you have to do some sort of "lazy loading" a db connection from the pool and at the same time keep the opens/close of db connection assigned to the servlet?



Update (to explain further):




  • say i have a command : X.java

  • this command might/might not need a db connection (depends if the data searched for are in the identity map or not)



The system that i would like to have is:



(1)"client request"



(2)---> "Servlet": command.execute(connection)//where connection = null for now



(3) ---> "Command X": Do i need to go to database or record is in identity map?

(3.a) Case where it is needed to go to the database:

(3.a.1)connection = datasource.getconnection

(3.a.2) go get the data



(4)--->back to servlet: close "connection" in "Servlet"



Right now it is working until (3.a.2), but once back in (4) it appears that connection is still "null" and thus the code:



finally { 
if(connection!=null)
connection.close()
}


Does not work (doesn't close the connection) and thus the db pool get drained like that.
How could connection - which starts as "null" and changes inside command "X"- get "globaly" updated to the its new value, and not only "updated" inside the scope of command "X"?





What is causing this in android webView?

I am getting the following exception and not able to debug it.



Please help.



    04-20 10:55:58.052: WARN/dalvikvm(9255): threadid=8: thread exiting with uncaught exception (group=0x400207d8)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): FATAL EXCEPTION: WebViewCoreThread
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.ViewRoot.checkThread(ViewRoot.java:2812)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.ViewRoot.invalidateChild(ViewRoot.java:607)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2505)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.View.invalidate(View.java:5115)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebView.viewInvalidate(WebView.java:2565)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebView.invalidateContentRect(WebView.java:2584)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebView.access$6200(WebView.java:304)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebView$PrivateHandler.handleMessage(WebView.java:7860)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.os.Handler.dispatchMessage(Handler.java:99)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.os.Looper.loop(Looper.java:123)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:637)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at java.lang.Thread.run(Thread.java:1096)
04-20 10:55:58.102: WARN/ActivityManager(172): Force finishing activity com.Hy5/.activity.Hy5CanvasActivity


thanks
Sneha





Xcode : How to display json image array in UITableView using multithreading?

I have few images on my server whose names are stored in the phpmysql table. The table contains two fields: id and images. I have prepared a php to fetch the images in json encoded formatted as mentioned:



jsonFetch.php



<?php
$dbhost = "localhost";
$dbname = "userauth";
$dbuser = "root";
//$DB_Pass = "root";
$dbtable = "images";

@mysql_connect($dbhost, $dbuser);
$db = mysql_select_db($dbname);


$sql = "SELECT * FROM $dbtable";
$query = mysql_query($sql);

while($row = mysql_fetch_array($query))
{
$rows[] = array(
//"id" => $row[0],
"image" => $row[1]
//"description" => $row['description']);
);
}

$json = json_encode($rows);
$callback = $_GET['images'];
echo $callback.$json ;
//print_r($json);

?>


Now, when i hit the url, i am getting following response:



[{"image":"./95462"},{"image":"./8838upload_image.jpg"}{"image":"./43185upload_image.jpg"},{"image":"/17426upload_image.jpg"}]



I am getting json array as above.



The next step is to display the above array in multithreaded manner in UITableView.
I am getting the images from url when i hardcode them but when it comes to json parse, i am a noob. I have tried every possible manner in which json can be parsed so for you reference, i am posting the .m file. :



#import "json.h"

@interface profilePhotos(Private)
- (void) initialize;
- (void) loadImage:(id)arg;
- (void) updateTableView:(id)arg;
- (void) addImagesToQueue:(NSArray *)images;
- (void) addImagesToQueue:(NSArray *)arrayImages;
- (void) addImagesToQueue:(NSArray *)arrayDataFromServer;
- (void) showcommentView;
- (void) hidecommentView;
@end

@implementation profilePhotos
@synthesize photosTable;
@synthesize addPhotos;
@synthesize deletePhotos;
@synthesize back;
@synthesize imageQueue, loadedImages, imageLoaderOpQueue, commentView;
//@synthesize photosView;


-(void)initializeWith:(int)buttonTag{

tag = buttonTag;

NSLog(@"tag = %d", tag);
}

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (!(self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
return self;
}

[self initialize];
return self;
}

- (void) awakeFromNib
{
NSLog(@"AsyncImageLoadingViewController::awakeFromNib called");
[super awakeFromNib];
[self initialize];
}

- (void) viewDidLoad
{
NSLog(@"AsyncImageLoadingViewController::viewDidLoad called");
[super viewDidLoad];
}

- (void) viewDidAppear:(BOOL)animated
{
NSLog(@"AsyncImageLoadingViewController::viewDidAppear called");
[super viewDidAppear:animated];


NSArray *images = [NSArray arrayWithObjects:
@"http://dl.dropbox.com/u/9234555/avatars/ava01.gif",
@"http://dl.dropbox.com/u/9234555/avatars/ava02.gif",
@"http://dl.dropbox.com/u/9234555/avatars/ava03.gif",
@"http://dl.dropbox.com/u/9234555/avatars/ava04.gif",
@"http://dl.dropbox.com/u/9234555/avatars/ava05.gif", nil];

[self addImagesToQueue:images];
NSLog(@"addImagesToQueue: %@",self);


}


#pragma mark -
#pragma mark Private Methods

/*!
@method
@abstract initializes class variables
*/
- (void) initialize
{
NSLog(@"AsyncImageLoadingViewController::initialize called");

NSMutableArray *a = [[NSMutableArray alloc] init];
self.imageQueue = a;
//[a release];

a = [[NSMutableArray alloc] init];
self.loadedImages = a;
//[a release];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
self.imageLoaderOpQueue = queue;
//[queue release];
}

/*!
@method
@abstract updates tableview for the newly downloaded image and scrolls the tableview to bottom
*/
- (void) updateTableView:(id)arg
{
NSLog(@"AsyncImageLoadingViewController::updateTableView called");

if ((arg == nil) || ([arg isKindOfClass:[UIImage class]] == NO)) {
return;
}

// store the newly downloaded image
[self.loadedImages addObject:arg];
//[arg release];

// refresh tableview
[self.photosTable reloadData];

// scroll to the last cell of the tableview
NSIndexPath *lastRow = [NSIndexPath indexPathForRow:([self.loadedImages count] - 1) inSection:0];
[self.photosTable scrollToRowAtIndexPath:lastRow
atScrollPosition:UITableViewScrollPositionBottom
animated:YES];
}

/*!
@method
@abstract downloads images, this is the method that dispatches tasks in the operation q ueue
*/
- (void) loadImage:(id)arg
{
NSLog(@"AsyncImageLoadingViewController::loadImage called");

if ((arg == nil) || ([arg isKindOfClass:[NSString class]] == NO)) {
return;
}

// create a local autorelease pool since this code runs not on main thread
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// fetch the image
NSLog(@"AsyncImageLoadingViewController::loadImage - will download image: %@", arg);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:arg]];
UIImage *image = [UIImage imageWithData:data];
NSLog(@"image: %@",image);

// update tableview with the downloaded image on main thread
[self performSelectorOnMainThread:@selector(updateTableView:) withObject:image waitUntilDone:NO];

//[pool release];
}

/*!
@method
@abstract adds images to the queue and starts the operation queue to download them
*/
- (void) addImagesToQueue:(NSArray *)images
{
NSLog(@"AsyncImageLoadingViewController::addImagesToQueue called");

[self.imageQueue addObjectsFromArray:images];
NSLog(@"addImagesToQueue Array: %@", self);

// suspend the operation queue
[self.imageLoaderOpQueue setSuspended:YES];

// add tasks to the operation queue
for (NSString *imageUrl in self.imageQueue) {
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImage:) object:imageUrl];
[self.imageLoaderOpQueue addOperation:op];
// [op release];
}

// clear items in the queue and resume the operation queue to start downloading images
[self.imageQueue removeAllObjects];
[self.imageLoaderOpQueue setSuspended:NO];
}


#pragma mark -
#pragma mark UITableViewDataSource Methods

- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{

return [self.loadedImages count];



}

- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"CellIdentifier";

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:CellIdentifier] autorelease];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:[NSString stringWithFormat:@"cellID%d",indexPath.row]];

cell.accessoryType =UITableViewCellAccessoryNone;
//cell.accessoryType =UITableViewCellAccessoryDisclosureIndicator;




}

for(UIView *subviews in cell.subviews)
[subviews removeFromSuperview];


UIImageView *photo;
photo=[[UIImageView alloc] init];
[photo setImage:[self.loadedImages objectAtIndex:indexPath.row]];
[photo setFrame:CGRectMake(0, 5, 150, 120)];
[cell addSubview:photo];
return cell;
}





-(void)aMethod:(UIButton *)sender{

//[sender tag];

NSIndexPath *indexPath = [photosTable indexPathForCell: (UITableViewCell*)[[sender superview]superview]];

NSLog(@"[sender tag] is %d",[sender tag]);



if([sender tag]==indexPath.row){

textField = (UITextField*)[cell viewWithTag:[sender tag]];
textField.hidden=NO;
}
//}


}



#pragma mark -
#pragma mark UITableViewDelegate Methods

-(void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

[tableView deselectRowAtIndexPath:indexPath animated:YES];


}




- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload{
// [self setPhotosView:nil];
[self setPhotosTable:nil];
[self setAddPhotos:nil];
[self setDeletePhotos:nil];
[self setBack:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:( UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


I believe that something is needed to be done in viewDidAppear method but what is it i don't understand.



Kindly, help me out. I have tried every possible json method . May be i am making some errors in that but i am all the way frustrated. Please help me please.