Skip to main content

Posts

Showing posts from March 8, 2012

Zend_Gdata and OAuth

I successfully retrieved token key / secret after applying Google Hybrid Protocol (OpenID + OAuth). Then I'm looking into Zend documentation here: http://framework.zend.com/manual/en/zend.gdata.html ... and into Calendar API example here: http://code.google.com/googleapps/marketplace/tutorial_php.html#Integrate-OAuth They mention about AuthSub method supported by Zend_Gdata library (especially in Zend_Gdata_HttpClient class form what I can see). But I cannot figure out how to use my key/secret tokens retrieved by Hybrid method in order to access calendar feeds. Example mentioned above uses AuthSub authentication, while Google recommends to switch to OAuth if possible and where possible, instead of using AuthSub. Any ideas? Thanks.

Case-inconsistency of PHP file paths on Mac / MAMP?

I'm developing a PHP program on MAMP, and just realized the following screwy behavior: echo "<br/>PATH = ".dirname(__FILE__); include 'include.php'; include.php: <?php echo "<br/>PATH = ".dirname(__FILE__); ?> Result: PATH = /users/me/stuff/mamp_server/my_site (All lower case) PATH = /Users/me/Stuff/mamp_server/my_site (Mixed case) What is causing this inconsistent behavior, and how can I protect against it? (Note that I can't just convert everything to lowercase, because the application is destined for a Linux server, where file paths are case sensitive. ) Update: This problem exists for __FILE__ and __DIR__ . It looks like this might be a real problem with no work around... going to file a bug report unless I hear otherwise. Bug report: https://bugs.php.net/bug.php?id=60017 Update: And another note: If you're doing an absolute path include(...) on Mac, it requires the mixed case version.

Why does an infinitely recursive function in PHP cause a segfault?

A hypothetical question for you all to chew on... I recently answered another question on SO where a PHP script was segfaulting, and it reminded me of something I have always wondered, so let's see if anyone can shed any light on it. Consider the following: <?php function segfault ($i = 1) { echo "$i\n"; segfault($i + 1); } segfault(); ?> Obviously, this (useless) function loops infinitely. And eventually, will run out of memory because each call to the function executes before the previous one has finished. Sort of like a fork bomb without the forking. But... eventually, on POSIX platforms, the script will die with SIGSEGV (it also dies on Windows, but more gracefully - so far as my extremely limited low-level debugging skills can tell). The number of loops varies depending on the system configuration (memory allocated to PHP, 32bit/64bit, etc etc) and the OS but my real question is - why does it happen with a segfault? Is this simply how

Is en_UK an illegal locale?

So far I had always used 'en_UK' for British English. Today I got an error when using it with Zend Framework because the locale is not included in the long list of recognized locales. Here's just a short extract of that list: 'ee_GH' => true, 'ee_TG' => true, 'ee' => true, 'el_CY' => true, 'el_GR' => true, 'el' => true, 'en_AS' => true, 'en_AU' => true, 'en_BE' => true, 'en_BW' => true, 'en_BZ' => true, 'en_CA' => true, 'en_GB' => true, 'en_GU' => true, 'en_HK' => true, 'en_IE' => true, 'en_IN' => true, 'en_JM' => true, 'en_MH' => true, 'en_MP' => true, 'en_MT' => true, 'en_NA' => true, 'en_NZ' => true, 'en_PH' => true, 'en_PK' => true, 'en_SG' => true, 'en_TT' => true, &#

Bug or hack? $GLOBALS

$GLOBALS["items"] = array('one', 'two', 'three', 'four', 'five' ,'six', 'seven'); $alter = &$GLOBALS["items"]; // Comment this line foreach($GLOBALS["items"] as $item) { echo get_item_id(); } function get_item_id(){ var_dump(key($GLOBALS["items"])); } Check output of this code, with commented and uncommented second line. My result(PHP 5.3.0). With second line int(1) int(2) int(3) int(4) int(5) int(6) NULL Without second line: int(1) int(1) int(1) int(1) int(1) int(1) int(1) Why so strange result?

Update whole page on Ajax request

