Friday, April 30, 2010

car and cdr in Scheme are driving me crazy ...

Programmer Question

Hi Im facing a problem with the car and cdr functions



for example:



first I defined a list called it x



(define x (a (bc) d ( (ef) g ) ))


so x now is equal to (a (bc) d ( (ef) g ) )



now for example I need to get the g from this list using only car and cdr
(!! noshortcuts as caddr cddr !!) the correct answer is:



(car(cdr(car(cdr(cdr(cdr x))))))


BUT how ? :-( I work according to the rules (the car gives the head of list and cdr gives the tail)



and instead of getting the answer above I keep reaching wrong answers.
Can any one help me in understanding this ... give me step or a way to solve it step by step



Thanks in advance. I'm really sick of Scheme.



Find the answer here

How to delete specific record from Google Datastore (in Java) ?

Programmer Question

I have some records in datastore, I want to delete a specific record from the table. for example in SQL , we use delete * from table1 where name ="mike" what is the equivalent code in java (I m using Eclipse with Google appengine API plugin)? or any other method to do that?



Find the answer here

Determine week number based on starting date

Programmer Question

I need help to create a function to determine the week number based on these 2 parameters:




  1. Starting date

  2. Specified date



For example, if I specify April 7, 2010 as the starting date & passed April 20, 2010 as the date to lookup, I would like the function to return WEEK 2. Another example, if I set March 6, 2010 as starting date and looked up April 5, 2010 then it should return WEEK 6.



I appreciate your time and help.



=================



UPDATE



For instance:



Starting date: 3/6 - week1
Lookup date: 4/5



Week 2 starts from Mar 7-13.
Week 3 (3/14-3/20).
Week 4 (3/21-3/27). Week 5 (3/28-4/3).
So 4/5 falls under Week 6.



An idea is to use the Sunday of the starting date as the NEW* starting date. So instead of looking up 3/6, the function will use 2/28 as the starting date.



Find the answer here

Producing an view of a text's revision history in Python

Programmer Question

I have two versions of a piece of text and I want to produce an HTML view of its revision similar to what Google Docs or Stack Overflow displays. I need to do this in Python. I don't know what this technique is called but I assume that it has a name and hopefully there is a Python library that can do it.



Version 1:




William Henry "Bill" Gates III (born
October 28, 1955)[2] is an American
business magnate, philanthropist, and
chairman[3] of Microsoft, the software
company he founded with Paul Allen.




Version 2:




William Henry "Bill" Gates III (born
October 28, 1955)[2] is a business
magnate, philanthropist, and
chairman[3] of Microsoft, the software
company he founded with Paul Allen.
He is American.




The desired output:




William Henry "Bill" Gates III (born
October 28, 1955)[2] is an American business
magnate, philanthropist, and
chairman[3] of Microsoft, the software
company he founded with Paul Allen.
He is American.




Using the diff command doesn't work because it tells me which lines are different but not which columns/words are different.



$ echo 'William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen.' > oldfile
$ echo 'William Henry "Bill" Gates III (born October 28, 1955)[2] is a business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American.' > newfile
$ diff -u oldfile newfile
--- oldfile 2010-04-30 13:32:43.000000000 -0700
+++ newfile 2010-04-30 13:33:09.000000000 -0700
@@ -1 +1 @@
-William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen.
+William Henry "Bill" Gates III (born October 28, 1955)[2] is a business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American.' > oldfile


Find the answer here

Syntax for specializing function templates

Programmer Question

Is there a difference between the following approaches?



// approach 1
namespace std
{
template<>
void swap<Foo>(Foo& x, Foo& y) // note the <Foo>
{
x.swap(y);
}
}

// approach 2
namespace std
{
template<>
void swap(Foo& x, Foo& y)
{
x.swap(y);
}
}


I stumpled upon this when I tried to specialize swap for my own string type and noticed that swap<::string> doesn't work, but for a completely different reason :)



Find the answer here

Tuesday, April 27, 2010

Can python code (say if I used djangno) be obfuscated to the same 'level' as c#/java?

Programmer Question

If I obfuscated python code, would it provide the same level of 'security' as c#/java obfuscating?



i.e it makes things a little hard, but really you can still reverse engineer if you really wanted to, its just a bit cryptic.



Find the answer here

The method split(String) is undefined for the type String

Programmer Question

I am using Pulse - the Plugin Manager for Eclipse and installed. I have the Eclipse 3.5 for mobile development(Pulsar) profile with a couple other profiles.



I realized that the split() method called on a string from code such as below:



String data = "one, two, three, four";
data.split(",");


generates the error: "The method split(String) is undefined for the type String". I am aware that the split() method did not exist before Java's JRE 1.4 and perhaps could be the cause of the problem.
The problem is I don't think I have jre/sdk versions installed. Perhaps there's one in-built with the Pulsar profile and needs editing - but I couldn't tell what settings (and where) needs tweaking. I have checked Windows>Preferences>Java>Installed JREs and it's set to >= jre1.4. Please help thanks.



Find the answer here

a design to avoid circular reference in this scenario

Programmer Question

Here is our dependency tree: BigApp -> Child Apps -> Libraries



ALL of our components are HEAVILY using one of the Libraries as above ( LibA).
But it has a ‘few’ public methods that require classes from ‘higher-level’ assemblies and we want to avoid CIRCULAR references.
What do you propose as a good design for this?



Find the answer here

What's the coolest hack you've seen or done?

Programmer Question

As programmers, we've all put together a really cool program or pieced together some hardware in an interesting way to solve a problem. Today I was thinking about those hacks and how some of them are deprecated by modern technology (for example, you no longer need to hack your Tivo to add a network port). In the software world, we take things like drag-and-drop on a web page for granted now, but not too long ago that was a pretty exciting hack as well.



One of the neatest hardware hacks I've seen was done by a former coworker at a telecom company years ago. He had a small portable television in his office and he would watch it all day long while working. To get away with it, he wired a switch to the on/off that was activated via his foot under his desk.



What's the coolest hardware or software hack you've personally seen or done? What hack are you working on right now?



Find the answer here

going to build a php MVC, what naming conventions do i need to be aware of?

Programmer Question

I'm pretty new to OO PHP, however i get how it all works and am ready to start building an MVC for a big site i'm working on. I know it isnt necessary written that you must do it like this but there's gotta be some normal practises....



class names - camelcase? underscores?



class files - same as class?



url/post/get controll name - router.php?



any other things i should be aware of before i embark?



Find the answer here

Monday, April 26, 2010

How does jdbc work

Programmer Question

can anyone tell me How does jdbc work? How it manages to communicate with a DBMS? since DBMS may be written with some other programming language.



Find the answer here

Pass certificate to j2me

Programmer Question

I created a certificate on apache server.
x.509 public key certificate RSA created using the keytool



I need to pass this to a J2me app, via http. So the J2me app can encrypt data



How do I do this.



Find the answer here

Help with rendering the Mandelbrot set in Java

Programmer Question

I wrote an implementation of the Mandelbrot set in Java using a JComponent but I'm getting strange results when I render it. Besides that everything compiles right. I'm just not for sure what I'm doing wrong with it. Any code review also would be appreciated.



My source is posted on pastebin since it would take up too much room here:



JMandelbrot.java
Mandelbrat.java



Find the answer here

Linux binary built for 2.0 kernel wouldn't execute on 2.6.x kernel.

Programmer Question

I was installing a binary Linux application on Ubuntu 9.10 x86_64. The app shipped with an old version of gzip (1.2.4), that was compiled for a much older kernel:



$ file gzip 
gzip: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.0.0, stripped


I wasn't able to execute this program. If I tried, this happened:



$ ./gzip
-bash: ./gzip: No such file or directory


ldd was similarly unhappy with this binary:



$ ldd gzip
not a dynamic executable


This isn't a showstopper for me, since my installation has a working version of gzip I can use. But I'm curious: What's the most likely source of this problem? A corrupted file? Or a binary incompatibility due to being built for a much older {kernel,libc,...}?



Find the answer here

How to use mySql DB from C# on shared hosting?

Programmer Question

Hi, i bought a web domain with some web space. They support only mySQL DB, how do i access the my SQL DB on my asp.net application? is there is way to access it through .net base classes without installing third party drivers?



Find the answer here

Sunday, April 25, 2010

Boost Shared Pointer: Simultaneous Read Access Across Multiple Threads

Programmer Question

I have a thread A which allocates memory and assigns it to a shared pointer. Then this thread spawns 3 other threads X, Y and Z and passes a copy of the shared pointer to each. When X, Y and Z go out of scope, the memory is freed. But is there a possibility that 2 threads X, Y go out of scope at the exact same point in time and there is a race condition on reference count so instead of decrementing it by 2, it only gets decremented once. So, now the reference count newer drops to 0, so there is a memory leak. Note that, X, Y and Z are only reading the memory. Not writing or resetting the shared pointer. To cut a long story short, can there be a race condition on the reference count and can that lead to memory leaks?



Find the answer here

syntax for generating an objectForKey from an array

Programmer Question

I'm having success when I use this code to get a string from an array called "fileList":



cell.timeBeganLabel.text = [[[self.fileList objectAtIndex:[indexPath row]] lastPathComponent] stringByDeletingPathExtension];


so I expected the same code to generate the same string as a key for me in this:



NSDictionary *stats = [thisRecordingsStats objectForKey:[[[self.fileList objectAtIndex:[indexPath row]] lastPathComponent] stringByDeletingPathExtension]];
cell.durationLabel.text = [stats objectForKey:@"duration"];


or this:



NSDictionary *stats = [thisRecordingsStats objectForKey:@"%@",[[[self.fileList objectAtIndex:[indexPath row]] lastPathComponent] stringByDeletingPathExtension]];


Both build without error, and the log shows my data is there: but I'm getting a blank UILabel.

Have I not written the dynamic key generator correctly?



Find the answer here

Declaring variables with this or var?

Programmer Question

What is the difference between declaring a variable with this or var ?



var foo = 'bar'


or



this.foo = 'bar'


When do you use this and when var?



Find the answer here

jQuery click event not working when mouse moves from one div to another with button held down

Programmer Question

I've made a page that uses jQuery to allow you to place <div>s on the page based on your mouse coordinates when you click.



The page



And here's the javascript:



$('document').ready(function() {
$("#canvas").click(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
$(document.createElement('div')).css({'left':x + 'px', 'top':y + 'px'}).addClass('tile').appendTo('#canvas');
});
});


