Wednesday, April 25, 2012

Notification Service for Blackberry OS 4.5 application

I am developing an application similar to email application.Whenever new message is received my notification service should indicate change to user by updating icon,also, the notification service should continuosly listen to server for incoming events.

I am developing in os version 4.5.

Facebook batch calls with JSONP

As of 10.04.2012,
There is a short paragraph in the Facebook developer document for 'batch request' entitled: Batch calls with JSONP, which reads:

"The Batch API supports JSONP, just like the rest of the Graph API - 
the JSONP callback function is specified using the 'callback' query string
or form post parameter."

I thought that meant you can also do a batch request using JSONP from Javascript (which will be a GET request, as JSONP works only as a GET request), so I tried that, with adding a 'batch' parameter (containing objects describing requests for batch as in the doc) to the query string.
Response from FB server was:

Only POST is allowed for batch requests

So, questions:

1. What did they mean in that paragraph?

2. Is there a way to do an asynchronous batch request from Javascript?

Looking for a WinForms control that can represent time values

I am looking for a third-party open source or commercial WinForms control that can represent the following values:

Total Duration of Task.

Time Elapsed.

Time Remaining.

Have not been able to find one.

When a subclass is instantiated, is only one object created?

Since many constructors also call the superclass constructor, it seems like one could think that both the subclass and the superclass are instantiated when a subclass is instantiated; i.e. more than one object is created.

Is still just one object created?

Thank you

C Program: newbie trying to pass 2D string array into a function

Programming in C ( with -std=C89), and running into errors trying to pass a character string array into a function.

In main(), I've declared the array as follows:

#define ROWS 501
#define COLS 101
void my_function( char **);
char my_array[ROWS][COLS];

In my_function, I've declared the array as:

void my_function( char **my_array )

I'm getting this error:

warning: passing argument 1 of 'my_function' from incompatible pointer type,
note: expected 'char **' but argument is of type 'char (*)[101]

PHP echo $_SERVER['PHP_SELF'] with added variable?

Just want to do $_SERVER['PHP_SELF'] as a link with ?logout=1 appended to it.

<a href="<?php echo ''$_SERVER['PHP_SELF']'.logout=1' ?>" id="add"><input type="button" value="LOGOUT" /></a>


Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in F:\export\srv\www\vhosts\main\htdocs\php\assign3\m_a2_functions.php on line 90

Redis monitoring info

I'm trying to figure out how to capture the following metrics in redis for monitoring the server. I looked at the INFO command but it does not provide such info.

  1. Operations / sec

  2. a breakdown of commands served, like history of commands served by of gets, sets, zincrby, zscore etc in the past hour?

  3. Reads per second

  4. writes per second

how to get referrer from a redirected url

I have an url

which redirects to .

