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.