I've found that if you mousedown in the div#canvas and mouseup with your pointer over a placed <div> (or vice versa) then a new <div> doesn't get placed. Why is this?



EDIT:



Ok, so the problem is that the mouse-up and mouse-down events are registering in different elements so it doesn't make a click event. So how do I get my mouse-up part of the click ignore the div.tile elements (the pink rectangles) and register in the div#canvas element to create the click event?



Find the answer here

Monad equivalent in Ruby

Programmer Question

What would an equivalent construct of a monad be in Ruby?



Find the answer here

Saturday, April 24, 2010

Is this the correct syntax for 'array_unique()' in PHP?

Programmer Question

I want to get rid of duplicates in my array but I'm still printing duplicates with this:



$getuser = ltrim($top10['url'], " users/" );  //trim url to get user id
$array[$i++] = $getuser;
$dirty = $array;
$clean = array_unique($dirty);
print_r($clean)."<br />";


Input print_r($array)



Array ( [0] => 33 [1] => 3 [2] => 29 [3] => 3104 ) Array ( [0] => 156686 [1] => 5 [2] => 3104 [3] => 1 ) Array ( [0] => 2 [1] => 115023 [2] => 185367 [3] => 180694 ) Array ( [0] => 2 [1] => 5 [2] => 3104 [3] => 139403 ) Array ( [0] => 3110 [1] => 2723 [2] => 8087 [3] => 97410 ) Array ( [0] => 1925 [1] => 60 [2] => 18995 [3] => 2940 ) Array ( [0] => 103205 [1] => 111503 [2] => 2 [3] => 128715 ) Array ( [0] => 3 [1] => 119266 [2] => 4 [3] => 3104 ) Array ( [0] => 32565 [1] => 2743 [2] => 148584 [3] => 3505 ) Array ( [0] => 35282 [1] => 99136 [2] => 54167 [3] => 5326 )


Output print_r($clean);



Array ( [0] => 33 [1] => 3 [2] => 29 [3] => 3104 ) Array ( [0] => 156686 [1] => 5 [2] => 3104 [3] => 1 ) Array ( [0] => 2 [1] => 115023 [2] => 185367 [3] => 180694 ) Array ( [0] => 2 [1] => 5 [2] => 3104 [3] => 139403 ) Array ( [0] => 3110 [1] => 2723 [2] => 8087 [3] => 97410 ) Array ( [0] => 1925 [1] => 60 [2] => 18995 [3] => 2940 ) Array ( [0] => 103205 [1] => 111503 [2] => 2 [3] => 128715 ) Array ( [0] => 3 [1] => 119266 [2] => 4 [3] => 3104 ) Array ( [0] => 32565 [1] => 2743 [2] => 148584 [3] => 3505 ) Array ( [0] => 35282 [1] => 99136 [2] => 54167 [3] => 5326 )


Find the answer here

In SQL, a Join is actually an Intersection? And it is also a linkage or a "Sideway Union"?

Programmer Question

I always thought of a Join in SQL as some kind of linkage between two tables.



For example,



select e.name, d.name from employees e, departments d 
where employees.deptID = departments.deptID


In this case, it is linking two tables, to show each employee with a department name instead of a department ID. And kind of like a "linkage" or "Union" sideway".



But, after learning about inner join vs outer join, it shows that a Join (Inner join) is actually an intersection.



For example, when one table has the ID 1, 2, 7, 8, while another table has the ID 7 and 8 only, the way we get the intersection is:



select * from t1, t2 where t1.ID = t2.ID


to get the two records of "7 and 8". So it is actually an intersection.



So we have the "Intersection" of 2 tables. Compare this with the "Union" operation on 2 tables. Can a Join be thought of as an "Intersection"? But what about the "linking" or "sideway union" aspect of it?



Find the answer here

How to Configure SSL over Database in Spring?

Programmer Question

Hi,



I want to add SSL security in the Database layer. I am using Struts2.1.6, Spring 2.5, JBOSS 5.0 and Informix 11.5. Any idea how to do this?



I have researched through a lot on the internet but could not find any solution.



Please suggest!



Here is my datasource and entity manager beans which is working perfect without SSL:





<bean id="entityManagerFactory"  
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="INFORMIX" />
<property name="showSql" value="true" />

</bean>
</property>
</bean>

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.informix.jdbc.IfxDriver" />
<property name="url"
value="jdbc:informix-sqli://SERVER_NAME:9088/DB_NAME:INFORMIXSERVER=SERVER_NAME;DELIMIDENT=y;" />
<property name="username" value="username" />
<property name="password" value="password" />
<property name="minIdle" value="2" />
</bean>

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" lazy-init="false">
<property name="targetObject" ref="dataSource" />
<property name="targetMethod" value="addConnectionProperty" />
<property name="arguments">
<list>
<value>characterEncoding</value>
<value>UTF-8</value>
</list>
</property>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype">
<property name="dataSource" ref="dataSource" />
</bean>


<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />


Find the answer here

How to define a ternary operator in Scala which preserves leading tokens?

Programmer Question

I'm writing a code generator which produces Scala output.



I need to emulate a ternary operator in such a way that the tokens leading up to '?' remain intact.