How do I get the referrer (i.e in my action for ?

One option was to add the referring domain as a parameter . .

Is there a way to get the referrer without passing old referrer as a parameter. Like we would get from **request.referrer**. request.referrer doesn't seem to work with redirected urls.

I am using Ruby on Rails for my development.

Converting searchable PDF to a non-searchable PDF

I have a PDF which is searchable and I need to convert it into a non-searchable one.

I tried using Ghostscript and change it to JPEG and then back to PDF which does the trick but the file size is way too large and not acceptable.

I tried using Ghostscript to convert the PDF to PS first and then PDF which does the trick as well but the quality is not good enough.

gswin32.exe -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pswrite -r1000 in.pdf
gswin32.exe -q -dNOPAUSE -dBATCH -dSAFER -dDEVICEWIDTHPOINTS=596 -dDEVICEHEIGHTPOINTS=834 -dPDFSETTINGS=/ebook -sDEVICE=pdfwrite -sOutputFile=out.pdf

Is there a way to give a good quality to the PDF?

Alternatively is there an easier way to convert a searchable PDF to a non-searchable one?

Loading fixtures in django unit tests

I'm trying to start writing unit tests for django and I'm having some questions about fixtures:

I made a fixture of my whole project db (not certain application) and I want to load it for each test, because it looks like loading only the fixture for certain app won't be enough.

I'd like to have the fixture stored in /proj_folder/fixtures/proj_fixture.json.

I've set the FIXTURE_DIRS = ('/fixtures/',) in my
Then in my testcase I'm trying

fixtures = ['proj_fixture.json']

but my fixtures don't load.
How can this be solved?
How to add the place for searching fixtures?
In general, is it ok to load the fixture for the whole test_db for each test in each app (if it's quite small)?

how to differentiate xml from html links in java

I have a list of links, containing links to html and xml pages, how can I extract the xml links from the list? in java


Send a message to a friend, I wonder Javascript API

Republic of Korea, I am a developer.

Now Facebook and Twitter-based website make.

Javascript API as a message to several friends

I want to spend.

So I consulted the Iframe Javascript API methods or using Facebook page looked as sending.

I wonder.

I use to send messages to friends as a Javascript API that provides a?

I do not know English well. So I used Google translator.

Please understand.

FB.api (path, "post", {

message: msg,

caption: "caption caption",

link: "",

description: "Description Description",

picture: "",

tag: "Tag",

name: "name names",

access_token: accessToken

}, Function (response) {

if (! response | | response.error){

alert ("error");



alert (;



Why does setting the `right` CSS attribute push an element to the left?

I have a very basic page with two elements, an outer green box, and inner blue box. I am confused as to why setting the right attribute on the inner box would move it to the left? Furthermore I am confused as to why right:0 would not align the boxes right edge to the right edge of the parent box? Here is my short example page...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<style type="text/css">
#outer {
background-color : green;
width : 500px;
height : 500px;

#inner {
position : relative;
background-color : blue;
height : 400px;
width : 400px;
top : 10px;
right : 20px;
<div id="outer">
<div id="inner">



Google Chrome Uses Wrong Size of Favicon

When I create a a ICO file on the Mac using 'Icon Composer' it allows specifying five images (16x16, 24x24, 32x32, 48x48, 256x256). If I specify a 16x16 and 32x32 Google Chrome (Mac OS X) use the 32x32 image as the icon that appears next to the name on the tabs and under the favourites (it is resized to 16x16). This causes the icon to look blurry.

Am I creating my favicon.ico correctly? Do I need to do anything else to tell the browser to use the 16x16 image? I currently have:

<link rel="shortcut icon" href="/favicon.ico" />

Saving Images To A Plist With NSUserDefaults

I have an app that behaves like a photo gallery. I'm implementing the ability for the user to delete the photos, by placing an invisible button over each UIImageView, and calling removeObject when they tap on the button. This code is working great, but its dependent upon tags. I need to tag every UIImageView / UIButton in interface builder in order for this to work. So, I'm now trying to save the images. I'm in a pretty strange predicament, if I use NSUserDefaults to save the pictures (I'm storing them in an array), I can delete the images perfectly, but I cant get them to save/load. If I use NSData to save the images in the array, I can save/load the images, but I cant delete them since my current code depends on the UIImageViews tags, which I can't use with NSData.

So I'm totally lost on what to do right now. I'm very, very new to programming and am shocked that I even made it this far. Any help or advice on what or how to edit my code to make this work is much appreciated, thanks!

Here is my entire file just for reference. This is how I grab the images, and how I'm attempting to save / load them:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
if (imageView.image == nil) {
imageView.image = img;

[self.array addObject:imageView.image];

[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];


if (imageView2.image == nil) {
imageView2.image = img;

[self.array addObject:imageView2.image];

[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];

if (imageView3.image == nil) {
imageView3.image = img;

[self.array addObject:imageView3.image];

[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSLog(@"Image on didenterbackground: %@", imageView);

[self.array addObject:imageView.image];
[self.array addObject:imageView2.image];
[self.array addObject:imageView3.image];

[self.user setObject:self.array forKey:@"images"];
[user synchronize];

- (void)viewDidLoad
self.user = [NSUserDefaults standardUserDefaults];
NSLog(@"It is %@", self.user);
self.array = [[self.user objectForKey:@"images"]mutableCopy];
imageView.image = [[self.array objectAtIndex:0] copy];
imageView2.image = [[self.array objectAtIndex:1] copy];
imageView3.image = [[self.array objectAtIndex:2] copy];

UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self

Here is how I delete the image when the user taps on the hidden button over the UIImageView:

- (IBAction)deleteButtonPressed:(id)sender {
NSLog(@"Sender is %@", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:@"Delete"
message:@"Are you sure you want to delete this photo?"
otherButtonTitles:@"Yes", nil];
[deleteAlertView show];

int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;

- (UIImageView *)viewForTag:(NSInteger)tag {
UIImageView *found = nil;
for (UIImageView *view in self.array) {
if (tag == view.tag) {
found = view;
return found;

- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex

if (buttonIndex != [alertView cancelButtonIndex]) {
NSLog(@"User Clicked Yes. Deleting index %d of %d", alertView.tag, [array count]);
NSLog(@"The tag is %i", alertView.tag);

UIImageView *view = [self viewForTag:alertView.tag];
if (view) {
[self.array removeObject:view];

NSLog(@"After deleting item, array count = %d", [array count]);
NSLog(@"Returned view is :%@, in view: %@", [self.view viewWithTag:alertView.tag], self.view);
((UIImageView *)[self.view viewWithTag:alertView.tag]).image =nil;

[self.user setObject:self.array forKey:@"images"];

running OS on bochs returned error

I'm working on an OS programming project called pintos. It is run on bochs following the command pintos run nameOfProcess

And here's the error message I get

Writing command line to /tmp/eKW3NMXoGT.dsk...
squish-pty bochs -q
Bochs x86 Emulator 2.5.1.svn
Built from SVN snapshot, after release 2.5.1
Compiled on Apr 6 2012 at 19:37:19
00000000000i[ ] reading configuration from bochsrc.txt
00000000000i[ ] installing x module as the Bochs GUI
00000000000i[ ] using log file bochsout.txt
Next at t=0
Writing command line to /tmp/eKW3NMXoGT.dsk...
squish-pty bochs -q
Bochs x86 Emulator 2.5.1.svn
Built from SVN snapshot, after release 2.5.1
Compiled on Apr 6 2012 at 19:37:19
00000000000i[ ] reading configuration from bochsrc.txt
00000000000i[ ] installing x module as the Bochs GUI
00000000000i[ ] using log file bochsout.txt
Next at t=0
(0) [0x00000000fffffff0] f000:fff0 (unk. ctxt): (invalid) ; ffff
<bochs:1> fgets() returned ERROR.
debugger interrupt request was 0
(0).[0] [0x00000000fffffff0] f000:fff0 (unk. ctxt): (invalid) ; ffff
(0) [0x00000000fffffff0] f000:fff0 (unk. ctxt): (invalid) ; ffff
<bochs:1> fgets() returned ERROR.
debugger interrupt request was 0
(0).[0] [0x00000000fffffff0] f000:fff0 (unk. ctxt): (invalid) ; ffff

Also my bochsrc.txt

romimage: file=$BXSHARE/BIOS-bochs-latest, address=0xe0000  
vgaromimage: file=$BXSHARE/VGABIOS-lgpl-latest
boot: disk
cpu: ips=1000000
megs: 4
log: bochsout.txt
panic: action=fatal
clock: sync=none, time0=0
ata0-master: type=disk, path=/tmp/eKW3NMXoGT.dsk, mode=flat, cylinders=1, heads=16, spt=63, translation=none
com1: enabled=1, mode=term, dev=/dev/stdout

Bochs was built from source with extra configurations on my Ubuntu 11.04

Struct.Error, Must Be a Bytes Object?

I am attempting to execute the code:

    values = (1, 'ab', 2.7)    
s.struct.Struct('I 2s f')
packed = s.pack(*values)

But I keep getting the error:

    Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: argument for 's' must be a bytes object

Why?How do I fix this?

Java / Eclipse (WindowBuilder plugin) - how do I effectively use Swing Actionlisteners?

My question is specific to Eclipse and the Swing WindowBuilder plugin.

To make simple Swing apps I normally create a class and extend a JFrame. I make my Swing components private class variables. This allows me to add an Actionlisteners and access the swing components in actionPerformed(), like this:

public class MyClass() extends JFrame implements ActionListener {
private JButton btnClickMe = new JButton("Click me");

public MyClass() {

public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == btnClickMe) { // do something }

public static void main(String[] args) {
new MyClass();

By default the WindowBuilder plugin create Swing component variables I guess in what would be considered the constructor (public MyClass()), rather than private class variables. As a result due to scope I am not able to use ActionListeners the way I am used to since the Swing variables are not visible to actionPerformed().

Can anyone advise how this can be overcome?

How does the textbox + button actually do the searching in

I was just curious as to how the textbox + button search actually performs the search to fill up my gridviews, because I couldn't see anywhere that causes the databounds or anything. Is it a post-back thing? How does it work?! o.o

<asp:TextBox ID="SearchBox" runat="server"></asp:TextBox>
<input id="Submit1" type="submit" value="Search" />

Thanks heaps :)

I want to get the current position for ruby script only

Ruby script only, please tell me the best practice to get the current position of latitude, longitude.

How do Java method annotations work in conjunction with method overriding?

I have a parent class Parent and a child class Child, defined thus:

class Parent {
void foo() {
// implementation irrelevant
class Child {
foo() {
// implementation irrelevant

If I obtain a Method reference to Child::foo, will childFoo.getAnnotation(MyAnnotation.class) give me @MyAnnotation? Or will it be null?

I'm interested more generally in how or whether annotation works with Java inheritance.

How do I clear the console in Objective-C

I'm making a console-based application in Objective-C which relies on being able to clear the console periodically. How can this be done? All I've seen on SO and Google were ways to have the developer clear the console with X-Code, but that will not do.

One solution I found on Yahoo! Answers told me to do the following, but it does not run due to being unable to find a file:

NSTask *task;
task = [[NSTask alloc]init];
[task setLaunchPath: @"/bin/bash"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"clear", nil];
[task setArguments: arguments];

[task launch];
[task waitUntilExit];

How to use an API level 8 class when possible, and do nothing otherwise

I have a custom view in my Android App that uses a ScaleGestureDetector.SimpleOnScaleGestureListener to detect when the user wants to scale the view via a 2 finger pinch in or out. This works great until I tried testing on an Android 2.1 device, on which it crashes immediately because it cannot find the class.

I'd like to support the pinch zoom on 2.2+ and default to no pinch zoom <2.1. The problem is I can't declare my:

private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
public boolean onScale(ScaleGestureDetector detector)
MyGameActivity.mScaleFactor *= detector.getScaleFactor();

// Don't let the object get too small or too large.
MyGameActivity.mScaleFactor = Math.max(0.1f, Math.min(MyGameActivity.mScaleFactor, 1.0f));

return true;

at all on android <2.1. Is there a clever way to get around this using java reflection? I know how to test if a method exists via reflection, but can I test if a class exists? How can I have my

private ScaleGestureDetector mScaleDetector;

declared at the top of my class if the API can't even see the ScaleGestureDetector class?

It seems like I should be able to declare some sort of inner interface like:

public interface CustomScaleDetector
public void onScale(Object o);

And then somehow...try to extend ScaleGestureDetector depending on if reflection tells you that the class is accessible...

But I'm not really sure where to go from there. Any guidance or example code would be appreciated, let me know if it isn't clear what I'm asking.

Search for a packages by a particular author

Sometimes I get accustomed to a particular R package's design and want to search CRAN for all packages by that author (let's use Hadley Wickham for instance). How can I do such a search (I'd like to use R but this doesn't have to be the mode of search).

Using data from C# DataReceived thread in a parent class (NO UI, can't Invoke)

I have a class that needs to have properties updated with data from the C# serial DataReceived event.

I'm not trying to update a UI, but the only references I find about using the results of the DataReceived event (which runs on a different thread) say to use .Invoke to get the data into a UI control. My class is not associated with a UI so .Invoke is not available.

When the handler tries to change a property in the class, I get the dreaded error: "The calling thread cannot access this object because a different thread owns it."

What is process for getting the results into the parent thread?

Coding a function to copy a linked-list [C++]

I need to implement an auxilliary function, named copyList, having one parameter, a pointer to a ListNode. This function needs to return a pointer to the first node of a copy of original linked list. So, in other words, I need to code a function in C++ that takes a header node of a linked list and copies that entire linked list, returning a pointer to the new header node. I need help implementing this function and this is what I have right now.

Listnode *SortedList::copyList(Listnode *L) {

Listnode *current = L; //holds the current node

Listnode *copy = new Listnode;
copy->next = NULL;

//traverses the list
while (current != NULL) {
*(copy->student) = *(current->student);
*(copy->next) = *(current->next);

copy = copy->next;
current = current->next;
return copy;

Also, this is the Listnode structure I am working with:

struct Listnode {    
Student *student;
Listnode *next;

Note: another factor I am running into with this function is the idea of returning a pointer to a local variable.

How to get good performance when writing a list of integers from 1 to 10 million to a file?


I want a program that will write a sequence like,


to a file. What's the simplest code one can write, and get decent performance? My intuition is that there is some lack-of-buffering problem. My C code runs at 100 MB/s, whereas by reference the Linux command line utility dd runs at 9 GB/s 3 GB/s (sorry for the imprecision, see comments -- I'm more interested in the big picture orders-of-magnitude though).

One would think this would be a solved problem by now ... i.e. any modern compiler would make it immediate to write such programs that perform reasonably well ...

C code

#include <stdio.h>

int main(int argc, char **argv) {
int len = 10000000;
for (int a = 1; a <= len; a++) {
printf ("%d\n", a);
return 0;

I'm compiling with clang -O3. A performance skeleton which calls putchar('\n') 8 times gets comparable performance.

Haskell code

A naiive Haskell implementation runs at 13 MiB/sec, compiling with ghc -O2 -optc-O3 -optc-ffast-math -fllvm -fforce-recomp -funbox-strict-fields. (I haven't recompiled my libraries with -fllvm, perhaps I need to do that.) Code:

import Control.Monad
main = forM [1..10000000 :: Int] $ \j -> putStrLn (show j)

My best stab with Haskell runs even slower, at 17 MiB/sec. The problem is I can't find a good way to convert Vector's into ByteString's (perhaps there's a solution using iteratees?).

import qualified Data.Vector.Unboxed as V
import Data.Vector.Unboxed (Vector, Unbox, (!))

writeVector :: (Unbox a, Show a) => Vector a -> IO ()
writeVector v = V.mapM_ (System.IO.putStrLn . show) v

main = writeVector (V.generate 10000000 id)

It seems that writing ByteString's is fast, as demonstrated by this code, writing an equivalent number of characters,

import Data.ByteString.Char8 as B
main = B.putStrLn (B.replicate 76000000 '\n')

This gets 1.3 GB/s, which isn't as fast as dd, but obviously much better.

drawString with Rectangle border

I want to draw string using Graphics with Rectangle border outside the string.

This is what I already do:

public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
FontMetrics fontMetrics = g2d.getFontMetrics();
String str = "aString Test";

int width = fontMetrics.stringWidth(str);
int height = fontMetrics.getHeight();

int x = 100;
int y = 100;

// Draw String
g2d.drawString(str, x, y);
// Draw Rectangle Border based on the string length & width
g2d.drawRect(x - 2, y - height + 2, width + 4, height);

My problem is, I want to draw string with new line ("\n") with Rectangle border outside:

This is the code for the new line:

public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
FontMetrics fontMetrics = g2d.getFontMetrics();
String str = "aString\nTest";

int width = fontMetrics.stringWidth(str);
int height = fontMetrics.getHeight();

int x = 100;
int y = 100;

// Drawing string per line
for (String line : str.split("\n")) {
g2d.drawString(line, x, y += g.getFontMetrics().getHeight());

Can anyone help me for this problem? I appreciate your help & suggestion...

Database design advice in Rails, The Pizza, Topping and Order

Yes, its another database question with the pizza analogy.
The ones I've seen don't seem to click just right, so here goes.

I need to be able to order multiple pizzas with any number of toppings in a single order.
Its a basic shopping cart pattern, but the toppings are making it difficult to implement.

The base models are,

class Pizza < ActiveRecord::Base
has_and_belongs_to_many :orders
has_and_belongs_to_many :toppings

class Topping < ActiveRecord::Base
has_and_belongs_to_many :pizzas

Pizza and Topping tables serve as the holder for the information of pizza and topping types that can be ordered.

class OrdersPizzas < ActiveRecord::Base
belongs_to :order
belongs_to :pizza

class PizzasToppings < ActiveRecord::Base
belongs_to :topping
belongs_to :pizza

class Order < ActiveRecord::Base
has_and_belongs_to_many :pizzas


Some clarification, the database design is intended for a shopping app, so being able to setup a "menu" by an admin, and users being able to see the menu, and order from it is imperative.

The operation of this goes in two steps, first you need to make a menu by creating the Pizzas and toppings, and associating them, not all pizzas can have all the toppings.

A Cheese Pizza can have extra olives, and extra cheese as toppings

A Peperoni Pizza can have only extra cheese for toppings

Step two is actually placing the orders according to the entered data, thus all the many to manys.

Now the question is, after entering the data above, I want to place an order

Peperoni Pizza with extra cheese

Cheeze Pizza with extra olives

in a single order, how should it be designed?

All I can think of is to add a

class OrdersPizzasToppings < ActiveRecord::Base
belongs_to :orders_pizzas
belongs_to :topping

so I can distinguish which pizza has the toppings, but that does not look like the right way to go.

MVC SQL cyclical cascade paths

I'm building a simple code-first MVC 3 blog like application. My model has three tables, user, comment, and tutorial. The comment table has a FK for both user and tutorial. Tutorial has also a foreign key for user.

When I run the program I get the following error:

Introducing FOREIGN KEY constraint 'FK_Comments_Users_UserID' on table 'Comments' 
may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON
UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.

It seems like the problem is being caused by something called cascading deletes. Microsoft's solution to this is to have better DB design, But this DB seems to be about as simple as you can get.

I've found a few other posts (Entity Framework Code first - FOREIGN KEY constraint problem) which seem to address this issue by adding a the following code in my db context class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)

.HasMany(u => u.Comments)
.HasRequired(c => c.User)
.HasForeignKey(c => c.UserId)

Unfortunately, Visual Studio gets mad at the syntax at '.HasRequired' The actual error is "Error 1 'System.Data.Entity.ModelConfiguration.Configuration.ManyNavigationPropertyConfiguration' does not contain a definition for 'HasRequired' and no extension method 'HasRequired' accepting a first argument of type 'System.Data.Entity.ModelConfiguration.Configuration.ManyNavigationPropertyConfiguration' could be found (are you missing a using directive or an assembly reference?)"

It seems like there is something simple here that I am missing. How can I restructure my database better or how can I solve this cyclical redundancy problem?