Monday, April 30, 2012

Mouse control not responding

I've just started using pygame. I've created my game but it's really unstable and crashes (having issues exiting).

I've created a welcome page but it has created a bug with game control (the character controlled by the mouse has stopped responding), I've tried few methods but just results in more game crashes and errors. can you please help me out to debug anything you might spot. you download the game from her

the code:

import pygame
from pygame import *
import random
import time
import os
import sys
from pygame.locals import *

black = (0,0,0)
white = (255,255,255)


def game():

os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = display.set_mode((800,500))
backdrop = pygame.image.load('bg.jpg').convert_alpha()
menu = pygame.image.load('green.jpg').convert_alpha()
ballpic = pygame.image.load('ball.gif').convert_alpha()
mouseball = pygame.image.load('mouseball.gif').convert_alpha()
back = pygame.Surface(screen.get_size())

def text(text,x_pos,color,font2=28):
tfont = pygame.font.Font(None, font2)

text=tfont.render(text, True, color)
textpos = text.get_rect(centerx=back.get_width()/2) = x_pos
screen.blit(text, textpos)

start = False
repeat = False
while start == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
start = True
#falling = True
#finish = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
#game over screen

#"Welcome to Escape"
#needs replacing with logo

text("Avoid the the enemies",340,white)
text("Last as long as you can!",360,white)
text("Press space to start",420,white)

while start == True:
falling = False
finish = False

for i in range(enemies):

font = pygame.font.Font(None, 28)
text = font.render('Starting Twerk... ', True, (100,100,100))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery

screen.blit(backdrop, (0,0))
screen.blit(text, textRect)

while start == True:
score= (end[1]-game[1])*3600 + (end[4]-game[4])*60 + end[5]-game[5]
if score > 1: break


while not finish or falling:
screen.blit(backdrop, (0,0))
for i in range(enemies):
strt = time.localtime()

if first:
while True:
score= (end[3]-strt[3])*3600 + (end[4]-strt[4])*60 + end[5]-strt[5]
if score > 3: break
first = False

if falling:
for i in range(enemies):

for i in range(enemies): positionx[i]=positionx[i]+positionxmove[i]
for i in range(enemies): positiony[i]=min(600,positiony[i]+positionymove[i])

if falling:
for posy in positiony:
if posy<600: falling=True

if not falling:
for i in range(enemies):
for j in range(i+1,enemies):
if abs(positionx[i]-positionx[j])<20 and abs(positiony[i]-positiony[j])<20:

for i in range(enemies):
if positionx[i]>600: positionxmove[i]*=-1
if positionx[i]<0: positionxmove[i]*=-1
if positiony[i]>440: positionymove[i]*=-1
if positiony[i]<0: positionymove[i]*=-1

for i in range(enemies):
if abs(positionx[i]-mousex)<40 and abs(positiony[i]-mousey)<40:

score= (endTime[3]-strtTime[3])*3600 + (endTime[4]-strtTime[4])*60 + endTime[5]-strtTime[5]
falling = True
finish = True

Thank you in advance

Can't return xmlhttp.responseText?

Any insight into the problem here? When run, the code yields nothing. No text appears on the page. If I uncomment the commented line, the xml results appear. Why can't I pass it as a variable? (I do get the alert, fyi, so the function is being called.)

 <script type="text/javascript">
function loadXMLDoc(parameterString)
alert("loadXMLDoc has been called.");
var xmlhttp = new XMLHttpRequest();

if (xmlhttp.readyState==4 && xmlhttp.status==200)

//document.getElementById("xmlResults").innerHTML = xmlhttp.responseText;
alert("Got the response!");
return xmlhttp.responseText;
else document.getElementById("xmlResults").innerHTML = "No results."

var url = "" + parameterString;"GET",url,true);

<script type="text/javascript">


//left out irrelevant code which creates the var "parameters"

var results = loadXMLDoc(parameters);

document.getElementById("xmlresults").innerHTML = results;



<div id="xmlresults"></div>

Android: Constantly Update Map With Coordinates from Web Service