e.g. convert the expression c ? p : q to c something. The simple if(c) p else q fails my criteria, as it requires putting if( before c.



My first attempt (still using c/p/q as above) is




c match { case(true) => p; case _ => q }


another option I found was:




class ternary(val g: Boolean => Any) { def |: (b:Boolean) = g(b) }

implicit def autoTernary (g: Boolean => Any): ternary = new ternary(g)


which allows me to write:




c |: { b: Boolean => if(b) p else q }


I like the overall look of the second option, but is there a way to make it less verbose?



Thanks



Find the answer here

Can I transform this asynchronous java network API into a monadic representation (or something else idiomatic)?

Programmer Question

I've been given a java api for connecting to and communicating over a proprietary bus using a callback based style. I'm currently implementing a proof-of-concept application in scala, and I'm trying to work out how I might produce a slightly more idiomatic scala interface.



A typical (simplified) application might look something like this in Java:



    DataType type = new DataType();
BusConnector con = new BusConnector();
con.waitForData(type.getClass()).addListener(new IListener<DataType>() {
public void onEvent(DataType t) {
//some stuff happens in here, and then we need some more data
con.waitForData(anotherType.getClass()).addListener(new IListener<anotherType>() {
public void onEvent(anotherType t) {
//we do more stuff in here, and so on
}
});
}
});

//now we've got the behaviours set up we call
con.start();


In scala I can obviously define an implicit conversion from (T => Unit) into an IListener, which certainly makes things a bit simpler to read:



implicit def func2Ilistener[T](f: (T => Unit)) : IListener[T] = new IListener[T]{
def onEvent(t:T) = f
}

val con = new BusConnector
con.waitForData(DataType.getClass).addListener( (d:DataType) => {
//some stuff, then another wait for stuff
con.waitForData(OtherType.getClass).addListener( (o:OtherType) => {
//etc
})
})


Looking at this reminded me of both scalaz promises and f# async workflows.



My question is this:



Can I convert this into either a for comprehension or something similarly idiomatic (I feel like this should map to actors reasonably well too)



Ideally I'd like to see something like:



for(
d <- con.waitForData(DataType.getClass);
val _ = doSomethingWith(d);
o <- con.waitForData(OtherType.getClass)
//etc
)


Find the answer here

Friday, April 23, 2010

Find Tables in PDF's

Programmer Question

Hello,



Are there any tools or tricks how to automatically extract tables from pdfs. Are there any C# libraries that could do that? Or do you maybe know other methods how this could be handled?



Thank you very much



Find the answer here

Netbeans configuration problem

Programmer Question

I am using Netbeans 6.8



The problem is that the projects explorer (that displays all the projects and their contents) displays each package as a node. For instance, if there is package hierarchy like this;




  • com.mycompany.myproject.package1.package1.1



then it displays 5 nodes for the five packages which is very disturbing while development.



Is there any way by which I can configure it(Netbeans) so that it groups all the subpackages of a package under one node and displays the subpackages only when I expand the package node?



Find the answer here

Windows XP Rejecting Digital Signature

Programmer Question

I don't want to see unsigned driver warnings while installing a driver, so I'm trying to digitally sign a driver using signtool, inf2cat, and a Software Publishing Certificate. Vista x64 requires the drivers to be digitally signed or it flat out rejects them, but I have managed to get Vista x64 to accept the driver, so I know I'm doing the process correctly.



However, I repeat the process for the Windows XP x86 driver. inf2cat and signtool both return successful results, signtool verifies the digital signatures, right-click -> properties on the file verifies the digital signature too.



However, when I go to load the driver in Windows XP, it still prompts me with an unsigned driver warning. Why does XP consider the file unsigned, but Vista does not?



Find the answer here

FLex MouseEvent doesn't fire when Mouse stays over element

Programmer Question

Hi, i'm trying to make a scrollable box, when a mouse enters and STAYS on "wrapper"'s area, "pubsBox" moves 10 pixels to the left.



<mx:Canvas id="wrapper" height="80" width="750">
<mx:HBox id="pubsBox" horizontalGap="10" height="80" width="100%" />
</mx:Canvas>


My problem is that I'm not sure how to make the MouseEvent.MOUSE_OVER work, to recognize that the mouse is still ON the area and so pubsBox should continue to move 10 pixels to the left every second.



I understand that i have to use a Timer, but what I'm concerned about is the fact that I can't get Flex to recognize that the mouse is still OVER "wrapper" and continue firing the event. Any ideas?



Find the answer here

Thinking Sphinx - sorting by a string attribute gets out of sync when changes are made

Programmer Question

I have a "restaurants" table with a "name" column. I've defined the following index:



indexes "REPLACE(UPPER(restaurants.name), 'THE ', '')", :as => :restaurant_name, :sortable => true


... because I want to sort the restaurant names without respect to the prefix "The ".



My problem is that whenever one of these records is updated (in any way) the new record jumps to the top of the sort order. If another record is updated, it also jumps ahead of the rest. I end up with two lists: a list of restaurants that have been updated since the last re-indexing and a list of those that haven't. Each respective list is in alphabetical order, but I don't understand why the overall list is getting segregated this way. I do have a delayed delta index set up, and I assume the issue is related to this.



Find the answer here

Thursday, April 22, 2010

Problems with video playback in iPad.

Programmer Question

I'm trying to implement a MPMoviePlayerView but I can't play the video files, I don't have a device yet to try it on, now I'm testing with simulator, I don't know if this is the cause.



So far I've been able to present the view and it shows the first frame of the video, but if I click play, it doesn't play I can move the progress bar and it shows the images, but there's no movement, it stays still.
Has anyone experienced something like this?



The code of my UIViewController goes like this:



NSURL *movieURL=[NSURL fileURLWithPath:@"video.mp4"];
MPMoviePlayerViewController *playerView=[[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
[self presentMoviePlayerViewControllerAnimated:playerView];


As I said, it shows up, I can move the progress bar back and forth, I see a still image, but no movement. Am I missing something here? or is it the simulator?
Thank you



Find the answer here

Undead Windows 7 service

Programmer Question

I created a Windows 7 service in Visual Studio 2010. Test install crashed and left lots of debris: service shows in the list of services but will not start ('Referenced file does not exist'), is impossible to uninstall ('Action valid only for services that are installed') and is not shown in the Programs and Features aplet.



Is there a list of installed services that I could hack?



Thanks,



Jan



Find the answer here

JPA Cascading Delete: Setting child FK to NULL on a NOT NULL column

Programmer Question

I have two tables: t_promo_program and t_promo_program_param.



They are represented by the following JPA entities:



@Entity
@Table(name = "t_promo_program")
public class PromoProgram {
@Id
@Column(name = "promo_program_id")
private Long id;

@OneToMany(cascade = {CascadeType.REMOVE})
@JoinColumn(name = "promo_program_id")
private List<PromoProgramParam> params;
}

@Entity
@Table(name = "t_promo_program_param")
public class PromoProgramParam {
@Id
@Column(name = "promo_program_param_id")
private Long id;

//@NotNull // This is a Hibernate annotation so that my test db gets created with the NOT NULL attribute, I'm not married to this annotation.
@ManyToOne
@JoinColumn(name = "PROMO_PROGRAM_ID", referencedColumnName = "promo_program_id")
private PromoProgram promoProgram;
}


When I delete a PromoProgram, Hibernate hits my database with:



update
T_PROMO_PROGRAM_PARAM
set
promo_program_id=null
where
promo_program_id=?

delete
from
t_promo_program
where
promo_program_id=?
and last_change=?


I'm at a loss for where to start looking for the source of the problem.



Find the answer here

Is it possible to inject a bean into a spring form bean

Programmer Question

I tried to do it 2 different ways, but neither way worked.



@Component  
public class EmailForm{
...
private QuestionDAO questionDAO;
...
@Autowired
public void setQuestionDAO(QuestionDAO questionDAO) {
this.questionDAO = questionDAO;
}
...


Another way:



@Component  
public class EmailForm implements ApplicationContextAware {
...
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.questionDAO = (QuestionDAO)applicationContext.getBean("questionDAO");
}
...


Neither way results in questionDAO being injected



Form bean is populated by spring:



@RequestMapping(method = RequestMethod.POST)
public String submit(@Valid final EmailForm emailForm, BindingResult result, final Model model) {


Find the answer here

Learning Perl, what to code in?

Programmer Question

Hey all,



I've got a few books and helpful guides to Perl from my company's scripting guy, but I can't seem to find where the best IDE for Perl is.



Mind you, simple is better. I'm just learning for now.



Thanks in advance!



Find the answer here

Wednesday, April 21, 2010

How to call these type of things using Javascript?

Programmer Question

  <%= Html.Trirand().JQGrid(Model.OrderGrid,"Grid1")%>


I need to call this using javascript?



Can anybody tell me?



thanks



Find the answer here

Can I create functions without defining it in the header file?

Programmer Question

Can I create a function inside a class without defining it in the header file of that class?



Find the answer here

Which Java ORM is considered the most performant generally speaking?

Programmer Question

Which Java ORM is considered the most performant generally speaking?



I realize this could mean less features, but just want an idea.



Find the answer here

protecting non .aspx pages with Asp.net Membership provider

Programmer Question

I'm currently using the asp.net membership provider (with logins stored in db) to protect certain pages of my site. However, I also have non .aspx resources I wish to protect - word docs, excel spreadsheets, pdfs, etc. Is this even possible? If so how would I go about doing this?



thanks!



Find the answer here

Factorising program not working. Help required.

Programmer Question

I am working on a factorisation problem using Fermat's Factorization and for small numbers it is working well. I've been able to calculate the factors (getting the answers from Wolfram Alpha) for small numbers, like the one on the Wikipedia page (5959).



Just when I thought I had the problem licked I soon realised that my program was not working when it came to larger numbers. The program follows through the examples from the Wikipedia page, printing out the values a, b, a2 and b2; the results printed for large numbers are not correct. I've followed the pseudocode provided on the Wikipedia page, but am struggling to understand where to go next.



Along with the Wikipedia page I have been following this guide. Once again, as my Math knowledge is pretty poor I cannot follow what I need to do next. The code I am using so far is as follows:



import java.math.BigInteger;

/**
*
* @author AlexT
*/
public class Fermat {

private BigInteger a, b;
private BigInteger b2;

private static final BigInteger TWO = BigInteger.valueOf(2);

public static BigInteger sqrt(BigInteger n) {
if (n.signum() >= 0) {
final int bitLength = n.bitLength();
BigInteger root = BigInteger.ONE.shiftLeft(bitLength / 2);

while (!isSqrt(n, root)) {
root = root.add(n.divide(root)).divide(TWO);
}
return root;
} else {
throw new ArithmeticException("square root of negative number");
}
}

public void fermat(BigInteger N) {
// a <- ceil(sqrt(N))
a = sqrt(N);
a = a.add(BigInteger.ONE);

// b2 <- a*a-N
b2 = (a.multiply(a)).subtract(N);

final int bitLength = N.bitLength();
BigInteger root = BigInteger.ONE.shiftLeft(bitLength / 2);
root = root.add(b2.divide(root)).divide(TWO);


// while b2 not square root
while(!(isSqrt(b2, root))) {
// a <- a + 1
a = a.add(BigInteger.ONE);
// b2 <- (a * a) - N
b2 = (a.multiply(a)).subtract(N);
root = root.add(b2.divide(root)).divide(TWO);
}

b = sqrt(b2);

BigInteger a2 = a.pow(2);

// Wrong
BigInteger sum = (a.subtract(b)).multiply((a.add(b)));

// Factors
BigInteger fact1 = a.subtract(b);
BigInteger fact2 = a.add(b);

System.out.println("F1: " + fact1 + "\nF2: " + fact2);

//if(sum.compareTo(N) == 0) {
//System.out.println("A: " + a + "\nB: " + b);
//System.out.println("A^2: " + a2 + "\nB^2: " + b2);
//}
}

/**
* Is the number provided a perfect Square Root?
* @param n
* @param root
* @return
*/
private static boolean isSqrt(BigInteger n, BigInteger root) {
final BigInteger lowerBound = root.pow(2);
final BigInteger upperBound = root.add(BigInteger.ONE).pow(2);
return lowerBound.compareTo(n) <= 0
&& n.compareTo(upperBound) < 0;
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Fermat fermat = new Fermat();
//Works
//fermat.fermat(new BigInteger("5959"));

// Doesn't Work
fermat.fermat(new BigInteger("90283"));
}
}


If anyone can help me out with this problem I'll be eternally grateful.



Find the answer here

Tuesday, April 20, 2010

How do you keep application logic separate from UI when UI components have built-in functionality?

Programmer Question

I know it's important to keep user interface code separated from domain code--the application is easier to understand, maintain, change, and (sometimes) isolate bugs. But here's my mental block ...



Delphi comes with components with methods that do what I want, e.g., a RichText Memo component lets me work with rich text. Other components, like TMS's string grid not only do what I want, but I paid extra for the functionality. These features put the R in RAD.



It seems illogical to write my own classes to do things somebody else has already done for me. It's reinventing the wheel [ever tried working directly with rich text? :-) ] But if I use the functionality built into components like these, then I will end up with lots of intermingled UI and domain code--I'll have a form with most of my code built into its event handlers.



How do you deal with this issue? ... Or, if I want to continue using the code others have already written for me, how would you suggest I deal with the issue?



Find the answer here

When will a TCP network packet be fragmented at the application layer?

Programmer Question

When will a TCP packet be fragmented at the application layer? When a TCP packet is sent from an application, will the recipient at the application layer ever receive the packet in two or more packets? If so, what conditions cause the packet to be divided. It seems like a packet won't be fragmented until it reaches the Ethernet (at the network layer) limit of 1500 bytes. But, that fragmentation will be transparent to the recipient at the application layer since the network layer will reassemble the fragments before sending the packet up to the next layer, right?



Find the answer here

How can I check if a value is in a list in Perl?

Programmer Question

I have a file in which every line is an integer which represents an id. What I want to do is just check whether some specific ids are in this list.
But the code didn't work. It never tells me it exists even if 123 is a line in that file. I don't know why? Help appreciated.



open (FILE, "list.txt") or die ("unable to open !");

my @data=<FILE>;

my %lookup =map {chop($_) => undef} @data;

my $element= '123';
if (exists $lookup{$element})
{
print "Exists";
}


Thanks in advance.



Find the answer here

ProtoBuffers, sending the protoobjects over the network

Programmer Question

My webservice(in java) will generate ProtoBuffer objects, how do i send this across so that my Python script can read the protobuffer object?



Find the answer here

How can i have a div stuck on the left side of the page no matter how much i scroll horizontally?

Programmer Question

This is kind of difficult to explain so ill link to a page that has the effect i need;



http://wpaoli.building58.com/wp-content/uploads/2009/08/feedback-panel.html



The feedback thing on the left side is what im trying to implement on my side,
instead of feedback im going to use it as a navigation menu that shows up when clicked on.



the things above is what i have right now.



my problem is when i scroll to the right ( my page is around 6000px wide )
i want it to stay on the left side,
is there a way to pull this off?



(this is to much for my brain to handle)..thanks!



Find the answer here

Monday, April 19, 2010

Swing: Scroll to bottom of JScrollPane, conditional on current viewport location

Programmer Question

Hi all,



I am attempting to mimic the functionality of Adium and most other chat clients I've seen, wherein the scrollbars advance to the bottom when new messages come in, but only if you're already there. In other words, if you've scrolled a few lines up and are reading, when a new message comes in it won't jump your position to the bottom of the screen; that would be annoying. But if you're scrolled to the bottom, the program rightly assumes that you want to see the most recent messages at all times, and so auto-scrolls accordingly.



I have had a bear of a time trying to mimic this; the platform seems to fight this behavior at all costs. The best I can do is as follows:



In constructor:



JTextArea chatArea = new JTextArea();
JScrollPane chatAreaScrollPane = new JScrollPane(chatArea);

// We will manually handle advancing chat window
DefaultCaret caret = (DefaultCaret) chatArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);


In method that handles new text coming in:



boolean atBottom = isViewAtBottom();

// Append the text using styles etc to the chatArea

if (atBottom) {
scrollViewportToBottom();
}


public boolean isAtBottom() {
// Is the last line of text the last line of text visible?
Adjustable sb = chatAreaScrollPane.getVerticalScrollBar();

int val = sb.getValue();
int lowest = val + sb.getVisibleAmount();
int maxVal = sb.getMaximum();

boolean atBottom = maxVal == lowest;
return atBottom;
}


private void scrollToBottom() {
chatArea.setCaretPosition(chatArea.getDocument().getLength());
}


Now, this works, but it's janky and not ideal for two reasons.




  1. By setting the caret position, whatever selection the user may have in the chat area is erased. I can imagine this would be very irritating if he's attempting to copy/paste.

  2. Since the advancement of the scroll pane occurs after the text is inserted, there is a split second where the scrollbar is in the wrong position, and then it visually jumps towards the end. This is not ideal.



Before you ask, yes I've read this blog post on Text Area Scrolling, but the default scroll to bottom behavior is not what I want.



Other related (but to my mind, not completely helpful in this regard) questions:
Setting scroll bar on a jscrollpane
Making a JScrollPane automatically scroll all the way down.



Any help in this regard would be very much appreciated.



Find the answer here

staying within boundaries of image?

Programmer Question

So I am to loop through copyFrom.pixelData and copy it into pixelData.



I realize that I need to check the conditions of i and j, and have them not copy past the boundaries of pixelData[x][y],



I need another 2 loops for that? I tried this, but was getting segmentation fault..
Is this the right approach?



void Image::insert(int xoff, int yoff, const Image& copyFrom, Color notCopy)
{
for (int x = xoff; x < xoff+copyFrom.width; x++) {
for (int y = yoff; y < yoff+copyFrom.height; y++) {
for (int i = 0; i<width; i++){
for (int j = 0; j<height; j++){
if (copyFrom.pixelData[i][j].colorDistance(notCopy)>20 )
pixelData[x][y]=copyFrom.pixelData[i][j];
}
}
}
}
}


Find the answer here

Mirroring a project from bitbucket to github

Programmer Question

Is there an efficient workflow to mirror a project that is mainly hosted on bitbucket, to github?



Find the answer here

Breaking a captcha

Programmer Question

What I'm looking for is a way to break this captcha: https://www.nfe.fazenda.gov.br/PORTAL/FormularioDePesquisa.aspx?tipoConsulta=completa



Notice that the image alternates based on 2 types of images. Anyone knows a OCR (optical character recognition) 'damm good'for this? Other solutions also accepted (except proxing).



I'm not looking for spamming, I just want to automatize my Software instead of proxing the image for the user.



Nowhere in the site says it is forbidden to automatically parse the image.



Find the answer here

Design: How to declare a specialized memory handler class

Programmer Question

On an embedded type system, I have created a Small Object Allocator that piggy backs on top of a standard memory allocation system. This allocator is a Boost::simple_segregated_storage<> class and it does exactly what I need - O(1) alloc/dealloc time on small objects at the cost of a touch of internal fragmentation. My question is how best to declare it. Right now, it's scope static declared in our mem code module, which is probably fine, but it feels a bit exposed there and is also now linked to that module forever. Normally, I declare it as a monostate or a singleton, but this uses the dynamic memory allocator (where this is located.) Furthermore, our dynamic memory allocator is being initialized and used before static object initialization occurs on our system (as again, the memory manager is pretty much the most fundamental component of an engine.) To get around this catch 22, I added an extra 'if the small memory allocator exists' to see if the small object allocator exists yet. That if that now must be run on every small object allocation. In the scheme of things, this is nearly negligable, but it still bothers me.



So the question is, is there a better way to declare this portion of the memory manager that helps decouple it from the memory module and perhaps not costing that extra isinitialized() if statement? If this method uses dynamic memory, please explain how to get around lack of initialization of the small object portion of the manager.



Find the answer here

Sunday, April 18, 2010

jquery navigate in code

Programmer Question

Hi trying to fade out elements on the page when a navigation link is clicked, then go to the clicked link:



$("#navigation a").click(function() {   
var $clickobj = $this;
$("div#content").animate({opacity: 'toggle', paddingTop: '0px'}, 'slow',function(){
$("div#navigation").animate({opacity: 'toggle', paddingTop: '0px'}, 'slow', function(){
$("div#logo").animate({opacity: 'toggle', paddingTop: '0px'}, 900, function(){
$clickobj.click();
});
});
});
return false;
});


but this just navigates straight away with the fade out...any ideas?



Find the answer here

android: having two listviews in two listactivities didn't work

Programmer Question

I guess my previous question wasn't clear enough (http://stackoverflow.com/questions/2549585/android-failed-to-setcontentview-when-switching-to-listactivity), so I explain as follows.



In my app I have two listactivities which uses two different listviews:



public class Activity1 extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.listview1);
}
public class Activity2 extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.listview2);
}


}