I have an AJAX request that can have two possible outcomes: The server responds with a message which I should place in a <div> The server responds with an HTML page, in this case I need to substitute current page with a new one and change the address (the client knows the address before a request). What would be the solution if I have the AJAX request that needs to handle both of these cases? url = "http://example.com" ajax.request(callback) function callback(response) { if (case2(response)) { history.pushState({}, "New page", url); document.innerHTML = response } else { updateDiv(response) } } I'm interested in a correct way to implement the first branch, or if the server can somehow compose a headers that will make browser to handle a response as a usual HTTP response and update a page location and content, something like redirect with given content. I understand that the server can retu

cURL equivalent in JAVA

I am tasked with writing an authentication component for an open source JAVA app. We have an in-house authentication widget that uses https. I have some example php code that accesses the widget which uses cURL to handle the transfer. My question is whether or not there is a port of cURL to JAVA, or better yet, what base package will get me close enough to handle the task? Update : This is in a nutshell, the code I would like to replicate in JAVA: $cp = curl_init(); $my_url = "https://" . AUTH_SERVER . "/auth/authenticate.asp?pt1=$uname&pt2=$pass&pt4=full"; curl_setopt($cp, CURLOPT_URL, $my_url); curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($cp); curl_close($cp); Heath , I think you're on the right track, I think I'm going to end up using HttpsURLConnection and then picking out what I need from the response.

PHP array comparison algorithm

While trying to simulate a bit of PHP behaviour I stumbled across this: $a=array(0 => 1, 'test' => 2); $b=array('test' => 3, 0 => 1); var_dump($a==$b, $a>$b, $b>$a); According to the output from var_dump $b is bigger than $a . In the PHP manual there is a Transcription of standard array comparison which states that the values of the arrays are compared one by one and if a key from the first array is missing in the second array, the arrays are uncomparable. So far so good. But if I try this (change in the first element of $a only): $a=array(0 => 2, 'test' => 2); $b=array('test' => 3, 0 => 1); var_dump($a==$b, $a>$b, $b>$a); All three comparison results are false . This looks like "uncomparable" to me (because the > result is the same as the < result, while the arrays are not == either, which makes no sense) but this does not fit the transcription from the PHP manual. Both k

shift bits vs multiply in PHP