Hello I am writing an app that makes the use of coordinates from a webserver. I know how to retrieve the coordinates from the webservice, but once I get them how can I constantly display them on the map. Sort of like the Location Listener updates the point on the map when the location from the location manager changes. I want to constantly update the points I receive from the webservice.
Is this done with a Service? If so how?

        public class GeoUpdateHandler implements LocationListener {  

public void onLocationChanged(Location location) {
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);

UPDATED: Code for Createmarker

private void createMarker() {  
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");

UPDATED: Code for getting coordinates from webservice...

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(".../android/serverFile.php");
JSONObject json = new JSONObject();
try {
JSONArray postjson=new JSONArray();
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
} catch (IOException e) {
} finally {
try {
} catch (IOException e) {
String jsonStr = sb.toString();
JSONObject jsonObj = new JSONObject(jsonStr);
String longitudecord = jsonObj.getString("lon");
String latitudecord = jsonObj.getString("lat");


Android custom listview with edit text,button and label

i want to make an custom list view in which there should be button edittext and textview and below listview there should be one button with text as Add New and when user click the Add New button the same widget that are in first row of listview should display in second row of list view and again when user click to Add New button same things should happen .
please help me with full xml and java code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:layout_width="fill_parent" android:layout_height="fill_parent"
<ListView android:id="@+id/android:list" android:layout_width="fill_parent"

<LinearLayout android:id="@+id/linearLayout1"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<Button android:text="Time" android:layout_weight="1" android:id="@+id/btntime" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<EditText android:text="" android:layout_weight="1" android:id="@+id/ettext"
android:layout_width="70dp" android:layout_height="wrap_content"></EditText>
<Button android:text="Record" android:layout_weight="1" android:id="@+id/btnRecord"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="alert" android:layout_weight="1" android:id="@+id/btnAlert"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

<Button android:layout_width="wrap_content"
android:layout_marginLeft="230dp" android:layout_height="wrap_content"
android:id="@+id/btnAddNew" android:text="Add new"></Button>

java code

public class some extends ListActivity implements OnClickListener {
Button add_time, enter_text, record, alert_alarm,add_new;
TimePicker time_picker;
View vw;
AlertDialog.Builder alertdialog;
int mHour,mMinute;
public void onCreate(Bundle savedInstanceState) {

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.widgets, null, null, null);

add_time = (Button) findViewById(;
add_new=(Button) findViewById(;

add_new.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
Toast.makeText(getApplicationContext(), "hi", 1000).show();


public void onClick(View v) {

protected Dialog onCreateDialog(int id)
alertdialog=new AlertDialog.Builder(this);
switch (id)
case 0:

LayoutInflater layout_inflater=getLayoutInflater();
vw=layout_inflater.inflate(R.layout.widgets, null);
alertdialog.setTitle("Select time");
time_picker=(TimePicker) vw.findViewById(;
alertdialog.setNegativeButton("cancel",new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which)
// TODO Auto-generated method stub

alertdialog.setPositiveButton("set", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which)
add_time=(Button) findViewById(;
if (mHour>12)
add_time.setText((mHour-12)+":"+mMinute+" "+"PM");
if (mHour==12)
add_time.setText("12"+":"+mMinute+" "+"PM");
if (mHour<12)
add_time.setText(mHour+":"+mMinute+" "+"AM");

return super.onCreateDialog(id);

Writing an LLVM Pass

i'm trying to create an LLVM pass using the guide at

but i'm having several problems:

  • i haven't many of the folder that are indicated into the guide (lib/Transform/Hello) and (Debug+Asserts), i have created them, is it right? what's the right path?
    i create these: /usr/lib/llvm-2.9/lib/Transforms/Hello and /usr/lib/llvm-2.9/Debug+Asserts

  • when i try to make the file in the guide i have error:


# Makefile for hello pass

# Path to top level of LLVM heirarchy
LEVEL = /usr/lib/llvm-2.9/build #*********I MODIFY THIS!!!! ***************

# Name of the library to build

# Make the shared library become a loadable module so the tools can
# dlopen/dlsym on the resulting library.

# Tell the build system which LLVM libraries your pass needs. You'll probably
# need at least LLVMSystem.a, LLVMSupport.a, LLVMCore.a but possibly several
# others too.
LLVMLIBS = LLVMCore.a LLVMSupport.a LLVMSystem.a

# Include the makefile implementation stuff
include $(LEVEL)/Makefile.common

and i modify also other lines into Makefile.common:

include $(LEVEL)/Makefile.rules
include $(LLVM_SRC_ROOT)/Makefile.rules

because it doesn't find the Makefile.rules (in this way it works)

but now i have this error when i do make into the folder containing my hello.c file (/usr/lib/llvm-2.9/lib/Transforms/Hello):

make: ***  No rule to make target "/configure", needed by "/config.status".  Stop.

what's the problem?!?

Save SQLite database

In my application, I'm using a database to store some data, but if I close my app, my database will be deleted too. So I want to know if there is any mean to save my database and re-use it for the next launch of my app.

I use for the moment
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);

in order to create my database.

Thanks for your help

Regarding expressing array in simpler terms

I am developing application..

    class Wheel {
private int size;

Wheel(int s) {
size = s;

void spin() {
System.out.print(size + " inch wheel spinning, ");


public class Bicycle {
public static void main(String[] args) {
Wheel[] wa = { new Wheel(15), new Wheel(17) };
for (Wheel w : wa)

But Please advise that how could we express Wheel[] wa = { new Wheel(15), new Wheel(17) }; in more simpler terms.

Can ASP.NET MVC3 Applications Host in cloud without specific code changes?

I had created an web app using:

-ASP.NET MVC 3 Webforms

-Linq to sql

-MSsql server database.


What would need to be done to host it on a cloud service? Should i convert it in to Azure application or not. can i directly upload my ASP.Net MVC Web application in a Cloud without specific code changes that would be required before hosting.

llvm pass error

i'm using this guide: for creating an llvm pass, but i have the following error when i use

opt -load ../../../Debug+Asserts/lib/ -hello < hello.bc > /dev/null

Error opening '../../../Release/lib/': ../../../Release/lib/ undefined symbol: _ZN4llvm12PassRegistry12registerPassERKNS_8PassInfoEb
-load request ignored.
opt: Unknown command line argument '-hello'. Try: 'opt -help'

note that i haven't the folder "Debug+Asserts" but "Release"

someone know what's the problem?

maybe because for creating the Hello.bc file i use llvm-clang instead of llvm-gcc? (this guide says to use llvm-gcc but it doesn'n work: or maybe because i have opt version 2.8 while i'm using llvm-3.0 ?

Android:drag and drop items from one list to another

I am looking for a nice user interface where i can move files from one folder(in phone memory) to another(cloud storage space) using drag and drop..

Can i represent files in my folders as a listView?drag and drop in it?

Can anybody help me with a sample or point me in the right direction or give any info thing regarding this...


.htaccess if directive

in .htaccess I have something like this:

RewriteCond %{REQUEST_URI} (\/out\/pictures\/)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (\.jpg|\.gif|\.png)$ core/utils/getimg.php

I want to change it to

RewriteCond %{REQUEST_URI} (\/out\/pictures\/)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
if url == {
RewriteRule (\.jpg|\.gif|\.png)$ core/utils/getimg.php
} else {
RewriteRule (\.jpg|\.gif|\.png)$ core/utils/getimg1.php

Is it possible in some way?

RaptureXML kind of slow

I've recently switched from TBXML to RaptureXML, and even though pulling in information is much easier, there is a noticeable delay when I tap the tab bar button containing my xml table view.

In my viewDidLoad method I have the following"

events = [[NSMutableArray alloc] init];

[self loadURL];

And my loadURL method is the following:

- (void)loadURL {

RXMLElement *rootXML = [RXMLElement elementFromURL:[NSURL URLWithString:@""]];

[rootXML iterateWithRootXPath:@"//event" usingBlock:^(RXMLElement *event) {
[events addObject:[NSArray arrayWithObjects:
[event attribute:@"uri"],
[event attribute:@"displayName"],
[event attribute:@"type"],

[rootXML iterateWithRootXPath:@"//location" usingBlock: ^(RXMLElement *location) {
[events addObject:[NSArray arrayWithObjects:
[location attribute:@"city"],
[location attribute:@"lat"],
[location attribute:@"lng"],

[rootXML iterateWithRootXPath:@"//start" usingBlock:^(RXMLElement *start) {
[events addObject:[NSArray arrayWithObjects:
[start attribute:@"time"],
[start attribute:@"date"],


Is there something I can do to speed it up? Also when I assign my row count as [events count] I'm getting 19 rows when I should only get 6. Please help.

jQuery UI Tabs "Select" Event Being Overridden by "Click" Event -- Uncaught TypeError

I'm having some trouble selecting a tab programmatically. My tabs are loading inside a Fancybox dialog window, which is launched on click of a link. Basically, I want to perform certain actions any time a tab is selected, and also select a specific tab when a link is clicked.

I am initializing jQuery UI Tabs with the select event like so:


select: function(event, ui) {

// grab value of a form input
var text = $(someElement).val();

// check its length
if ( text.length > 0 ) {
// do stuff

Later on in my JS file I have the following:

$(document).on('click', 'a.edit', function() {
if($category == 'book') {
// load the tab specific to the 'book' category
$('#tabs').tabs({ selected: 3 });

When I click the a.edit link for an item in the "book" category, my console throws this error:

Uncaught TypeError: Cannot read property 'length' of undefined

Then, instead of the tabs loading in the Fancybox, nothing happens. This error is not thrown when I click the link for items that are not in the book category. Thus, two things are painfully evident:

  1. I am a n00b

  2. My select event is apparently getting overridden by the click event, so text is not set

I've tried setting a default for text at the top of my JS file but that doesn't work. My question, then, is:

What is the correct way to initialize UI Tabs with a select event, while also being able to programmatically select a tab with a click event?

Or, more concisely,

Why am I getting that damn error?

interestOps throws IllegalArgumentException

I wand send a message to all User in map.

    for (User u : _userMap.values()) {


but whene I run this function I see

Exception in thread "main" java.lang.IllegalArgumentException

this line make error


getKey() returns SelectionKey, getMessages returns ArrayList, data is a byte[] array with message I read using;


In a constructor I make Selector

_selector =;

I run server

public void startServer() throws IOException {
while (true) {;

Iterator<SelectionKey> keys = _selector.selectedKeys().iterator();

while (keys.hasNext()) {
SelectionKey key =;

if (!key.isValid())
if (key.isAcceptable())
else if (key.isReadable())
else if (key.isWritable())

I accept connection

private void accept(SelectionKey key) throws IOException {
ServerSocketChannel serverChannel = (ServerSocketChannel);
SocketChannel channel = serverChannel.accept();

User u = new User(key);
_userMap.put(channel, u);

channel.register(_selector, SelectionKey.OP_READ);

In read function whene I read message I have this for each loop. But whene is one user and I move line with interestOps just behind loop it works.


Full read and write function:

private void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel);

ByteBuffer buffer = ByteBuffer.allocate(2048);
int read = -1;

try {
read =;
} catch (Exception e) {

if (read == -1) {



byte[] data = new byte[read];

System.arraycopy(buffer.array(), 0, data, 0, read);

/// WYSy?A DO WSZYSTKICH. usun??

for (User u : _userMap.values()) {



private void write(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel);

ArrayList<byte[]> msg = _userMap.get(channel).getMessages();
Iterator<byte[]> i = msg.iterator();

while (i.hasNext()) {
byte[] item =;




I can't answer my own question now, so put it here:

SelectionKey in accept method is a little handicapped. I tried to replace it with new key in read method and it works. So in User class I don't keep SelectionKey var any more, now I keep SocketChannel. SocketChannel have keyFor method, so whene I have selector I can get key


Printing html5 template from within C++ program automatically

I'm trying to find a way through C++ to create a program that fills in an html5(or CSS) text template for user invoices and has it automatically print them. Unfortunately my searches for anything like this has been quite awful as i'm probably missing key terminology to search on.

To keep it organized, I want to:

  • Create an invoice template in html5

  • Fill in various fields with the information inside of a C++ application

  • Have the C++ application automatically print the designed invoice template

Creating the application and invoice are not issues, but rather trying to find a creative way to have it print without the program requiring a user to be present has been. Can anyone guide me towards a solution to do something like this? Thanks for any insight, it's greatly appreciated.


Okay, everything I've checked on this site referring to validation isn't what I'm looking for.

What I'm looking to do is a minimum length and maximum length of a value in firstname and secondname, this is the code which I currently have.

        if (isset($_POST['submit'])) {
$errors = array();

if (isset($_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "You have not entered a first name";

if (isset($_POST['secondname'])) {
$sn = $_POST['secondname'];
} else {
$errors[] = "You have not entered a second name";

I was just wondering how would I apply preg_match to those which the minimum is 4 letters and the maximum is 15?

I do know it's something to do with

if(preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname']))

In doing this I tried to do

    if (isset($_POST['firstname']) && preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname')) {

But that also gave me an error :/

Could anyone give me a solution for this?



Nvm, I found a way around it. I just did this

if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3> You must enter between 4 and 15 characters! </h3></center>";
} else {
$errors[] = "You have not entered a name";

For both the firstname and secondname. :)

Fast in-place partitioning of sorted array into two sorted subarrays

Edit - I removed all unnecessary context explanation - too wordy and ultimately irrelevant to the problem :)

This is not homework - I've written the question like it is to ensure that all the nuances are communicated.

Given the sorted arrays:

 int[] ints =  { 0, 1, 2, 3, 4, 5, 6 };
//this one is important - my current solution fails on this
int[] ints2 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Note due to a clarification asked by a colleague, all that's guaranteed about these arrays is that element[n] will be less than or equal to element[n+1].

Successful operations on these will separate them into two sub arrays L and R (indicated below):

/*ints == */  { 1, 3, 5, 0, 2, 4, 6 }
/*|> L <| |> R <|*/

/*ints2 == */ { 1, 3, 5, 7, 9, 0, 2, 4, 6, 8 }
/*|> L <| |> R <|*/

L contains the integers that are odd and R contains those that are even, whilst retaining the original sort-order of those elements within those subarrays.

The function will NOT resort to re-sorting the elements (a lengthy sort operation will already have been performed in advance) and it won't use a temporary array. I believe that means I'm looking for O(N) complexity and O(1) memory.

The function will be provided with the start and end elements of each sub array - i.e. the caller will know in advance how many items will fall on the left/right sides (possibly by scanning the array in advance for odd/even).

This where my code is at now - I've updated it and commented it from what was in the original post:

public void DivideSubArray(int[] array, int leftStart, int leftCount, 
int rightStart, int rightCount)
int currentLeft = leftStart, currentRight = rightStart;
int leftCounter = leftCount;
int temp;
int readahead;
while (leftCounter != 0) {
if ((array[currentLeft] % 2) == 0)
//remember the element we swap out
temp = array[currentRight];
//Set as next item on the right. We know this is the next lowest-sorted
//right-hand item because we are iterating through an already-sorted array
array[currentRight++] = array[currentLeft];
// * read ahead to see if there are any further elements to be placed
// * on the left - move them back one by one till there are no more.
readahead = currentLeft + 1;
while ((array[readahead] % 2) != 0)
array[currentLeft++] = array[readahead++];
//Now write the swapped-out item in, but don't increment our currentLeft.
//The next loop will check if the item is in the correct place.
array[currentLeft] = temp;
else //this item is already in the correct place

When called as follows:

int numOdd = ints.Count(i => (i % 2) == 1);
DivideSubArray(ints, 0, numOdd, numOdd, ints.Length - numOdd);

It produces the expected array for ints (and many other arrays), but not ints2:

{ 1, 5, 3, 7, 9, 0, 2, 6, 4, 8 }

So it partitions correctly - but swaps 3,5 and 6,4. I understand why: because in the first loop 5 is swapped to the left, then 2 is propagated over because the algorithm says that 5 is odd and should stay. I have a decision tree written out that'll fix it, but having followed it a few loops it infers that the solution is recursive.

I'm struggling to see how to get around this without running more sort operations within the sub array (don't want that), or creating temporary lists/arrays as workspace (might as well stick with my current solution instead).

I feel there must be a simple way to exploit a single 'spare' variable to swap the items - I just can't see it - I'm hoping the SO collective brain will :)

is_null vs ===null [closed]

Possible Duplicate:

What's the difference between is_null($var) and ($var === null)?

Is there any difference between following code:

if(is_null($x)) { ...


if($x===null) { ...

gettimeofday/settimeofday for Making a Function Appear to Take No Time

I've got an auxiliary function that does some operations that are pretty costly.

I'm trying to profile the main section of the algorithm, but this auxiliary function gets called a lot within. Consequently, the measured time takes into account the auxillary function's time.

To solve this, I decided to set and restore the time so that the auxillary function appears to be instantaneous. I defined the following macros:

#define TIME_SAVE struct timeval _time_tv; gettimeofday(&_time_tv,NULL);
#define TIME_RESTORE settimeofday(&_time_tv,NULL);

. . . and used them as the first and last lines of the auxiliary function. For some reason, though, the auxiliary function's overhead is still included!

So, I know this is kind of a messy solution, and so I have since moved on, but I'm still curious as to why this idea didn't work.

Can someone please explain why? Ubuntu 10.04 x86_64.


How to make IE 6 play MPEG-4 HTTP stream?

I have MPEG-4 video stream at and I can to watch it using Chrome or Firefox, but Internet Explorer 6 doesn't play it, just attempts to load it forever (I think, it waits for end of file, which, probably, won't ever happen).

I've tried to use Flowplayer and JWplayer, but with no success:

<div id="container">Loading the player...</div>
<script type="text/javascript">
flashplayer: "/jwplayer/player.swf",
width: 800,
height: 450,
levels: [
bitrate: 300,
file: "",
width: 800
provider: "http",

It's available on

The videostream is done by D-Link DCS-2130 webcam and proxied by nginx.

Any ideas to get it working in IE?

P.S> I can set video/mpeg MIME-type for video stream, but it brokes playback in Chrome and doesn't help for IE.


For now I've done an unfair solution: found an URL in camera's web interface, from where I can get a single videoframe, proxied it with Nginx, and refresh it every second with javascript. Totally unfair, but works everywhere.