As required by android, listview must have an ID which is exactly "@android:id/list". If I set the listview in both listview1 and listview2 with the same ID, then they will end up using the same format of listview, which is not what I want. But if I set one of the IDs to be sth like "@+id/listview2", android gave me the error:
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'



How do I handle this dilema?



Find the answer here

What C++ library to use to write a cross-platform service/daemon?

Programmer Question

I wonder what library would ease the development of a cross-platform service/daemon ? (C/C++)



I'm targeting: Windows, Linux and OS X.



Also it would be nice to have a basic sample service application.



Find the answer here

User control always crashes Visual Studio

Programmer Question

I'm trying to open a user control in one of our projects. It was created, I believe, in VS 2003, and the project has been converted to VS2008. I can view the code fine, but when I try to load the designer view, VS stops responding and I have to close it with the task manager. I have tried leaving it running for several minutes, but it does not do anything. I ran "devenv /log" but didn't see anything unusual in the log. I can't find a specific error message anywhere. Any idea what the problem might be? Is there a lightweight editing mode I might be able to use or something?



The reason I need to have a look at the visual representation of this control is to decide where to insert some new components.



I've tried googling it and searching SO, but either I don't know what to search or there is nothing out there about this. Any help is appreciated.



(The strangest thing is that the user control seems to load fine in another project which references, but VS crashes as soon as I even so much as click on it in that project.)



