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 http://dl.dropbox.com/u/47312995/Twerk.rar



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)

pygame.init()

def game():

os.environ['SDL_VIDEO_CENTERED'] = '1'
mouse.set_visible(False)
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()
display.set_caption('Twerk')
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)
textpos.top = 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
screen.blit(menu,[0,0])
pygame.display.set_caption("TWERK")

#Text
#"Welcome to Escape"
#needs replacing with logo
text("Twerk",60,white,300)

#"Instructions"
text("Instructions",310,white)
text("----------------------------------------------------------------------------------------",320,white)
text("Avoid the the enemies",340,white)
text("Last as long as you can!",360,white)
text("Press space to start",420,white)
pygame.display.flip()


while start == True:
positionx=[]
positiony=[]
positionxmove=[]
positionymove=[]
falling = False
finish = False
score=0
enemies=1
velocity=1

for i in range(enemies):
positionx.append(random.randint(300,400)+random.randint(-300,200))
positiony.append(random.randint(200,340)+random.randint(-200,100))
positionxmove.append(random.randint(1,velocity))
positionymove.append(random.randint(1,velocity))


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)
pygame.display.update()
game=time.localtime()

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

first=True
strtTime=time.localtime()

while not finish or falling:
screen.blit(backdrop, (0,0))
for i in range(enemies):
screen.blit(ballpic,(positionx[i],positiony[i]))
(mousex,mousey)=mouse.get_pos()
screen.blit(mouseball,(mousex,mousey))
display.update()
strt = time.localtime()

if first:
while True:
end=time.localtime()
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):
positionymove[i]=1000
positionxmove[i]=0


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:
falling=False
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:
temp=positionxmove[i]
positionxmove[i]=positionxmove[j]
positionxmove[j]=temp
temp=positionymove[i]
positionymove[i]=positionymove[j]
positionymove[j]=temp

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:

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


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();

xmlhttp.onreadystatechange=function()
{
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 = "http://metpetdb.rpi.edu/metpetwebsearchIPhone.svc?" + parameterString;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>



<script type="text/javascript">

$(function(){

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

var results = loadXMLDoc(parameters);

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

});


</script>


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




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 {  

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


UPDATED: Code for Createmarker



private void createMarker() {  
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}


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();
postjson.put(json);
// Execute HTTP Post Request
System.out.print(json);
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) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<ListView android:id="@+id/android:list" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>

<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>
</LinearLayout>

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


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;
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.some);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.widgets, null, null, null);
this.setListAdapter(adapter);

add_time = (Button) findViewById(R.id.btntime);
add_time.setOnClickListener(this);
add_new=(Button) findViewById(R.id.btnAddNew);

add_new.setOnClickListener(new OnClickListener() {

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


}
});
}

public void onClick(View v) {
showDialog(0);
}

@Override
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.setView(vw);
alertdialog.setIcon(R.drawable.icon);
alertdialog.setTitle("Select time");
time_picker=(TimePicker) vw.findViewById(R.id.timepicker);
time_picker.setIs24HourView(false);
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(R.id.btntime);
mHour=time_picker.getCurrentHour();
mMinute=time_picker.getCurrentMinute();
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");
}

}
});
alertdialog.show();
}
return super.onCreateDialog(id);
}
}




Writing an LLVM Pass

i'm trying to create an LLVM pass using the guide at http://llvm.org/releases/2.9/docs/WritingAnLLVMPass.html

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
LIBRARYNAME = Hello

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

# 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:



ifndef LLVM_SRC_ROOT
include $(LEVEL)/Makefile.rules
else
include $(LLVM_SRC_ROOT)/Makefile.rules
endif


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)
w.spin();
}
}


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 asp.net web app using:



-ASP.NET MVC 3 Webforms

-Linq to sql

-MSsql server database.

-WCF



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: http://llvm.org/releases/3.0/docs/WritingAnLLVMPass.html for creating an llvm pass, but i have the following error when i use



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


Error opening '../../../Release/lib/Hello.so': ../../../Release/lib/Hello.so: 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: llvm.org/releases/3.0/docs/GettingStarted.html#tutorial) 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...



Thanks..





.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 == www.mysite.com {
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:@"http://api.somexml.com/xml"]];

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

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

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



}


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:



$('#tabs').tabs({

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()) {
u.getMessages().add(data);

u.getKey().interestOps(SelectionKey.OP_WRITE);
}


but whene I run this function I see




Exception in thread "main" java.lang.IllegalArgumentException




this line make error



u.getKey().interestOps(SelectionKey.OP_WRITE);


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



MORE INFO:



In a constructor I make Selector



_selector = Selector.open();


I run server



public void startServer() throws IOException {
while (true) {
_selector.select();

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

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

if (!key.isValid())
continue;
if (key.isAcceptable())
accept(key);
else if (key.isReadable())
read(key);
else if (key.isWritable())
write(key);
}
}
}


I accept connection



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

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.



        //u.getKey().interestOps(SelectionKey.OP_WRITE);
}
key.interestOps(SelectionKey.OP_WRITE);


Full read and write function:



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

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

try {
read = channel.read(buffer);
} catch (Exception e) {
e.printStackTrace();
}

if (read == -1) {
_userMap.remove(channel);

channel.close();
key.cancel();

return;
}

byte[] data = new byte[read];

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

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

for (User u : _userMap.values()) {
u.getMessages().add(data);

u.getKey().interestOps(SelectionKey.OP_WRITE);
}
//key.interestOps(SelectionKey.OP_WRITE);

///////
}

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

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

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

channel.write(ByteBuffer.wrap(item));
}

key.interestOps(SelectionKey.OP_READ);
}


SOLUTION:



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



        u.getChannel().keyFor(_selector).interestOps(SelectionKey.OP_WRITE);




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.





preg_matchvalidation

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?



Thanks!



UPDATE:-



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++];
leftCounter--;
}
//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
{
currentLeft++;
leftCounter--;
}
}
}


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)) { ...


and



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.



Thanks,
Ian





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

I have MPEG-4 video stream at http://pool.amursu.ru/video.mpg 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">
jwplayer("container").setup({
flashplayer: "/jwplayer/player.swf",
width: 800,
height: 450,
levels: [
{
bitrate: 300,
file: "http://pool.amursu.ru/video.mpg",
width: 800
}
],
provider: "http",
"http.startparam":"starttime"
});
</script>


It's available on http://pool.amursu.ru/



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.



UPD:



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. http://pool.amursu.ru/