I have the following code: <?php $start = 1; $timestart = microtime(1); for ($i = 0; $i < 1000000; $i++) { $result1 = $start * 4; } echo "\n"; echo microtime(1) - $timestart; echo "\n"; $timestart = microtime(1); for ($i = 0; $i < 1000000; $i++) { $result2 = $start << 2; } echo "\n"; echo microtime(1) - $timestart; echo "\n"; This outputs: 0.14027094841003 0.12061500549316 I found on the Internet a Google interview question (which I wanted to apply for a developer, but I realize I can't), and one of the questions asked what the fastest way was to multiply a number. My first thought was to use the * sign, so I tested it. My question is, why is shifting bits faster than multiplication?

How to check php syntax of multiple files at once?

i have a svn server that i checkout the repository in my computer the main repositiry is about 2k files 3rd party generic code classes custom classes i have made changes to lots of files (mainly php) and i want to make sure they are all valid before i commit svn commit -m "i fix the bug #293" how can i check all the files at once to make sure they are valid and no php errors so i dont have to manually check all these files thanks

php cronjob interruption

i have a cronjob in php that calculates few business rules (eg: net rev, gross rev, estimated rev, etc... using standard deviation & other math algo) this cronjob calls multiple cron calls 3 php scripts using exec for each calls i start a process in background and tell the system that jobs x started. eg: here's my logic start main cron start - message cron sub 1 start - message run cron sub 1 cron sub 1 end - message wait until cron sub 1 stop process stuff cron sub 2 start - message run background cron sub 2 // this will automaticaly send a message when this jobs end cron sub 3 start - message run background cron sub 3 // this will automaticaly send a message when this jobs end main cron end - message end what i need to fix is this if someone runs the job manually and cancel it (ctrl+c) or something bad happen in the cron (fatal error or cannot connect to db) or anything else (like not enough memory) i want to stop the cronjob and tell what h

What is wrong with my code - circularly sorted array does not show any results

I had an interview today and the person asked me this question: How do you find easily an item in a circularly sorted array Since I didn't know the answer, I tried to find a solution. Here's what I have: Thanks <?php function searchincircularsorterlist($a, $len, $num) { $start=0; $end=$len-1; $mid = 0; while($start<$end) { $mid=$start+$end/2; if ($num == $a[$mid]) { return $num; } if($num<$a[$mid]) { if($num<$a[$start] && $a[$start]<=$a[$start+1]) $start=$mid++; else $end=$mid--; } else { if($num>$a[$end] && $a[$end-1]<=$a[end]) $end=$mid--; else $start=$mid++; } } if ($start == $end && $num == $a[$start]) { return $num; } return -1; } $array = array(7,8,9,0,1,2,3,4,5,6); var_dump(searchincircularsorterlist($array,sizeof(

Parsing Domain From URL In PHP

I need to build a function which parses the domain from a URL. So, with http://google.com/dhasjkdas/sadsdds/sdda/sdads.html or http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html , it should return google.com ; with http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html , it should return google.co.uk .

Ways to improve performance consistency

In the following example, one thread is sending "messages" via a ByteBuffer which is the consumer is taking. The best performance is very good but its not consistent. public class Main { public static void main(String... args) throws IOException { for (int i = 0; i < 10; i++) doTest(); } public static void doTest() { final ByteBuffer writeBuffer = ByteBuffer.allocateDirect(64 * 1024); final ByteBuffer readBuffer = writeBuffer.slice(); final AtomicInteger readCount = new PaddedAtomicInteger(); final AtomicInteger writeCount = new PaddedAtomicInteger(); for(int i=0;i<3;i++) performTiming(writeBuffer, readBuffer, readCount, writeCount); System.out.println(); } private static void performTiming(ByteBuffer writeBuffer, final ByteBuffer readBuffer, final AtomicInteger readCount, final AtomicInteger writeCount) { writeBuffer.clear(); readBuffer.clear();

How can I check website security for free?

I've heard that there are some free applications that will check the vulnerability of a PHP website, but I don't know what to use. I'd like a free program (preferably with a GUI) for Windows that will analyze my site an give me a report. Anyone know of a solution?

What should every PHP programmer know?

I would like to be a PHP/MySQL programmer What are the technologies that I must know? Like: Frameworks IDEs Template Engines Ajax and CSS Frameworks Please tell me the minimum requirements that I must know, and tell me your favourite things in the previous list? Thanks

what is j2ee/jee?

OK stupid question but... I realize that literally it translates to java 2 enterprise edition. What I'm asking is what does this really mean? when a company requires j2ee experience what are they really asking for? experience with ejb's? experience with java web apps? I suspect that this means something different to different people and the definition is subjective, so please try to upvote rather than reposting something already in another answer.

How to make a Java thread wait for another thread"s output?

I'm making a Java application with an application-logic-thread and a database-access-thread. Both of them persist for the entire lifetime of the application. However, I need to make sure that the app thread waits until the db thread is ready (currently determined by calling dbthread.isReady() ). I wouldn't mind if app thread blocked until the db thread was ready. Thread.join() doesn't look like a solution - the db thread only exits at app shutdown. while (!dbthread.isReady()) {} kind of works, but the empty loop consumes a lot of processor cycles. Any other ideas? Thanks.

Can anyone recommend a simple Java web-app framework?

I'm trying to get started on what I'm hoping will be a relatively quick web application in Java, yet most of the frameworks I've tried (Apache Wicket, Liftweb) require so much set-up, configuration, and trying to wrap my head around Maven while getting the whole thing to play nice with Eclipse, that I spent the whole weekend just trying to get to the point where I write my first line of code! Can anyone recommend a simple Java webapp framework that doesn't involve Maven, hideously complicated directory structures, or countless XML files that must be manually edited?

differences between 2 JUnit Assert classes

I've noticed that the JUnit framework contains 2 Assert classes (in different packages, obviously) and the methods on each appear to be very similar. Can anybody explain why this is? The classes I'm referring to are: junit.framework.Assert and org.junit.Assert . Cheers, Don

How to return multiple objects from a Java method?

I want to return two objects from a Java method and was wondering what could be a good way of doing so? The possible ways I can think of are: return a HashMap (since the two Objects are related) or return an ArrayList of Object objects. To be more precise, the two objects I want to return are (a) List of objects and (b) comma separated names of the same. I want to return these two Objects from one method because I dont want to iterate through the list of objects to get the comma separated names (which I can do in the same loop in this method). Somehow, returning a HashMap does not look a very elegant way of doing so.

Find Java classes implementing an interface

Some time ago, I came across a piece of code, that used some piece of standard Java functionality to locate the classes that implemented a given interface. I know the functions were hidden in some non-logical place, but they could be used for other classes as the package name implied. Back then I did not need it, so I forgot about it, but now I do, and I can't seem to find the functions again. Where can these functions be found? Edit: I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.

How can you organize the code for a game to fit the MVC pattern?

I'm a freshman in college going for my computer science degree... I've programmed plenty the last several years but just lately I've been getting more into theoretical ideas about organizing code, design patterns, differences in languages, etc. I have a Java class, so I've dropped my C++ research/development and moved into Java and JOGL (Java OpenGL). It's wonderful! But that's beside the point. I want to make a small role-playing game, but this question really applies to any sort of game. How do you organize the game objects in a way that is structured, like the Model-View-Controller pattern? It looks to be an amazing pattern, very widely used and makes a lot of sense, but I'm having trouble figuring out how to implement it. For instance, I need to keep track of a GL object for drawing to the screen. I have to have classes that implement MouseListener, MouseMotionListener, MouseWheelListener, and KeyListener (or one class, an all-in-one input manage

Is System.nanoTime() completely useless?

As documented here , on x86 systems. Java's System.nanoTime() returns the time value using a cpu specific counter. Now consider the following case I use to measure time of a call - long time1= System.nanotime(); foo(); long time2 = System.nanotime(); long timeSpent = time2-time1; Now in a multi core system, it could be that after measuring time1, the thread is scheduled to a different processor whose counter is less than that of the previous cpu. Thus we could get a value in time2 which is less than time1. Thus we would get a negative value in timeSpent. Considering this case, isnt it that System.nanotime is pretty much useless for now? Edit: I know that changing the system time doesnt affect nanotime. that is not the problem i describe above. The problem is that each cpu will keep a different counter since it was turned on. This counter can be lower on the 2nd cpu compared to the first cpu. Since the thread can be scheduled by the OS to the 2nd cpu after getting time1, t

Why doesn"t Sun do a C# to Java byte code compiler?

We Want to Run Our C# Code on the JVM My company has a large C# code base. Well over half of this code is our core engine for creating, reading, modifying, calculating and writing Excel workbooks. We frequently get questions from customers and potential customers asking whether we are going to build a Java version of our engine - many of them are not at all interested in the UI. We even have a few customers who have taken the trouble to use our .NET library from their Java applications. So, we would like to build a Java version of our core engine, ideally without maintaining a separate Java source code base. Eric Sink described this problem very well. I am in a similar position except for the fact that our software license includes royalty free deployment, making Eric's choice of Mainsoft a nonstarter for us. I have been Googling the likes of "c# to jvm" every few months for several years now with no joy. Having spent ~7 years developing similar software for J

Uses for the Java Void Reference Type?

There is a Java Void -- uppercase V-- reference type . The only situation I have ever seen it used is to parameterize Callable s final Callable<Void> callable = new Callable<Void>() { public Void call() { foobar(); return null; } }; Are there any other uses for the Java Void reference type? Can it ever be assigned anything other than null ? If yes, do you have examples?

Howto embed Tomcat 6?

I'm currently running my webapps on Tomcat 6 in production, and would like to evaluate running Tomcat in embedded mode. Is there a good tutorial or other resource besides what's in the api documentation ?

Android download binary file problems

I am having problems downloading a binary file (video) in my app from the internet. In Quicktime, If I download it directly it works fine but through my app somehow it get's messed up (even though they look exactly the same in a text editor). Here is a example: URL u = new URL("http://www.path.to/a.mp4?video"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); FileOutputStream f = new FileOutputStream(new File(root,"Video.mp4")); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; while ( (len1 = in.read(buffer)) > 0 ) { f.write(buffer); } f.close();

Changing the current working directory in Java?

How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case. I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call System.setProperty( "user.dir", "/path/to/dir" ) , but as far as I can figure out, calling that line just silently fails and does nothing. I would understand if Java didn't allow you to do this, if it weren't for the fact that it allows you to get the current working directory, and even allows you to open files using relative file paths....

Why is Java"s Iterator not an Iterable?

Why does the Iterator interface not extend extend Iterable ? The iterator() method could simply return ' this '. Is it on purpose or just an oversight of Java's designers? It would be convenient to be able to use a for-each loop with iterators like this: for(Object o : someContainer.listSomObjects()) { .... } where listSomeObject returns an iterator.

BoxLayout can"t be shared error

I have this Java JFrame class, in which I want to use a boxlayout, but I get an error saying java.awt.AWTError: BoxLayout can't be shared . I've seen others with this problem, but they solved it by creating the boxlayout on the contentpane, but that is what I'm doing here. Here's my code: class edit_dialog extends javax.swing.JFrame{ javax.swing.JTextField title = new javax.swing.JTextField(); public edit_dialog(){ setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE); setTitle("New entity"); getContentPane().setLayout( new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS)); add(title); pack(); setVisible(true); } }

Why java people frequently consume exception silently?

I never did any serious Java coding before, but I learned the syntax, libraries, and concepts based on my existing skills (Delphi & C#). One thing I hardly understand is that I've seen soo much code that silently consume exceptions after "printStackTrace" like this: public void process() { try { System.out.println("test"); } catch(Exception e) { e.printStackTrace(); } } There is similar code like this one in almost every Java article & project I ran into. Based on my knowledge this is very bad. The exception should almost always be forwarded to the outer context like this: public void process() { try { System.out.println("test"); } catch(Exception e) { e.printStackTrace(); throw new AssertionError(e); } } Most of the time the exception should end up being handled at the outermost loop which belongs to the underlying framework (Jav

Java: Why charset names are not constants?

Charset issues are confusing and complicated by themselves, but on top of that you have to remember exact names of your charsets. Is it "utf8" ? Or "utf-8" ? Or maybe "UTF-8" ? When searching internet for code samples you will see all of the above. Why not just make them named constants and use Charset.UTF8 ?

Is it bad practice to make a setter return "this&rdquo;?

Is it a good or bad idea to make setters in java return "this"? public Employee setName(String name){ this.name = name; return this; } This pattern can be useful because then you can chain setters like this: list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!")); instead of this: Employee e = new Employee(); e.setName("Jack Sparrow"); ...and so on... list.add(e); ...but it sort of goes against standard convention. I suppose it might be worthwhile just because it can make that setter do something else useful. I've seen this pattern used some places (e.g. JMock, JPA), but it seems uncommon, and only generally used for very well defined APIs where this pattern is used everywhere. Update: What I've described is obviously valid, but what I am really looking for is some thoughts on whether this is generally acceptable, and if there are any pitfalls or related best practices. I know about the Builder pattern

toString() in Java

A lead developer on my project has taken to referring to the project's toString() implementations as "pure cruft" and is looking to remove them from the code base. I've said that doing so would mean that any clients wishing to display the objects would have to write their own code to convert the object to string, but that was answered with "yes they would". Now specifically, the objects in this system are graphic elements like rectangles, circles, etc and the current representation is to display x, y, scale, bounds, etc... So, where does the crowd lie? When should you and when shouldn't you implement toString?

Eclipse - no Java (JRE) / (JDK) &hellip; no virtual machine

I am trying to get Eclipse Galileo to re-run on my computer - i have run it before with no problems but now i keep getting this error: A java Runtime Environment (JRE) or Java Development kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations: C:\eclipse\jre\javaw.exe javaw.exe in your current PATH I've just done a fresh install of both the JDK and the SDK I have Windows 7 (x64) what's up with this? / how do i fix it->? UPDATE-> i can't run any of the ipconfig / tracert / ping

Android: How to fire onListItemClick in Listactivity with buttons in list?

I have a simple ListActivity that uses a custom ListAdapter to generate the views in the list. Normally the ListAdapter would just fill the views with TextViews, but now I want to put a button there as well. It is my understanding and experience however that putting a focusable view in the list item prevents the firing of onListItemClick() in the ListActivity when the list item is clicked. The button still functions normally within the list item, but when something besides the button is pressed, I want onListItemClick to be triggered. How can I make this work?

Java Urban Myths

Along the line of C++ Urban Myths and Perl Myths : What are the Java Urban Myths? That is, the ideas and conceptions about Java that are common but have no actual roots in reality . As a Java programmer, what ideas held by your fellow Java programmers have you had to disprove so often that you've come to believe they all learned at the feet of the same drunk old story-teller? Ideally, you would express these myths in a single sentence, and include an explanation of why they are false.