Find the answer here

What are some linq "best practices"

Programmer Question

Looking to use linq throughout my next project to ease some of the hard labor. Before, I dive into the linq world I would like some advice on best prctices on using linq. I am still undecided on EF and linq to sql



Find the answer here

Saturday, April 17, 2010

Check if a variable is empty

Programmer Question

I have some user-submitted variables that I want to display in a different part of my site like this:



<div class="pre_box">Term: </div>
<div class="entry"><?php $key='term'; echo get_post_meta($post->ID, $key, true); ?></div>


Occasionally, these variables might be empty in which case I don't want to display the label for the empty variable. In the example above I would want to hide the <div class="pre_box">Term: </div> part. Is there some simple way to check if a php variable like the one above is empty and prevent the label from being displayed?



Update, here is the code using !empty



<?php $key='term' ?>
<?php if( !empty( $key ) ): ?>
<div class="pre_box">Term: </div>
<div class="entry">
<?php echo get_post_meta($post->ID, $key, true); ?>
</div>
<?php endif; ?>


However, this still displays the content no matter what. I think the problem might be in the way I am defining the $key variable. Im trying to pull data from a custom field set in a wordpress post - thats what the $post->ID business is all about.



Find the answer here

Inheritance - initialization problem

Programmer Question

I have a c++ class derived from a base class in a framework.



The derived class doesn't have any data members because I need it to be freely convertible into a base class and back - the framework is responsible for loading and saving the objects and I can't change it. My derived class just has functions for accessing the data.



But there are a couple of places where I need to store some temporary local variables to speed up access to data in the base class.



mydata* MyClass::getData() {
if ( !m_mydata ) { // set to NULL in the constructor
m_mydata = some_long_and complex_operation_to_get_the_data_in_the_base()
}
return m_mydata;
}


The problem is if I just access the object by casting the base class pointer returned from the framework to MyClass* the ctor for MyClass is never called and m_mydata is junk.

Is there a way of only initializing the m_mydata pointer once?



Find the answer here

MSBuild conditionals depending on task parameters

Programmer Question

In MSBuild it's straightforward to define, say, a PropertyGroup which depends on the value of a property Foo:



<PropertyGroup Conditional="'$(Foo)'=='Bar'" />


Is it also possible for the conditional to depend on a task parameter?



For example, I'd like to use the value of the Link task's SubSystemparameter roughly like this:



<PropertyGroup Conditional="'$(Link/SubSystem)'=='Console'" />


but don't know if it is possible, and if it is, what the correct syntax is.



I'm pretty new to MSBuild though, so it's perfectly possible that I've missed something.



Find the answer here

What is a good balance for having developers learn at work

Programmer Question

So now I am the manager.



One of the things I always promised myself I would do is have the other developers focus on learning new stuff. In fact I even want to force them to read a couple books that really helped me learn to program.



However now I am also accountable for the product getting finished. I have this vision of everyone reading books instead of working and me getting fired.



What is the best way to work learning into the developers schedules, especially for the ones that just don't care to learn. How much time should be spent on learning in a work week?



Find the answer here

iPhone App made using Xcode 3.2.3 does not run on 3.1.3 OS

Programmer Question

I can't figure this out and I thought that someone might run through the same thing.



I have Xcode 3.2.3 (Pre Release with OS 4 beta) and I started to create my application, after the final touches and everything worked ok, I changed the Simulator - 4.0 to Simulator - 3.1.3 (latest iPhone OS) and I could never start my app again :-(



Does anyone know what I should do?



I created a simple Screencast of the problem so everyone can see what I'm writing about.



Thank you for all the help.



Find the answer here

Friday, April 16, 2010

Why won't jqGrid won't populate initially in Chrome

Programmer Question

Hi,



I've got a web page with a jqGrid that uses am xmlreader to populate itself with data that is spat out by a RoR service. The page loads fine in firefox and safari. In Chrome however I get a blank grid. Only when I change the sort order by clicking on the columns does it populate.



<html> 
<head>
<title>LocalFx</title>
<link href="/stylesheets/main.css?1271423251" media="screen" rel="stylesheet" type="text/css" />


<link href="/stylesheets/redmond/jquery-ui-1.8.custom.css?1271404544" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/ui.jqgrid.css?1265561560" media="screen" rel="stylesheet" type="text/css" />
<script src="/javascripts/jquery-1.3.2.min.js?1259426008" type="text/javascript"></script>
<script src="/javascripts/i18n/grid.locale-en.js?1266140090" type="text/javascript"></script>
<script src="/javascripts/jquery.jqGrid.min.js?1271437772" type="text/javascript"></script>



<script type="text/javascript">

jQuery().ready(function() {
jQuery("#list").jqGrid({
xmlReader: {
root:"contracts",
row:"contract",
repeatitems:false,
id:"id"
},
jsonReader: {
repeatitems:false,
root:"contracts"
},
datatype: 'xml',
url:'http://localhost:3000/contracts/index/all.xml',
mtype: 'GET',
colNames:['User','B/S', 'Currency', 'Amount', 'Rate'],
colModel :[
{name:'user', index:'username', width:100 , xmlmap:'user>username'} ,
{name:'side', index:'side', width:100 , xmlmap:'side'} ,
{name:'currency', index:'ccy', width:100 , xmlmap:'currency>ccy'} ,
{name:'amount', index:'amount', width:100 , xmlmap:'amount'},
{name:'rate', index:'rate', width:100 , xmlmap:'exchange-rate>rate'}
],
pager: jQuery('#pager'),
caption: 'Contracts',
sortname: 'side',
sortorder: "asc",
viewrecords:true,

rowNum:10,
rowList:[10,20,30]
});
$("#list").trigger("reloadGrid")
});
</script>


</head>
<body>

<table id="list" align="center" class="scroll"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>

</body>
</html>


This is the xml:



<contracts type="array"> 
<contract>
<amount type="float">1000.0</amount>
<created-at type="datetime">2010-04-16T13:59:40Z</created-at>
<currency-id type="integer">488525179</currency-id>
<id type="integer">18277852</id>
<side>BUY</side>
<updated-at type="datetime">2010-04-16T13:59:40Z</updated-at>
<user-id type="integer">830138774</user-id>
<exchange-rate>
<contract-id type="integer">18277852</contract-id>
<created-at type="datetime">2010-04-16T13:59:40Z</created-at>
<denccy-id type="integer">890731696</denccy-id>
<id type="integer">419011264</id>
<numccy-id type="integer">488525179</numccy-id>
<rate type="float">1.3</rate>
<updated-at type="datetime">2010-04-16T13:59:40Z</updated-at>
</exchange-rate>
<user>
<created-at type="datetime">2010-04-16T13:59:40Z</created-at>
<id type="integer">830138774</id>
<updated-at type="datetime">2010-04-16T13:59:40Z</updated-at>
<username>John Doe</username>
</user>
<currency>
<ccy>EUR</ccy>
<created-at type="datetime">2010-04-16T13:59:40Z</created-at>
<id type="integer">488525179</id>
<updated-at type="datetime">2010-04-16T13:59:40Z</updated-at>
</currency>
</contract>
<contract>
<amount type="float">500.0</amount>
<created-at type="datetime">2010-04-16T13:59:40Z</created-at>
<currency-id type="integer">890731696</currency-id>
<id type="integer">716237132</id>
<side>SELL</side>
<updated-at type="datetime">2010-04-16T13:59:40Z</updated-at>
<user-id type="integer">830138774</user-id>
<exchange-rate>
<contract-id type="integer">716237132</contract-id>
<created-at type="datetime">2010-04-16T13:59:40Z</created-at>
<denccy-id type="integer">890731696</denccy-id>
<id type="integer">861902380</id>
<numccy-id type="integer">488525179</numccy-id>
<rate type="float">1.3</rate>
<updated-at type="datetime">2010-04-16T13:59:40Z</updated-at>
</exchange-rate>
<user>
<created-at type="datetime">2010-04-16T13:59:40Z</created-at>
<id type="integer">830138774</id>
<updated-at type="datetime">2010-04-16T13:59:40Z</updated-at>
<username>John Doe</username>
</user>
<currency>
<ccy>GBP</ccy>
<created-at type="datetime">2010-04-16T13:59:40Z</created-at>
<id type="integer">890731696</id>
<updated-at type="datetime">2010-04-16T13:59:40Z</updated-at>
</currency>
</contract>
</contracts>


Find the answer here

problem with uninitialized constant

Programmer Question

Hi, I have the following controller



class ActiveUsersController < ApplicationController

def edit
end


end



And my routes.rb is like this:



map.resources :active_users


When I try to access the controller using the url http://localhost:3000/active_users/COo8e45RqQAHr6CqSCoI/edit I got the following error:



NameError in Active usersController#edit



uninitialized constant ActiveUsersController
RAILS_ROOT: /Users/vintem/Documents/Projetos/Pessoal/bugfreela



Application Trace | Framework Trace | Full Trace
/Users/vintem/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:443:in load_missing_constant'
/Users/vintem/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:80:in
const_missing'
/Users/vintem/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:92:in const_missing'
/Users/vintem/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/inflector.rb:361:in
constantize'
/Users/vintem/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/inflector.rb:360:in each'
/Users/vintem/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/inflector.rb:360:in
constantize'
/Users/vintem/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/string/inflections.rb:162:in constantize'
/Users/vintem/.gem/ruby/1.8/gems/actionpack-2.3.5/lib/action_controller/routing/route_set.rb:443:in
recognize'
/Users/vintem/.gem/ruby/1.8/gems/actionpack-2.3.5/lib/action_controller/routing/route_set.rb:436:in `call'



Can anyone help me?



Thanks



Find the answer here

How do I simplify this templated vector initializer loop using lambdas or some kind of STL transform?

Programmer Question

How do I simplify this templated vector initializer loop using lambdas or some kind of STL transform?



template<typename T>
template<typename... Args>
DotProduct<T>::DotProduct(int n, RNG& rng, Args const&... args) {
myBasis.resize(n);
for (auto it = myBasis.begin(); it != myBasis.end(); ++it) {
typename T::CPDDist cpd(rng, args...);
*it = T(cpd);
}
}


Find the answer here

Wednesday, April 14, 2010

Get PocketC File Handle Int?

Programmer Question

I'm now taking a look at the PocketC powerful tool, but there is an fileopen function, that generates a integer called filehandle, that is used for most of the File I/O operations of PocketC. How do I use this int filehandle to call the other file manipulation functions?



Here is my example function that I'm using at my program:



fileopen("\test.txt", 0, 0x00000000);


Description of int filehandle: Integer used for file operations, used as a pointer to the fileopen instruction.



Find the answer here

handle user logoff or machine shutdown requests on WindowsME

Programmer Question

I have to write a C# application that runs on WindowsME. Yes, I mean that Microsoft operating system that has been forgotten a long long time ago. My program needs no user interaction and as WindowsME doesn't support services, it will be a console application. Furthermore it will be used on more modern operating systems, where the user can choose whether to start it as console application or install it as a windows service. Now suppose the software is running on WinME and the user decides to logoff or shutdown the machine without a prior quit of my software. WinME complains about my program still running and asks if it should kill the process. Apart from the bad user experiance, this means that the application is not shut down properly.



So I look for a way to be informed if the user logs off or wants to shutdown the machine to be able to perform a proper shutdown of my software first.



Find the answer here

Issue with CAAnimation and CALayer Transforms

Programmer Question

I have a CALayer that I want to animate across the screen. I have created two methods: one slide open the layer and one to slide close. These both work by assigning a property to the layer's transform property.



Now I want to use a CAKeyFrameAnimation to slide open the layer. I got this working so the layer slides open, but now I can't slide the layer close using my old method. I am trying to figure out why this is. Any help would be great.



Code:



- (id)init
{
if( self = [super init] )
{
bIsOpen = NO;
closeTransform = self.transform;
openTransform = CATransform3DMakeTranslation(-235.0, 0.0, 0.0);
}
return self;
}

- (void)closeMenu
{
if( bIsOpen )
{
self.transform = closeTransform;
bIsOpen = !bIsOpen;
}
}

- (void)openMenu
{
if( !bIsOpen )
{
CAKeyframeAnimation *closeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
closeAnimation.duration = 1.0;
closeAnimation.removedOnCompletion = NO;
closeAnimation.fillMode = kCAFillModeForwards;
closeAnimation.values = [NSArray arrayWithObjects:[NSValue valueWithCATransform3D:closeTransform],[NSValue valueWithCATransform3D:openTransform],nil];
closeAnimation.timingFunctions = [NSArray arrayWithObject:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];

[self addAnimation:closeAnimation forKey:@"transform"];
bIsOpen = !bIsOpen;
}
}


Find the answer here

how to echo data that we read with file_get_contents

Programmer Question

i want to check remote url's page contents. IF remote site's page content contains string http://yahoo.com set $qqq = YH if not contains $qqq = NOYH. i am not talking about "url of that page" im talking about page content of url



$url = "'".$get['url']."'";
$needle = "http://yahoo.com/";
$contents = file_get_contents($url);
if(stripos($contents, $needle) !== false) {
$qqq = "YH";
}


But it's not working. Can anybody help me with the correct syntax? thanks..



Find the answer here

Java: Initializing a public static field in superclass that needs a different value in every subclass instance

Programmer Question

Good evening,



I am developing a set of Java classes so that a container class Box contains a List of a contained class Widget. A Widget needs to be able to specify relationships with other Widgets. I figured a good way to do this would be to do something like this:



public abstract class Widget {
public static class WidgetID {
// implementation stolen from Google's GWT
private static int nextHashCode;
private final int index;

public WidgetID() {
index = ++nextHashCode;
}

public final int hashCode() {
return index;
}
}

public abstract WidgetID getWidgetID();

}


so sublcasses of Widget could:



public class BlueWidget extends Widget {
public static final WidgetID WIDGETID = new WidgetID();

@Override
public WidgetID getWidgetID() {
return WIDGETID;
}
}


Now, BlueWidget can do getBox().addWidgetRelationship(RelationshipTypes.SomeType, RedWidget.WIDGETID, and Box can iterate through it's list comparing the second parameter to iter.next().getWidgetID().



Now, all this works great so far. What I'm trying to do is keep from having to declare the public static final WidgetID WIDGETID in all the subclasses and implement it instead in the parent Widget class. The problem is, if I move that line of code into Widget, then every instance of a subclass of Widget appears to get the same static final WidgetID for their Subclassname.WIDGETID. However, making it non-static means I can no longer even call Subclassname.WIDGETID.



So: how do I create a static WidgetID in the parent Widget class while ensuring it is different for every instance of Widget and subclasses of Widget? Or am I using the wrong tool for the job here?



Thanks!



Find the answer here

Tuesday, April 13, 2010

JavaScript: 'textarea.value' not working in IE?

Programmer Question

Hi! A few hours ago, I was instructed how to style a specific textarea with JS. The following piece of code (thanks again, Mario Menger) works like a charm in Firefox but unfortunately nothing happens in Internet Explorer (7 tested only so far).



var foo = document.getElementById('HCB_textarea');
var defaultText = 'Your message here';
foo.value = defaultText;
foo.style.color = '#888';
foo.onfocus = function(){
foo.style.color = '#000';
if ( foo.value == defaultText ) {
foo.value = '';
}
};
foo.onblur = function(){
foo.style.color = '#888';
if ( foo.value == '' ) {
foo.value = defaultText;
}

};


I've already tried to replace 'value' by 'innerHTML' (for IE only) but to no effect. Any suggestions? TIA



Find the answer here

Using XSD to validate node count

Programmer Question

I don't think this is possible but I thought I'd throw it out there. Given this XML:



 <people count="3">
<person>Bill</person>
<person>Joe</person>
<person>Susan</person>
</people>


Is it possible in an XSD to force the @count attribute value to be the correct count of defined elements (in this case, the person element)? The above example would obviously be correct and the below example would not validate:



 <people count="5">
<person>Bill</person>
<person>Joe</person>
<person>Susan</person>
</people>


Find the answer here

How can I flush the output of disp in Octave?

Programmer Question

I have a program in Octave that has a loop - running a function with various parameters, not something that I can turn into matrices. At the beginning of each iteration I print the current parameters using disp.



The first times I ran it I had a brazillion warnings, and then I also got these prints. Now that I cleaned them up, I no longer see them. My guess is that they're stuck in a buffer, and I'll see them when the program ends or the buffer fills.



Is there any way to force a flush of the print buffer so that I can see my prints?



Find the answer here

Any tool available to detect what's not HTTPS on an encrypted page?

Programmer Question

More often than I like when designers edit some of our sites' pages, they include javascript or an external image our SSL pages that are not encrypted. For example if we have a page like this:




https://www.example.com/cart/EnterCreditCard




And the designer includes some non-encrypted image like this:



<img src='http://www.cardprocessor.com/logo.gif' />


Of course, this creates errors in all browsers:




  • IE: Do you want to view only the webpage content that was delivered securely?

  • Firefox: Connection Partially Encrypted

  • Chrome: (I forget this message)



What I'm looking for is a tool or plugin that lets me easily see what objects are not encrypted. A firefox extension or something along those lines would be great.



Edit: Ben pointed me in the right direction. If you're using Chrome, do a Ctrl-Shift-J to bring up the developer tools. Then click on Resources to see all the items on the page.



Find the answer here

What would I use to remove escaped html from large sets of data.

Programmer Question

Our database is filled with articles retrieved from RSS feeds. I was unsure of what data I would be getting, and how much filtering was already setup (WP-O-Matic Wordpress plugin using the SimplePie library). This plugin does some basic encoding before insertion using Wordpress's built in post insert function which also does some filtering. Between the RSS feed's encoding, the plugin's encoding using PHP, Wordpress's encoding and SQL escaping, I'm not sure where to start.



The data is usually at the end of the field after the content I want to keep. It is all on one line, but separated out for readability:



<img src="http://feeds.feedburner.com/~ff/SoundOnTheSound?i=xFxEpT2Add0:xFbIkwGc-fk:V_sGLiPBpWU" border="0"></img>



<img src="http://feeds.feedburner.com/~ff/SoundOnTheSound?d=qj6IDK7rITs" border="0"></img>



<img src="http://feeds.feedburner.com/~ff/SoundOnTheSound?i=xFxEpT2Add0:xFbIkwGc-fk:D7DqB2pKExk"



Notice how some of the images are escape and some aren't. I believe this has to do with the last part being cut off so as to be unrecognizable as an html tag, which then caused it to be html endcoded while the actual img tags were left alone.



Another record has only this in one of the fields, which means the RSS feed gave me nothing for the item (filtered out now, but I have a bunch of records like this):



<img src="http://farm3.static.flickr.com/2183/2289902369_1d95bcdb85.jpg" alt="post_img" width="80"



All extracted samples are on one line, but broken up for readability. Otherwise, they are copied exactly from the database from the command line mysql client.



Question: What is the best way to work with the above escaped html (or portion of an html tag), so I can then remove it without affecting the content?



I can do it in Perl, PHP, SQL, Ruby, and even Python. I believe Perl to be the best at text parsing, so that's why I used the Perl tag. And PHP times out on large database operations, so that's pretty much out unless I wanted to do batch processing and what not.



[EDIT]
If it was just a matter of pulling the html I wanted out and doing a strip_tags and reinserting the data, I wouldn't be asking this question.



The portion that I have a problem with is that what used to be an img tag was html encoded and the end cut off. If it's deencoded it will not be an html tag, so I cannot parse it the usual way.



With all the <img src=" crap, I can't get my head around searching for it other than SELECT ID, post_content FROM table WHERE post_content LIKE '<img' which at least gets me those posts. But when I get the data, I need a way to find it, remove it, but keep the rest of the content.



[/EDIT]



PS One of the nice things about using Wordpress's insert post function, is that if you use php's strip_tags function to strip out all html, insert post function will insert <p> at the paragraph points.



Let me know if there's anything more that I can answer.



Some article that didn't quite answer my questions.
(http://stackoverflow.com/questions/2016751/remove-text-from-within-a-database-text-field)
(http://stackoverflow.com/questions/462831/regular-expression-to-escape-html-ampersands-while-respecting-cdata)



Find the answer here

Monday, April 12, 2010

where can i get the spring framework 3.0 distribution?

Programmer Question

has anyone been able to download the spring framework 3.0.0.M4 release from the spring source site... (or can you provide an alternative download page)?



http://www.springsource.org/download



am I missing something..., the site is giving me the runaround...



when i get to the "Spring Community Downloads" page and choose spring from the LHS menu... I get no download link...



ta in advance...



Find the answer here

MVC Areas - View not found

Programmer Question

Hi,



I have a project that is using MVC areas. The area has the entire project in it while the main "Views/Controllers/Models" folders outside the Areas are empty barring a dispatch controller I have setup that routes default incoming requests to the Home Controller in my area.



This controller has one method as follows:-



public ActionResult Index(string id)
{
return RedirectToAction("Index", "Home", new {area = "xyz"});
}


I also have a default route setup to use this controller as follows:-



routes.MapRoute(
"Default", // Default route
"{controller}/{action}/{id}",
new { controller = "Dispatch", action = "Index", id = UrlParameter.Optional }
);


Any default requests to my site are appropriately routed to the relevant area. The Area's "RegisterArea" method has a single route:-



context.MapRoute(
"xyz_default",
"xyz/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }


My area has multiple controllers with a lot of views. Any call to a specific view in these controller methods like "return View("blah");
renders the correct view. However whenever I try and return a view along with a model object passed in as a parameter I get the
following error:-



Server Error in '/DeveloperPortal' Application.
The view 'blah' or its master was not found. The following locations were searched:
~/Views/Profile/blah.aspx
~/Views/Profile/blah.ascx
~/Views/Shared/blah.aspx
~/Views/Shared/blah.ascx


It looks like whenever a model object is passed in as a param. to the "View()" method [e.g. return View("blah",obj) ] it searches for the view
in the root of the project instead of in the area specific view folder.



What am I missing here ?



Thanks in advance.



Find the answer here

ASP.NET MVC 2.0 Validation and ErrorMessages

Programmer Question

I need to set the ErrorMessage property of the DataAnnotation's validation attribute in MVC 2.0. For example I should be able to pass an ID instead of the actual error message for the Model property, for example...



[StringLength(2, ErrorMessage = "EmailContentID")] 
[DataType(DataType.EmailAddress)]
public string Email { get; set; }


Then use this ID ("EmailContentID") to retrieve some content(error message) from a another service e.g database. Then the error error message is displayed to the user instead of the ID. In order to do this I need to set the DataAnnotation validation attribute’s ErrorMessage property.



It seems like a stright forward task by just overriding the DataAnnotationsModelValidatorProvider‘s protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)



However it is complicated now....



A. MVC DatannotationsModelValidator’s ErrorMessage property is readonly. So I cannot set anything here
B. System.ComponentModel.DataAnnotationErrorMessage property(get and set) which is already set in MVC DatannotationsModelValidator so I cannot set it again. If I try to set it I get “The property cannot set more than once…�? error message.



 public class CustomDataAnnotationProvider : DataAnnotationsModelValidatorProvider 
{
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
{
IEnumerable<ModelValidator> validators = base.GetValidators(metadata, context, attributes);

foreach (ValidationAttribute validator in validators.OfType<ValidationAttribute>())
{
messageId = validator.ErrorMessage;
validator.ErrorMessage = "Error string from DB And" + messageId ;
}

//......
}
}


Can anyone please give me the right direction on this?



Thanks in advance.



Find the answer here

Big O complexity

Programmer Question

what is Big Oh notation mean and when an algorithm has logarithmic complexity??
for example how is quick sort O(nlogn)???



Find the answer here

How to properly encode "[" and "]" in queries using Apache HttpClient?

Programmer Question

I've got a GET method that looks like the following:



 GetMethod method = new GetMethod("http://host/path/?key=[\"item\",\"item\"]");


Such a path works just fine when typed directly into a browser, but the above line when run causes an IllegalArgumentException : Invalid URI.



I've looked at using the URIUtils class, but without success. Is there a way to automatically encode this (or to add a query string onto the URL without causing HttpClient to barf?).



Find the answer here

Sunday, April 11, 2010

Create Registry Value In Local Machine Using C#

Programmer Question

I'm trying to save an install path to the registry so my windows service will know where my other application was installed.



I'm using visual studio's deployment to create a registry value in HKEY_CURRENT_USER, but my windows service which runs under LocalMachine doesn't have access to that. I then made the installer create a registry value in HKEY_LOCAL_MACHINE, but when I view the registry after the install it appears it never made the value. Any ideas?



Find the answer here

Call two Matlab functions simultaneously from .net

Programmer Question

I am writing a C# application and I would like to make calls to different matlab functions simultaneously(from different threads). Each Matlab function is located in its own compiled .net library. It seems that I am only able to call one Matlab function at a time however.



ie, if matlab_func1() gets called from thread1 then matlab_func2() gets called from thread2, matlab_func2() must wait for matlab_func1() to finish executing.



Is there a way to call different matlab functions simultaneously? Thanks.



Find the answer here

LinkWithin

Related Posts with Thumbnails