Sunday, February 28, 2010

Programmer - default value, oracle sp call

Programmer Question

I have an oralcle SP forced on me that will not accept an empty parameter in an update. So if I wanted to set a value back to the default of ('') it will not let me pass in the empty string. Is there a keyword you can use such as default, null, etc that oracle would interpret back to the default specified for a particular column?



Find the answer here

Programmer - C++: Compiler warning for large unsigned int

Programmer Question

I have following array, that I need to operate by hand on bitmaps.



const unsigned int BITS[32] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 
2048, 4096, 8192, 16384, 32768, 65536, 131072,
262144, 524288, 1048576, 2097152, 4194304,
8388608, 16777216, 33554432, 67108864, 134217728,
268435456, 536870912, 1073741824, 2147483648};


Unfortunately, when compiled I get




warning: this decimal constant is unsigned only in ISO C90




How can I remove this?



Find the answer here

Programmer - JSON Twitter List in C#.net

Programmer Question

Hi, My code is below. I am not able to extract the 'name' and 'query' lists
from the JSON via a DataContracted Class (below)
I have spent a long time trying to work this one out, and could really do
with some help...



My Json string == {"as_of":1266853488,"trends":{"2010-02-22
15:44:48":[{"name":"#nowplaying","query":"#nowplaying"},{"name":"#musicmonday","query":"#musicmonday"},{"name":"#WeGoTogetherLike","query":"#WeGoTogetherLike"},{"name":"#imcurious","query":"#imcurious"},{"name":"#mm","query":"#mm"},{"name":"#HumanoidCityTour","query":"#HumanoidCityTour"},{"name":"#awesomeindianthings","query":"#awesomeindianthings"},{"name":"#officeformac","query":"#officeformac"},{"name":"Justin
Bieber","query":"\"Justin Bieber\""},{"name":"National
Margarita","query":"\"National Margarita\""}]}}



WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(this.Auth.UserName, this.Auth.Password);
string res = wc.DownloadString(new Uri(link));
//the download string gives me the above JSON string - no problems
Trends trends = new Trends();
Trends obj = Deserialise<Trends>(res);


private T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
obj = (T)serialiser.ReadObject(ms);
ms.Close();
return obj;
}
}


[DataContract]
public class Trends
{
[DataMember(Name = "as_of")]
public string AsOf { get; set; }

//The As_OF value is returned - But how do I get the
//multidimensional array of Names and Queries from the JSON here?
}


Find the answer here

Programmer - Fonction to prevent special characters in nickname

Programmer Question

Hi,



I've a website where users can register. For the nickname (used to login) I would like to prevent all special characters, accents, etc. I use PHP.



How can I do that ? Thanks



Find the answer here

Programmer - Java: constructing a file from a URI?

Programmer Question

I need to obtain a File object from a URI, working in Java, but keep getting a length of zero - though I know the file size is not zero.



I need the File object to pass to another constructor.



I'm not sure if it's because I'm constructing it in the wrong way? Here's my code:



    File videoFile = new File(videoURI.getPath());
if (videoFile == null) {
Log.d(LOG_TAG, "File not found!");
return false;
}

Log.d(LOG_TAG, "about to upload, filepath: " + videoFile.getPath());

Log.d(LOG_TAG, "File length: " + String.valueOf(videoFile.length()));


The log output doesn't spit out 'File not found!', and prints a non-null path, but shows a length of 0.



Find the answer here

Saturday, February 27, 2010

Programmer - Brackets matching using BIT

Programmer Question

I am trying to check if brackets are balanced in a given string containing only ('s or )'s.
I am using a BIT(Binary indexed tree) for solving the problem.
The procedure i am following is as follows:



I am taking an array of size equal to the number of characters in the string.
I am assigning -1 for ) and 1 for ( to the corresponding array elements.



Brackets are balanced in the string only if the following two conditions are true.




  • The cumulative sum of the whole array is zero.

  • Minimum cumulative sum is non negative.
    i.e the minimum of cumulative sums of all the prefixes of the array is non-negative.



Checking condition 1 using a BIT is trivial.
I am facing problem in checking condition 2.



Find the answer here

Programmer - Parsing JSON without quoted keys

Programmer Question

I understand that in JSON, keys are supposed to be surrounded in double quotes. However, I'm using a data source which doesn't quote them, which is causing the Ruby JSON parser to raise an error. Is there any way to perform 'non-strict' parsing?



Example:



>> JSON.parse('{name:"hello", age:"23"}')
JSON::ParserError: 618: unexpected token at '{name:"hello", age:"23"}'
from /Library/Ruby/Gems/1.8/gems/json-1.1.7/lib/json/common.rb:122:in `parse'
from /Library/Ruby/Gems/1.8/gems/json-1.1.7/lib/json/common.rb:122:in `parse'
from (irb):5
>> JSON.parse('{"name":"hello", "age":"23"}')
=> {"name"=>"hello", "age"=>"23"}
>>


(I tried using a regular expression to add the quotes in before parsing but couldn't get it fully working).



Find the answer here

Programmer - How do I get Attributes from Core Data into an Array for - iPhone SDK

Programmer Question

Hi All,



I'm trying to retrieve data from Core Data and put it into a Mutable Array



I have an Entity called 'Stock' and in Properties, attributes called : Code, Price & Description...



How do I get the data stored in these attributes into a simple Mutable Array?



Find the answer here

Programmer - convert txt or doc to pdf using php

Programmer Question

have anyone come across a php code that convert text or doc into pdf ?



it has to follow the same format as the original txt or doc file meaning the line feed as well as new paragraph...



Find the answer here

Programmer - What was your first home computer?

Programmer Question

What was your first home computer? The one that made you "fall in love" with programming.






There are 300+ entries, many (most?) of which are duplicates.



As with all StackOverflow Poll type Q&As, please make certain your answer is NOT listed already before adding a new answer - searching doesn't always find it (model naming variations, I assume).




  • If it already exists, vote that one up so we see what the most popular answer is, rather than duplicating an existing entry.


  • If you see a duplicate, vote it down so the top entries have only one of each model listed.


  • If you have interesting or additional information to add, use a comment or edit the original entry rather than creating a duplicate.




Find the answer here

Friday, February 26, 2010

Programmer - PCRE: Lazy and Greedy at the same time (Possessive Quantifiers)

Programmer Question

I am trying to match a series of text strings with PCRE on PHP, and am having trouble getting all the matches in between the first and second. Another problem I have is matching pairs.



If anyone wonders why on Earth I would want to do this, it's because of Doc Comments. Oh, how I wish Zend would make native/plugin functions to read Doc Comments from a PHP file...



The following example (plain) text will be used for each problem. It will always be pure PHP code, with only one opening tag at the beginning of the file, no closing. You can assume that the syntax will always be correct.



<?php
class someClass extends someExample
{
function doSomething($someArg = 'someValue')
{
// Nested code blocks...
if($boolTest){}
}
private function killFurbies(){}
protected function runSomething(){}
}

abstract
class anotherClass
{
public function __construct(){}
abstract function saveTheWhales();
}

function globalFunc(){}


Problem One



Trying to match all methods in a class; my RegEx does not find the method killFurbies() at all. Letting it be greedy means it only matches the last method in a class, and letting it be lazy means it only matches the first method.



$part = '.*';  // Greedy
$part = '.*?'; // Lazy

$regex = '%class(?:\\n|\\r|\\s)+([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)'
. '.*?\{' . $part .'(?:(public|protected|private)(?:\\n|\\r|\\s)+)?'
. 'function(?:\\n|\\r|\\s)+([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff'
. ']*)(?:\\n|\\r|\\s)*\\(%ms';

preg_match_all($regex, file_get_contents(__EXAMPLE__), $matches, PREG_SET_ORDER);
var_dump($matches);


Results in:



// Lazy:
array(2) {
[0]=>
array(4) {
[0]=>
// Omitted.
[1]=>
string(9) "someClass"
[2]=>
string(0) ""
[3]=>
string(11) "doSomething"
}
[1]=>
array(4) {
[0]=>
// Omitted.
[1]=>
string(12) "anotherClass"
[2]=>
string(6) "public"
[3]=>
string(11) "__construct"
}
}

// Greedy:
array(2) {
[0]=>
array(4) {
[0]=>
// Omitted.
[1]=>
string(9) "someClass"
[2]=>
string(0) ""
[3]=>
string(13) "saveTheWhales"
}
[1]=>
array(4) {
[0]=>
// Omitted.
[1]=>
string(12) "anotherClass"
[2]=>
string(0) ""
[3]=>
string(13) "saveTheWhales"
}
}


How do I match all? :S



Problem Two



Of course, searching for Doc Comments on methods in a class means I have to know which character is the closing brace for the class the RegEx is running on. Is there anyway to count how many opening braces PCRE encounters ($n), and when it encounters the $n'th closing brace, to stop searching. At the moment, it will keep searching and find the methods inside classes defined later in the file, and also functions in the global scope. I'm guessing this has something to do recursion or subpatterns.



Any help would be gratefully appreciated, as I already feel this question is ridiculous as I'm typing it out. Anyone attempting to answer a question like this is braver than me!



Thanks, mniz.



Find the answer here

Programmer - mathematica printing with multiple indices

Programmer Question

What do I need to do to make Pa[p] an ASN[P] to come out as numeric values.
Abreviated code is given below. roots, PA2[p] and ANS2[p] are created
using an i index.



MMA CODE: ********



Clear[x, y, p];
x := BinomialDistribution[n1, p];
y := BinomialDistribution[n2, p];

Pa[p_] := CDF[x, c1] + Sum[PDF[x, j]*CDF[y, c2 - j], {j, c1 + 1, c2}];
Print[TableForm[Table[{p, Pa[p]}, {p, .01, .1, .01}],
TableHeadings -> {None, {"p", "Pa[p]"}}]];
ASN[p_] := n1*1 + n2* CDF[x, c2] - CDF[x, c1];
Print[TableForm[Table[{p, ASN[p]}, {p, .01, .1, .01}],
TableHeadings -> {None, {"p", "ASN[p]"}}]];

p = {.01, .02, .03, .04, .05, .06, .07, .08, .09, .1};
Print[TableForm[
Table[ {r2[[i]], p[[i]], Pa[[i]], ASN[[i]], Pa2[[i]],ASN2[[i]] },
{i, 1,10,1}],
TableHeadings -> {None, {"roots", "p", "Pa[p]","ASN[p]","PA2[p]","ASN2[p]"} } ]];


MMA OUTPUT: *******



p   Pa[p]
0.01 0.980277
0.02 0.817478
0.03 0.555413
0.04 0.327922
0.05 0.177956
0.06 0.0916007
0.07 0.0453877
0.08 0.0217882
0.09 0.0101644
0.1 0.00461704

p ASN[p]
0.01 178.866
0.02 176.136
0.03 167.438
0.04 153.427
0.05 137.505
0.06 122.884
0.07 111.274
0.08 102.986
0.09 97.5368
0.1 94.1847

roots p Pa[p] ASN[p] PA2[p] ASN2[p]
1.17508 0.01 Pa$1660[[1]] ASN$1660[[1]] 0.977398 64.4721
0.472821 0.02 Pa$1660[[2]] ASN$1660[[2]] 0.840606 84.1587
0.000638883 0.03 Pa$1660[[3]] ASN$1660[[3]] 0.583404 89.3915


-0.3770350 .04 Pa$1660[[4]] ASN$1660[[4]] 0.340761 79.3716
-0.7039350 .05 Pa$1660[[5]] ASN$1660[[5]] 0.185355 65.0975
-1. 0.06 Pa$1660[[6]] ASN$1660[[6]] 0.1 52.7007
-1.27609 0.07 Pa$1660[[7]] ASN$1660[[7]] 0.0547126 43.2261
-1.5388 0.08 Pa$1660[[8]] ASN$1660[[8]] 0.0304681 36.1651
-1.79248 0.09 Pa$1660[[9]] ASN$1660[[9]] 0.017227 30.8583
-2.04012 0.1 Pa$1660[[10]] ASN$1660[[10]] 0.00985218 26.7938



Find the answer here

Programmer - Winforms databinding with interface inheritance

Programmer Question

I need someone to confirm what I am seeing before I may a change to the domain of the application because of this issue. The issue is that when databinding against interfaces that inherit from one another, you can not see the properties on the base interfaces.



I am working on a WinForms application that uses databinding. This is in .net3.5 and no I can not use wpf.



Anyways, I have a setup something like this.



public interface IClassOne
{
string Prop1 { get; set; }
}

public interface IClassTwo : IClassOne
{
string Prop2 { get; set; }
}

public abstract class ClassOne : IClassOne
{
public string Prop1 { get; set; }
}

public class ClassTwo : ClassOne, IClassTwo
{
public string Prop2 { get; set; }
}


The base class would hold common properties and logic. The base interface would have those common properties on it so they would have to be implemented on each concrete implementation.



If I was databinding to my class structure above, I would be binding to IClassTwo. The problem is when I databind to IClassTwo, I can not see Prop1 in any of the designer operations for WinForms. Even if I get around that limitation and get a control to be bound to Prop1, it does not work.



However if I bind two ClassTwo, then databinding works.



I do not want to deal with the concrete classes because that would make using mocks and testing too hard. I also do not want to put everything on IClassTwo because I would have to repeat code when I make another concrete implementation.



What I need to know is if this truly doesn't work. If you know why, that would be a bonus.



Thank you
Tony



Find the answer here

Programmer - Log runtime Exceptions in Java using log4j

Programmer Question

Hi,
I am currently building an application using Tomcat, Spring, JAVA. I am using Log4J as my logging library. I currently am logging everything to a text file. One of the issues I'm having is that RuntimeExceptions are not being logged to any files. I was wondering if there was a way to log all RuntimeExceptions that maybe thrown to my application log file. If not is it possible to have it log to another log file? Is there a standard way to do this? If so is there a standard way to do this when running your application within Tomcat?



Thank you in advance for your help!



Find the answer here

Programmer - Good (non-code) interview questions for college intern candidates [closed]

Programmer Question


Possible Duplicates:

What's a good non-programming interview question when hiring a programmer?

C# - Programmer Challenge for Interviews - Programming to an Interface & Patterns






Next week I'm beginning several rounds of interviews for a company wide technical intern program. Many of these candidates are only sophomores or juniors and have little programming experience. They can do basic data structures, regurgitate algorithms and the like, but they have little or no professional coding experience in an enterprise environment.



So, given that fact, I try and ask questions that show a passion for computing and software development. Basically what I want to know is, do these people love the idea of being a software developer? I have a few questions that I always like asking to see if the candidate gets excited or passionate about, but I'm looking for more. I have some simple language agnostic coding questions too, but I'm not trying to focus on those. We're only going to have these people for three months so we really just want someone who is ready to jump in any try anything (while being appropriately cautious :)



Here are the questions I generally use:




  • Why did you pick computer science as a major? Why do you want to be a software developer?

  • What do you do in your spare time that relates to software development?

  • What is your favorite piece of software (or website) - why?

  • (Followup) What is one thing you'd change about your favorite piece of software?

  • What is your least favorite piece of software (or website) - why?

  • Tell me about your favorite software development project or assignment



Does anyone have any other questions they use quite a bit for this purpose? Like I said, I'm looking for passion (or dare I say nerdiness :) but I don't want to get too technical.



Update This question was closed as a duplicate. I don't feel as though the "duplicates" answered the specific question I was asking. Yes, they asked about non-technical interview questions, but I'm specifically wondering about intern recruiting. 20 plus responses seems to indicate that there are plenty of people willing to respond.



Find the answer here

Thursday, February 25, 2010

Programmer - what is the best way to convert html to postscript? in java

Programmer Question

hello
what is the best way ( if there is any ) in java to convert html with css2 support to
postscript file ?



Find the answer here

Programmer - Calling function in other Class not working

Programmer Question

Hey everyone, not sure what is going on here :(



Basically I have a function that is needs to tell 2 other classes to do something. It works for one of the classes: BigPlayButton, but not Background for some reason.



TabMenu.as Class function



Note: The function below WILL call the hitPlayCircle function in my BigPlayButton class, but I get an undefined property error for the Background switchTitle function.



private function thumbClick(e:MouseEvent = null):void
{
trace("YOU CLICKED THUMBNAIL: " + e.target.id);
trace("PLAY THIS VIDEO: " + tabData[tabID].video[e.target.id].@flv);
trace("THE VIDEO TITLE: " + tabData[tabID].video[e.target.id].@title);

newTitle = tabData[tabID].video[e.target.id].@title;
Background.instance.switchTitle(newTitle);

BigPlayButton.instance.playState = false;
BigPlayButton.instance.hitPlayCircle(); // Hide the big play button

vdp.setflvSource(tabData[tabID].video[e.target.id].@flv);
vdp.playNewVideo(tabData[tabID].video[e.target.id].@flv);
}





I've imported both classes so not sure what's going on :(
I did correctly set my static var instance variables.



public static var instance:Background; //<- in Background Class

public static var instance:BigPlayButton; // <- in BigPlayButton Class


And I have instance = this; in Both Classes as well...




The function inside my Background Class I'm trying to call from my TabMenu Class:



public function switchTitle(sentText):void
{
titleString = sentText;
vTitle.text = titleString;
}


Error Message (I always seem to get this error)



TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.touchstorm.TEN.ui::TabMenu/thumbClick()


Find the answer here

Programmer - pre tag- text overflows the box

Programmer Question

I have applied the following style to the pre tag
[code]pre {
[color=blue]background-color[/color]:[color=orange] #FFFFCC[/color]
[color=blue]border[/color]:[color=orange] 2px dashed #FF6666[/color]
[color=blue]padding-top[/color]:[color=orange] 7px[/color]
[color=blue]padding-bottom[/color]:[color=orange] 8px[/color]
[color=blue]padding-left[/color]:[color=orange] 10px[/color]
[color=blue]float[/color]:[color=orange] none[/color]
[color=blue]padding-right[/color]:[color=orange] 10px[/color]
[color=blue]margin[/color]:[color=orange] 10px[/color]
}[/code]



The text overflows the box.
When I applied the float:right property the box behaved as expected but in large screens the rest floated around the box naturally. Not happy.
I am new to css and html - I am sure there is a simple solution. Please help.
:(



Find the answer here

Programmer - Is it better to create a new object and return it or create the new object in the return statement?

Programmer Question

For example:



public Person newPerson() {
Person p = new Person("Bob", "Smith", 1112223333);
return p;
}


as opposed to:



public Person newPerson() {
return new Person("Bob", "Smith", 1112223333);
}


Is one more efficient than the other?



Find the answer here

Programmer - Comparing folder current state with saved prior state

Programmer Question

I want to make a winform application that tells you whenever you open it all the changes that have been made since last opening, and maybe record a log of it, such as:




  • File/folder creations

  • File/folder renamings

  • File/folder exclusions



I've figured i have to do three tasks:




  • Save the folder state (tree) in a
    reloadable format

  • Load this information back

  • Compare this information with current
    state gathered on-the-go

  • List changes, log and display them



I've come up with some ideas, what have you got to help me ?



(I'm using C#, vs 08 and .NET 3.5)



Find the answer here

Wednesday, February 24, 2010

Programmer - jQuery. Using json data on remote server fails.

Programmer Question

Hello,



I am working with json data together with jQuery. It works perfectly fine when using a local json file, but shows just a blank page when using a remote json file from another server (even when using a complete URL from my own server).



This works:



$.getJSON('9.json', function(data) {


Does does not work:



$.getJSON('http://beta.ambadoo.com/users/9.json', function(data) {


Does anyone know how to fix it?



Thanks!

Programmer - Objective-C: Calling Methods Problems

Programmer Question

hi, i got a xib called RootViewController and a xib called Test, i got a method in RootViewController.m that need to show something in a label in Test's view xib...
I tryed different things and they alll don't work. plz help, thx.

Programmer - Fastest Way to Delete a Line from Large File in Python

Programmer Question

Hi all,



I am working with a very large (~11GB) text file. Using an conventional text editor to make changes to the data is not possible based on system resource constraints. I need to remove a specific line - in its entirety - from the file. What is the fastest (in terms of execution time) way to do this in Python?



Thanks,



-aj

Programmer - accessing DOM trees in frames/iframes using mshtml in C#

Programmer Question

hi, I have to programmically load a web page that has frames in it and then grab the DOM tree inside those frames. I have tried quite some time, but i am still struck at the code. here it is,



        void grabDOMTest()
{
mshtml.HTMLDocument htmldoc = new mshtml.HTMLDocument();
IHTMLDocument2 htmldoc2 = (IHTMLDocument2)htmldoc;
htmldoc2.writeln("<html>");
htmldoc2.writeln("<frameset cols='25%,50%,25%'>");
htmldoc2.writeln("<frame src='about:blank'>");
htmldoc2.writeln("<frame src='about:blank'>");
htmldoc2.writeln("<frame src='about:blank'>");
htmldoc2.writeln("</frameset>");
htmldoc2.writeln("</html>");
htmldoc2.close();

mshtml.FramesCollection frames = htmldoc2.frames;
object o = null;
for (int i = 0; i <= frames.length - 1; i++)
{
o = i;
try
{
mshtml.IHTMLWindow2 fwin = (mshtml.IHTMLWindow2)frames.item(ref o); //COMException,HRESULT E_FAIL
}
catch (COMException e)
{
.....
}

//do sth
}
}


i keep getting exceptions in the line with frames.item.
how can i get it to work? or is there any alternative approach?

Programmer - Why use JOIN rather than inner queries

Programmer Question

I find myself unwilling to push to using JOIN when I can easily solve the same problem by using an inner query:



e.g.



SELECT COLUMN1, ( SELECT COLUMN1 FROM TABLE2 WHERE TABLE2.ID = TABLE1.TABLE2ID ) AS COLUMN2 FROM TABLE1;



My question is, is this a bad programming practice? I find it easier to read and maintain as opposed to a join.



UPDATE



I want to add that there's some great feedback in here which in essence is pushing be back to using JOIN. I am finding myself less and less involved with using TSQL directly these days as of a result of ORM solutions (LINQ to SQL, NHibernate, etc.), but when I do it's things like correlated subqueries which I find are easier to type out linearly.

Tuesday, February 23, 2010

Programmer - jQuery how to execute event only on the inner element

Programmer Question

Is there is a smooth way to only let the inner element of a listitem
do something?
I read something here that using live complicates things.



Summation:



I have list elements that can contain a elements with a certain class.



The inner a elements are bound to a live click event handler.
The list items themselves have also a click event handler.



Something like this



<li>some text<a class="someClassName">some text</a></li>


with the handler for the a tags



$('#somelist li a').live("click", function(e)

Programmer - Where can I legally declare a variable in C99?

Programmer Question

When I was first introduced to C I was told to always declare my variables at the top of the function. Now that I have a strong grasp of the language I am focusing my efforts on coding style, particularly limiting the scope of my variables. I have read this SO question on the benefits to limiting the scope and I came across an interesting example. Apparently, C99 allows you to do this...



for (int i = 0; i < 10; i++)
{
puts("hello");
}


I had always thought that a variables scope was limited by the inner-most curly brackets { }, but in the above example int i appears to be limited in scope by the for-loop's parentheses ( ) and the compiler will promptly give you an error if you try to use i inside the for-loop body.



I tried to extend the above example with fgets() to do what I thought was something similar but both of these gave me a syntax error.



fgets(char fpath[80], 80, stdin); See Note*



fgets(char* fpath = malloc(80), 80, stdin);



So just where exactly is it legal to declare variables in C99? Was the for-loop example an exception to the rule? Does this apply to while and do while loops as well?



Note*: I'm not even sure this would be syntactically correct even if I could declare the char array there since fgets() is looking for pointer to char not pointer to array 80 of char. This is why I tried the malloc() version.

Programmer - How do you communicate effectively in a small development team?

Programmer Question

I work in a small team (4-5 developers) on a single project. Every member of our team is developing a different functionality from our project and their are highly independent. In fact, some members use technologies that other member doesn't know about. It's still a single project and there a lot of common business logic in it.



In addition, most of the members are completely unaware what and how the others are doing. Somehow, we manage to avoid code replication (credits for our team-leader, but even he is not completely aware what is happening). I wonder, what is a good practice to keep the whole team on the track what is going on. For example if some one from the team quits or is missing when an important fix should be maid - it's difficult for the others to handle.



We have a policy, for conducting code-reviews, but only the team-leaders and one member of the team participates in it. The other "regular" members do not take part, there.



Also, we have a "newslist" for checkin-s committed in the source control by our members, but this seems too boring to deal with and it looks like nobody is taking time to read what others have just committed (and it's not effective, to be fair).



So, I wonder what is a good practice in this matter. What experience do you have? Is there a solution at all ?



Best Regards!

Programmer - Pareto chart SS 2005

Programmer Question

I am trying to create a Pareto Chart in SS 2005. I created a chart, but having difficulties in trying to get my cumulative(line) to display. I listed my values below.



=SUM(Fields!Total_SR.Value)/MAX(Fields!Total_SR.Value,
"SeriesGroup")*0.75



cumulative value:



=RunningValue(Fields!Total_SR,
Sum, "SeriesGroup") / Sum(Fields!Total_SR, "SeriesGroup")



I am able to get the Bar to display.



This is the instructions I used:



http://msdn.microsoft.com/en-us/library/aa964128(SQL.90).aspx

Programmer - Tools to find included headers which are unused?

Programmer Question

I know PC-Lint can tell you about headers which are included but not used. Are there any other tools that can do this, preferably on linux?



We have a large codebase that through the last 15 years has seen plenty of functionality move around, but rarely do the leftover #include directives get removed when functionality moves from one implementation file to another, leaving us with a pretty good mess by this point. I can obviously do the painstaking thing of removing all the #include directives and letting the compiler tell me which ones to reinclude, but I'd rather solve the problem in reverse - find the unused ones - rather than rebuilding a list of used ones.

Monday, February 22, 2010

Programmer - How to immediately exit a Windows Form application?

Programmer Question

In our app, we have a quite extensive exception handling mechanism. At some point in our error handling logic, we want to terminate the application -- right at this point with no further code execution. Our current code use Environment.Exit() to do that. After a call to Environment.Exit(), some code is still executed. For instance, the GC may execute the finalizer of some objects (and that causes a problem in our case). We don't want that to happen. Is there a way to really kill our own process (a win32 API call maybe)? Of course we don't want the end-user to see the Windows dialog that appears when a program crashes...

Programmer - How do you trigger an event across classes?

Programmer Question

I am writing a Class Library that will be used by other applications. I am writing it in C#.NET. I am having a problem with triggering events across classes. Here is what I need to do...



public class ClassLibrary
{
public event EventHandler DeviceAttached;

public ClassLibrary()
{
// do some stuff
OtherClass.Start();
}
}

public class OtherClass : Form
{
public Start()
{
// do things here to initialize receiving messages
}

protected override void WndProc (ref message m)
{
if (....)
{
// THIS IS WHERE I WANT TO TRIGGER THE DEVICE ATTACHED EVENT IN ClassLibrary
// I can't seem to access the eventhandler here to trigger it.
// How do I do it?

}
base.WndProc(ref m);
}

}


Then in the application that is using the class library I will do this...



public class ClientApplication
{
void main()
{
ClassLibrary myCL = new ClassLibrary();
myCL.DeviceAttached += new EventHandler(myCl_deviceAttached);
}

void myCl_deviceAttached(object sender, EventArgs e)
{
//do stuff...
}
}

Programmer - Is MS SQL 'MONEY' data type a decimal floating point or binary floating point?

Programmer Question

I couldn't find anything that rejects or confirms whether MS SQL 'MONEY' data type is a decimal floating point or binary floating point.



In the description it says that MONEY type range is from -2^63 to 2^63 - 1 so this kind of implies that it should be a binary floating point.



But on this page it lists MONEY as "exact" numeric. Which kind of suggests that MONEY might be a decimal floating point (otherwise how is it exact? or what is the definition of exact?)



Then if MONEY is a decimal floating point, then what is the difference between MONEY and DECIMAL(19,4) ?

Programmer - What would I lose by abandoning the standard EventHandler pattern in .NET?

Programmer Question

There's a standard pattern for events in .NET - they use a delegate type that takes a plain object called sender and then the actual "payload" in a second parameter, which should be derived from EventArgs.



The rationale for the second parameter being derived from EventArgs seems pretty clear (see the .NET Framework Standard Library Annotated Reference). It is intended to ensure binary compatibility between event sinks and sources as the software evolves. For every event, even if it only has one argument, we derive a custom event arguments class that has a single property containing that argument, so that way we retain the ability to add more properties to the payload in future versions without breaking existing client code. Very important in an ecosystem of independently-developed components.



But I find that the same goes for zero arguments. This means that if I have an event that has no arguments in my first version, and I write:



public event EventHandler Click;


... then I'm doing it wrong. If I change the delegate type in the future to a new class as its payload:



public class ClickEventArgs : EventArgs { ...


... I will break binary compatibility with my clients. The client ends up bound to a specific overload of an internal method add_Click that takes EventHandler, and if I change the delegate type then they can't find that overload, so there's a MissingMethodException.



Okay, so what if I use the handy generic version?



public EventHandler<EventArgs> Click;


No, still wrong, because an EventHandler<ClickEventArgs> is not an EventHandler<EventArgs>.



So to get the benefit of EventArgs, you have to derive from it, rather than using it directly as is. If you don't, you may as well not be using it (it seems to me).



Then there's the first argument, sender. It seems to me like a recipe for unholy coupling. An event firing is essentially a function call. Should the function, generally speaking, have the ability to dig back through the stack and find out who the caller was, and adjust its behaviour accordingly? Should we mandate that interfaces should look like this?



public interface IFoo
{
void Bar(object caller, int actualArg1, ...);
}


After all, the implementor of Bar might want to know who the caller was, so they can query for additional information! I hope you're puking by now. Why should it be any different for events?



So even if I am prepared to take the pain of making a standalone EventArgs-derived class for every event I declare, just to make it worth my while using EventArgs at all, I definitely would prefer to drop the object sender argument.



Visual Studio's autocompletion feature doesn't seem to care what delegate you use for an event - you can type += [hit Space, Return] and it writes a handler method for you that matches whatever delegate it happens to be.



So what value would I lose by deviating from the standard pattern?



As a bonus question, will C#/CLR 4.0 do anything to change this, perhaps via contravariance in delegates? I attempted to investigate this but hit another problem. I originally included this aspect of the question in that other question, but it caused confusion there. And it seems a bit much to split this up into a total of three questions...



Update:



Turns out I was right to wonder about the effects of contravariance on this whole issue!



As noted elsewhere, the new compiler rules leave a hole in the type system that blows up at runtime. The hole has effectively been plugged by defining EventHandler<T> differently to Action<T>.



So for events, to avoid that type hole you should not use Action<T>. That doesn't mean you have to use EventHandler<TEventArgs>; it just means that if you use a generic delegate type, don't pick one that is enabled for contravariance.

Programmer - PHP var_dump array

Programmer Question

array(14) {
[0]=>
string(1) "1"
["id"]=>
string(1) "1"
[1]=>
string(7) "myUserName"
["UserID"]=>
string(7) "myUserName"
[2]=>
string(10) "myPassword"
["passwordID"]=>
string(10) "myPassword"
[3]=>
string(24) "myEmail@domain.com"
["emailAddress"]=>
string(24) "myEmail@domain.com"
[4]=>
string(7) "myFirstName"
["firstName"]=>
string(7) "myFirstName"
[5]=>
string(8) "myLastName"
["lastName"]=>
string(8) "myLastName"
[6]=>
string(1) "1"
["active"]=>
string(1) "1"
}


how do i access the contents of this array using PHP?



the above was a var_dump($info)

Sunday, February 21, 2010

Programmer - Getting two tables in LaTeX to have the same (right-aligned) column width

Programmer Question

I have two very short and consecutive sections (for a CV), each containing a small table:



\section{Work Experience}

\begin{tabular}{r|p{11cm}}
Current & Your job at Your Company, Town \\
Jan 2009 & What your company does \\
& A description of what you do\\
\multicolumn{2}{c}{}\
\end{tabular}

\section{Education}

\begin{tabular}{r|p{11cm}}
Slightly wider first column & University, Town \\
Jan 2009 & Thesis subject \\
& A description of what you did\\
\multicolumn{2}{c}{}\
\end{tabular}


So each table has two columns: The first containing the period, aligned to the right. The second: some more info with a certain width, top (and left) aligned.



The problem is that the width of the left column in the two tables is different, and doesn't look nice since the sections (therefore tables) are consecutive and in one page. I cannot give r a width like p:



\begin{tabular}{r{11cm}|p{11cm}}


Does not work. How can I get the widths of the first columns of the two tables the same length while also having them right aligned?



EDIT Thanks for the answers guys, they all work for me so I upvoted all of them, and accepted the one that appealed to me the most (and most upvoted), since you don't have to specify the \hfill in each row. However if you don't want to use the array package for any reason then the other solutions are also great.

Programmer - Qt widget disobeys drop in Windows

Programmer Question

I have a Qt 4.6 based app that is compiled on both a Linux machine and Windows machine. I have two widgets:
1. allowdrop=false and drop type is internal only
2. allowdrop=false and drop type is no drag and drop



On the linux machine, dragging the first control's items to seconds does nothing and even shows the "no" symbol for not allowed to drop. On the Windows machine, everything except the second widget disallows drops. On Windows, when dragging the firsts' object to second, it allows the drag/drop and then crashes the program due to that move supposed to be blocked.



I'm guessing this is a QT bug, but is there something I can do short of filing a bug report that will make it behave on Windows?

Programmer - Bash and Mac OS X, open application in Space N

Programmer Question

Hi,



I wonder if it is possible in bash for OSX to create a script for which we give as input the application name and a number N, so this app gets opened in the Space's space number N.



I would like with this to create a meta-script, so when the computer boots and after login, on each space I get different apps, and important, I can change this in the script file, and not through mac os x Space's preferences



Thanks

Programmer - What is the differrence between Int32 and UInt32?

Programmer Question

What is the difference between Int32 and UInt32?



If they are the same with capacity range capabilities, the question is for what reason UInt32 was created? When should I use UInt32 instead of Int32?

Programmer - Has anyone used Robotium or Calculon for testing Android apps?

Programmer Question

Has anyone used Robotium or Calculon for testing Android apps? Are they useful? Any recommendations on which is better?

Programmer - Is there any Android game framework ready to use

Programmer Question

Do you know any tile based game framework for android like HGE for PC or at least some good examples of tile based engine for Android

Programmer - iPhone - Keyboard hides TextField

Programmer Question

I am using UITextField to receive user inputs. However, since my textfields are towards the middle/bottom of the nib, it gets hidden when the keyboard pops up. Is there any way sort of slide it along with the keyboard so that it's on the top of the keyboard during selection? Also, since I am also using the numberpad, is there an easy way to include a done button somewhere?



Thanks for the help.

Programmer - fluent nhibernate manytomany mapping

Programmer Question

Hi guys,
I am trying to map these entities
Messages table fields are Id generated Id,SentFrom int, sentTo int
where Sentfrom and sentTo are linked to the users table
I also have a linker table
MessageUser table with userId and MessageId



CREATE TABLE [dbo].[MessageUser](
[MessageId] [int] NOT NULL,
[UserId] [int] NOT NULL,


CONSTRAINT [PK_MessageUser] PRIMARY KEY CLUSTERED
(
[MessageId] ASC,
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]



GO



ALTER TABLE [dbo].[MessageUser] WITH CHECK ADD CONSTRAINT [FK_MessageUser_Messages] FOREIGN KEY([MessageId])
REFERENCES [dbo].[Messages] ([Id])
GO
ALTER TABLE [dbo].[MessageUser] CHECK CONSTRAINT [FK_MessageUser_Messages]
GO
ALTER TABLE [dbo].[MessageUser] WITH CHECK ADD CONSTRAINT [FK_MessageUser_Users] FOREIGN KEY([UserId])
REFERENCES [dbo].[Users] ([Id])
GO
ALTER TABLE [dbo].[MessageUser] CHECK CONSTRAINT [FK_MessageUser_Users]
GO



I think the db design is Ok but I can't figure out the best way to map the entities
my ultimate goal to be able to get the Messages sentTo and message sentFrom using the user and the message entities.
Any idea how to achieve that goal.



Thanks

Programmer - How do I receive notification of a new window opening?

Programmer Question

I want to respond to a certain type of new window being opened by an external application. I have some experience finding applications and windows currently open (system wide) using some of the carbon functionality, so could theoretically just check every few seconds. This would require getting a list of all open windows and checking it against some list I would have to maintain, and feels very clunky.



How can I get a simple, clean notification when a new window is launched? Should I use the accessibility API? If so, what specifically am I looking for?

Programmer - read the last line of a fifo

Programmer Question

Here is the situation : Some process writes lines into a fifo file (created with mkfifo). At some point in my program, I want to read the last line in the fifo, and discard all the others. The procedure may block, only if there is less than one line in the fifo.



I can't come up with a clean way to do this, any ideas ?



EDIT : The writing process will never stop writing lines into the fifo, What I mean by the last line is the last by the time I read the fifo. It is not necessarily followed by a EOF.

Programmer - SQL join against date ranges?

Programmer Question

Consider two tables:



Transactions, with amounts in a foreign currency:



     Date  Amount
========= =======
1/2/2009 1500
2/4/2009 2300
3/15/2009 300
4/17/2009 2200
etc.


ExchangeRates, with the value of the primary currency (let's say dollars) in the foreign currency:



     Date    Rate
========= =======
2/1/2009 40.1
3/1/2009 41.0
4/1/2009 38.5
5/1/2009 42.7
etc.


Exchange rates can be entered for arbitrary dates - the user could enter them on a daily basis, weekly basis, monthly basis, or at irregular intervals.



In order to translate the foreign amounts to dollars, I need to respect these rules:



A. If possible, use the most recent previous rate; so the transaction on 2/4/2009 uses the rate for 2/1/2009, and the transaction on 3/15/2009 uses the rate for 3/1/2009.



B. If there isn't a rate defined for a previous date, use the earliest rate available. So the transaction on 1/2/2009 uses the rate for 2/1/2009, since there isn't an earlier rate defined.



This works...



Select 
t.Date,
t.Amount,
ConvertedAmount=(
Select Top 1
t.Amount/ex.Rate
From ExchangeRates ex
Where t.Date > ex.Date
Order by ex.Date desc
)
From Transactions t


... but (1) it seems like a join would be more efficient & elegant, and (2) it doesn't deal with Rule B above.



Is there an alternative to using the subquery to find the appropriate rate? And is there an elegant way to handle Rule B, without tying myself in knots?

Programmer - Php retreive input value

Programmer Question

Hello again,
Would anyone perhaps know how to get the value of a specific element in an HTML document with PHP? What I'm doing right now is using file_get_contents to pull up the HTML code from another website, and on that website there is a textarea:



<textarea id="body" name="body" rows="12" cols="75" tabindex="1">Hello World!</textarea>


What I want to do is have my script do the file_get_contents and just pull out the "Hello World!" from the textarea. Is that possible? Sorry for bugging you guys, again, you give such helpful advice :].

Programmer - Getting of raw response http header

Programmer Question

Is there any way to get raw response http header?



The getHeaderField() method doesn't work for me, because server spits multiple 'Set-Cookie' and some of them get lost.

Programmer - What does O(log n) mean exactly?

Programmer Question

I am currently learning about Big O Notation running times and amortized times. I understand the notion of O(n) linear time, meaning that the size of the input affects the growth of the algorithm proportionally...and the same goes for, for example, quadratic time O(n^2) etc..even algorithms, such as permutation generators, with O(n!) times, that grow by factorials.



For example, the following function is O(n) because the algorithm grows in proportion to its input n:



f(int n) {
int i;
for (i = 0; i < n; ++i)
printf("%d", i);
}


Similarly, if there was a nested loop, the time would be O(n^2).



But what exactly is O(log n)? For example, what does it mean to say that the height of a complete binary tree is O(log n)?



I do know (maybe not in great detail) what Logarithm is, in the sense that: log10 100 = 2, but I cannot understand how to identify a function with a log time.

Programmer - Can I use a C# dll with unsafe code in VB.NET?

Programmer Question

There is an FastBitmap class for C#, that lets you acces and modify pixel information of am bitmap. I have already used it in some C# project, but I need it now in VB.NET.
The problem is that that class uses unsafe code, that is not supported in VB.NET.



The question is. Can I compile the FastBitmap class in a dll and use it in VB.NET?



[EDIT]
Or is there some library that can be used to modfy pixel data in VB.NET?

Programmer - String array/list in maple?

Programmer Question

What is the equivalent of a string array/list in Maple? I can't see to figure out and Google has failed me.



I tried the following, but it didn't work. I received an error saying unexpected ,.



myArray := ['string1','string2'];

Programmer - How do I get selected background color from SecondView to pass to FirstView?

Programmer Question

I am going insane! This is a simple app with two Views. FirstView is a text field with info button to flip to SecondView. In SecondView I have 6 buttons for background color choice. When button is pushed the color of background changes perfectly but cannot make it also change background color for FirstView. Any help would be GREAT! Thanks!

Programmer - Specifying python interpreter from virtualenv in emacs

Programmer Question

Today I've been trying to bring more of the python related modes into
my emacs configuration but I haven't had much luck.



First what I've noticed is that depending on how emacs is
launched(terminal vs from the desktop), the interpreter it decides to
use is different.




  • launched from kde menu: M-! which python --> /usr/bin/python


  • launched from terminal: M-! which python -->~/local/bin/python




I can kind of accept this since I have my .bashrc appending
~/local/bin to the path and I guess kde ignores that by default.I can
work around this, however what I don't understand is then if I
activate a virtualenv, I would expect M-! which python to point to
~/project.env/bin/python however it still points to ~/local/bin/python



Thus when I M-x py-shell, I get ~/local/bin/python so if I try to
py-execute-buffer on a module that resides in a package in the
virtualenv, py-shell will complain about not knowing about modules
also in the virtualenv.



Setting py-python-command to ~/project.env/bin/python seems to have no
effect after everything is loaded.



So I guess the overall crux of my question is, how does one get all
the python related emacs stuff pointing at the right interpreter?

Programmer - How to rewrite a stream of HTML tokens into a new document?

Programmer Question

Suppose I have an HTML document that I have tokenized, how could I transform it into a new document or apply some other transformations?



For example, suppose I have this HTML:



<html>
<body>
<p><a href="/foo">text</a></p>
<p>Hello <span class="green">world</span></p>
</body>
</html>


What I have currently written is a tokenizer that outputs a stream of tokens. For this document they would be (written in pseudo code):



TAG_OPEN[html] TAG_OPEN[body] TAG_OPEN[p] TAG_OPEN[a] TAG_ATTRIBUTE[href]
TAG_ATTRIBUTE_VALUE[/foo] TEXT[text] TAG_CLOSE[a] TAG_CLOSE[p]
TAG_OPEN[p] TEXT[Hello] TAG_OPEN[span] TAG_ATTRIBUTE[class]
TAG_ATTRIBUTE_VALUE[green] TEXT[world] TAG_CLOSE[span] TAG_CLOSE[p]
TAG_CLOSE[body] TAG_CLOSE[html]


But now I don't have any idea how could I use this stream to create some transformations.



For example, I would like to rewrite TAG_ATTRIBUTE_VALUE[/foo] in TAG_OPEN[a] TAG_ATTRIBUTE[href] to something else.



Another transformation I would like to do is make it output TAG_ATTRIBUTE[href] attributes after the TAG_OPEN[a] in parenthesis, for example,



<a href="/foo">text</a>


gets rewritten into



<a href="/foo">text</a>(/foo)


What is the general strategy for doing such transformations? There are many other transformations I would like to do, like stripping all tags and just leaving TEXT content, adding tags after some specific tags, etc.



Do I need to create the parse tree? I have never done it and don't know how to create a parse tree from a stream of tokens. Or can I do it somehow else?



Any suggestions are welcome.



And one more thing - I would like to learn all this parsing myself, so I am not looking for a library!



Thanks beforehand, Boda Cydo

Programmer - C# application doesn't run on another computer

Programmer Question

I complied my C# windows forms application on Visual Studio 2008 with configuration "Release". When I try to run it on another computer, no windows are shown at all.
What can it be?

Saturday, February 20, 2010

Programmer - Hibernate HQL with interfaces

Programmer Question

According to this section of the Hibernate documentation I should be able to query any java class in HQL



http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-polymorphism



Unfortunately when I run this query...



"from Transaction trans where trans.envelopeId=:envelopeId"


I get the message "Transaction is not mapped [from Transaction trans where trans.envelopeId=:envelopeId]".



Transaction is an interface, I have to entity classes that implement it, I want on HQL query to return a Collection of type Transaction.

Programmer - What are the Best Practices For SQL Inserts on Large Scale in reference to ad impressions?

Programmer Question

I am working on a site where I will need to be able to track ad impressions. My environment is ASP.Net with IIS using a SQL Server DMBS and potentially Memcached so that there are not as many trips to the database. I must also think about scalability as I am hoping that this application becoming a global phenom (keeping my fingers crossed and working my ass off)! So here is the situation:




  • My Customers will pay X amount for Y Ad impressions

  • These ad impressions (right now, only text ads) will then be shown on a specific page.

  • The page is served from Memcached, lessening the trips to the DB

  • When the ad is shown, there needs to be a "+1" tick added to the impression count for the database



So the dilemma is this: I need to be able to add that "+1" tick mark to each ad impression counter BUT I cannot run that SQL statement every time that ad is loaded. I need to somehow store that "+1" impression count in the session (or elsewhere) and then run a batch every X minutes, hours, or day.



Please keep in mind that scalability is a huge factor here. Any advice that you all have would be greatly appreciated.

Programmer - Rails image_tag not closing image tag

Programmer Question

On a rails project I am using the image_tag to generate my image html elements.



<%= image_tag("test.jpg", :alt => "test image") %>


is generating



<img src="test.jpg" alt="test image">


This is happening throughout my entire rails project.



Is there a setting somewhere that someone else set that is causing this?
How can I get rails to always close the image tag?

Programmer - Hidden Features of JavaScript?

Programmer Question

What "Hidden Features" of JavaScript do you think every programmer should know?



After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.





Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.

Programmer - Is it possible to do computation before super() in the constructor?

Programmer Question

Given that I have a class Base that has a single argument constructor with a TextBox object as it's argument. If I have a class Simple of the following form:



public class Simple extends Base {
public Simple(){
TextBox t = new TextBox();
super(t);
//wouldn't it be nice if I could do things with t down here?
}
}


I will get a error telling me that the call to super must be the first call in a constructor. However, oddly enough, I can do this.



public class Simple extends Base {
public Simple(){
super(new TextBox());
}
}


Why is it that this is permited, but the first example is not? I can understand needing to setup the subclass first, and perhaps not allowing object variables to be instantiated before the super-constructor is called. But t is clearly a method (local) variable, so why not allow it?



Is there a way to get around this limitation? Is there a good and safe way to hold variables to things you might construct BEFORE calling super but AFTER you have entered the constructor? Or, more generically, allowing for computation to be done before super is actually called, but within the constructor?



Thank you.

Programmer - "The resource cannot be found." ASP.NET MVC 2.0 RC and Visual Studio 2010 RC

Programmer Question

I opened a solution in Visual Studio 2010 RC that I previously created using Visual Studio 2008 and ASP.NET MVC 2.0 RC using the 3.5 framework. When I tested it I received a 404 error. I tried adding the default page as described in this post but got an invalid route error.



Anyone else ran into this?

Programmer - how to copy youtube annotations

Programmer Question

For example this video
How to Fix Bicycles : How to Tighten the Brakes on a Bicycle
http://www.youtube.com/watch?v=zqMDye2Jumg&NR=1&feature=fvwp



there are annotations, basically a transcript of what the expert says.
is there any way to copy those annotations?
transcribing by hand gets tedious

Programmer - Making a variable name a dynamic variable

Programmer Question

Hi There



I hope someone can help me with the following...



I have this code below it is written in classic asp and javascript...



I have this variable in the code below my2String1 how can I make this a dynamic variable like:




  • my2String1_1

  • my2String1_2

  • my2String1_3



I have a database value Recordset2.Fields.Item("article_no").Value which could be the dynamic value like:



my2String1_Recordset2.Fields.Item("article_no").Value (which should do the trick) but I am not sure how to implement it...



while((Repeat1__numRows-- != 0) && (!Recordset2.EOF)) { 
var my2String1 = ""+(Recordset2.Fields.Item("article_description").Value)+"";
my2String = my2String1;
var my2regexp = new RegExp(checkduplicates, "ig");
my2Array = my2String1.match(my2regexp);
my2length = my2Array.length;

for (i = 0; i < my2length; i++) {
my2Array[i] = '\''+my2Array[i]+'\'';
}

var arr = (myArray+my2Array).split(',');
var sorted_arr = arr.sort();
var results = [];

for (var i = 0; i < arr.length - 1; i += 1) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}

Repeat1__index++;
Recordset2.MoveNext();
}


If you have any ideas on how to solve this please help me

Programmer - Position Absolute Problems in Older IE

Programmer Question

.top_line {
background:#003466;
float:left;
height:107px;
width:100%;
}
.header_logo {
background:url("../images/header.png") top no-repeat;
position: absolute;
height:107px;
width:910px;
}
.page_wrapper {
margin:0px auto;
width:910px;
}

<div class="top_line"></div>
<div class="page_wrapper">
<div class="header_logo" align="center"></div>


The header image appears correctly in the background color on FF,Chrome, and newer versions of IE. However it appears below and to the right of the background-color bar on older versions of IE. How do I fix this?

Programmer - What is a good Java library for Parts-Of-Speech tagging?

Programmer Question

I'm looking for a good open source POS Tagger in Java. Here's what I have come up with so far.





Anybody got any recommendations?

Programmer - Ajax modal popup with repeater control

Programmer Question

hi



I created a repeater it has a column called comment on click of a comment icon, a AJAX Modal Popup comes out were user can enter the comments,



now the problem is AJAX Modalpopup comes out and disappear immediately , i dont know wats wrong in that



when i make targetcontrolid attribute of AJAX modal popup pointing to a button it works properly.but from the repeater item it does not.



i feel that this issue is related to okcontrolid and cancelcontrolid.



can anybody help me in sorting this out.

Programmer - How to return a generic iterator (independent of particular container)?

Programmer Question

I'd like to design a class Foo that stores various data of different types and returns iterators over them. It's supposed to be generic, so the user of Foo does not know how the data is stored (Foo could be using std::set or std::vector or whatever).



I'm tempted to write an interface like this:



class Foo {
class FooImpl;
FooImpl* impl_;
public:
const Iterator<std::string>& GetStrings() const;
const Iterator<int>& GetInts() const;
};


where Iterator is something like this (like iterators in .NET):



template<class T>
class Iterator {
public:
const T& Value() const = 0;
bool Done() const = 0;
void Next() = 0;
};


But I know that kind of iterator is not standard in C++, and it's better to use iterators the way the STL does, so you can use the STL algorithms on them.



How can I do that? (Do I need iterator_traits by any chance?)

Programmer - session variable object gets deleted

Programmer Question

I have made something like the following code:



protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["loginid"].ToString();
}

protected void delete_click(object sender, EventArgs e)
{
delete("mail1",Session["loginid"]);
}

private int delete(string mailid, string user)
{
System.IO.Directory.Delete(Server.MapPath(@"~\files\" + user + @"\" + mailid), true);
}


When i press the delete button, everything works fine and the folder gets delted.
but after that when page postbacks again then a
NullRefrenceException is raised at
Label1.Text = Session["loginid"].ToString();



why is it happening...??
Please help.

Programmer - C++ TCL (tree container library): How to traverse a tree from a node straight to root

Programmer Question

I am using this library to hold information about tree structure:



http://www.datasoftsolutions.net/tree_container_library/overview.php



Here is simplified version of my C++ code:



#include "tcl/sequential_tree.h"

// Node has some data which is not important now

typedef sequential_tree<Node> gametree_t;
typedef sequential_tree<Node>::iterator gametree_iter;

int main() {
gametree_t gametree;
gametree_iter gametree_it;

gametree_it = gametree.insert(Node(0));
gametree_it->insert(Node(1));
gametree_it->insert(Node(2));

gametree_it = gametree_it->insert(Node(3));
gametree_it->insert(Node(4));

gametree_it = gametree_it->insert(Node(5));
gametree_it->insert(Node(6));

return 1;
}


The tree looks like this



0
|_ 1
|_ 2
|_ 3
|_4
|_5
|_6


I am trying to make a function which given the Node(6) will traverse all the nodes leading to root i.e 6,5,3,0. This is my first project in C++ and I have trouble understanding pointers. Probably it is a few lines of C++ but I'm trying to do this for a couple of hours with no success. Any help will be appreciated.



something like this works but it must work with many levels not only with 4:



gametree_it->get()->get_value();
gametree_it->parent()->get()->get_value();
gametree_it->parent()->parent()->get()->get_value();
gametree_it->parent()->parent()->parent()->get()->get_value();

Programmer - Replacing Functionality of PIL (ImageDraw) in Google App Engine (GAE)

Programmer Question

So, Google App Engine doesn't look like it's going to include the Python Imaging Library anytime soon. There is an images api, but it's paltry, and inadequate for what I need.



I'm wondering what Python only (no C-extensions) there are that can replace the Image.paste and the ImageDraw modules. I don't want to write them myself, but that is an option. I'm also open to other solutions, such as "do the processing somewhere else, then call via api", if they're not too ugly. (For the record, the solution I just suggested seems pretty ugly to me.)



How have others gotten around this?



(I'm not wedded to GAE, just exploring, and this looks like a deal breaker for my app.)



Notes:



For me, crop, resize is not enough. In particular I need




  1. paste (replace part of an image with another.... can be faked with "compose")

  2. draw (for drawing gridlines, etc. Can be faked as well)

  3. text (write text on an image, much harder to fake, unless someone wants to correct me)

Programmer - which method is more efficient: set a class property; or return the result?

Programmer Question

Please consider this example. (PHP)



class Database{  
private $result;
private $conn;

function query($sql){
$result = $this->conn->query($sql);
// Set the Database::$result ?? Or return the value and avoid setting property?
return $result;
// $this->result = $result;
}
}


what are the advantages of both these methods? Where are they applicable?

Programmer - Is there a tool to convert php built-in functions to c implementation?

Programmer Question

I'm curious about how some built in functions are implemented,but it's very time consuming to look it up directly in the source,is there a tool that can automate this?



EDIT



Or is there a tool that can debug into the c code that's actually executed?

Programmer - How to send keys instead of characters to a process?

Programmer Question

System.Diagnostics.Process exposes a StreamWriter named StandardInput, which accepts only characters as far as I know.



But I need to send keystrokes as well, and some keystrokes don't map well to characters.



What should I do?

Programmer - Alternate method to kron

Programmer Question

I'm doing CDMA spreading in MATLAB. And I'm having an Out of Memory error in MATLAB despite upgrading my RAM, preallocating arrays, etc.



Is there an alternate method to kron (Kronecker tensor product) in MATLAB? Here is my code:



tempData = kron( Data, walsh); 


Data is a M by 1 matrix and walsh (spread code) is a 8 by 1 matrix.



My Data is comprises of real and imaginary parts, e.g.: 0.000 + 1.000i or 1.000 + 0.000i in double format.

Programmer - How can I tell if my Apache2+PHP uses CGI/FCGI?

Programmer Question

If I haven't setup FastCGI or mod_php, does that mean my vanilla Apache2 uses CGI for PHP?

Programmer - What's the best way to conditionally include an element in a list?

Programmer Question

Possible ways:




  1. Using push:



    my @list;  
    push @list, 'foo' if $foo;
    push @list, 'bar' if $bar;

  2. Using the conditional operator:



    my @list = (  
    $foo ? 'foo' : (),
    $bar ? 'bar' : (),
    );

  3. Using the x!! Boolean list squash operator:



    my @list = (  
    ('foo') x!! $foo,
    ('bar') x!! $bar,
    );



Which one is better and why?

Programmer - How to deal with IE errors

Programmer Question

I don't get any error in firefox or firebug, but yet in IE I get invalid argument for some reason, and I can't figure out what is the invalid argument, the javascript halts when "error" is discovered .. what can I do to debug it ?

Programmer - how to completely Hide website from search engines?

Programmer Question

Whats the best recommended way yo hide my staging website from search engines, i Googled it and found some says that i should put a metatag, and some said that i should put a text file inside my website directory, i want to know the standard way.



my current website is in asp.net, while i believe that it must be a common way for any website whatever its programming language.

Programmer - Wicket Component ID Best practive

Programmer Question

Hi,



Just started playing around with, how is everyone linking up their component ids ?



So far the most frequent error I've got are mismatches in component ids. For example,



In the html



...
<span wicket:id="messageID">message will be here</span>
...


and on the Java side



...
add(new Label("messageID", "If you see this message wicket is properly configured and running"));
...


I'm running on a maven/IntelliJ setup if that helps. Thanks!

Programmer - what method does navigationcontroller fire

Programmer Question

I have a navigationController and 3 View controllers. VC1 pushes VC2 and VC2 uses PresentModalViewController to display the 3rd VC




  1. When VC2 uses presentModalViewController to show VC3, is the VC3 actually pushed on the navigationcontroller stack?

  2. viewdidload of VC3 is called only 1st time. My goal is to show VC3 with a new imageView everytime. Where do I add the code to do that? viewdidappear and viewwillappear of VC3 is not fired either

Programmer - WM_MOUSELEAVE not being generated when left mouse button is held

Programmer Question

In my Win32 app, I don't get WM_MOUSELEAVE messages when I hold down the left mouse button and quickly move the mouse pointer out of the window. But If I, holding down the left mouse button, start from the inside of the window and move slowly past the window edge, it'll generate a WM_MOUSELEAVE.



If I don't hold the left mouse button, I get WM_MOUSELEAVE messages every time no matter how fast the mouse pointer moves off the window.



What's the difference? What can I do to handle both cases properly?



EDIT: If I left click and hold, move out of the window and then let go of the left mouse button I get the WM_MOUSELEAVE message. But it's way too late.

Programmer - Event not fired when copying entire object. How to do it?

Programmer Question

If I have a class that contains some properties and methods, and when a property is changed, it fires an event (in this case passing a string in the args):



public class Settings
{
public delegate void SettingsChangedHandler(object sender, string e);
public event SettingsChangedHandler SettingsChanged;

private string rootfolder;
public string RootFolder
{
get { return rootfolder; }
set
{
rootfolder = value;
if (SettingsChanged != null)
SettingsChanged(this, "ROOT_FOLDER");
}
}
}


If i have somewhere in my code:



public Settings SettingsInstance = new Settings();
SettingsInstance.SettingsChanged += new SettingsChangedHandler(SettingsInstance_SettingsChanged);
SettingsInstance = SomeOtherSettingsInstance;


I want all of the properties that have changed to fire their events.



How do I achieve something like this? Surely I don't have to copy them over one at a time?

Programmer - Writing a portable C program - which things to consider?

Programmer Question

For a project at university I need to extend an existing C application, which shall in the end run on a wide variety of commercial and non-commercial unix systems (FreeBSD, Solaris, AIX, etc.).



Which things do I have to consider when I want to write a C program which is most portable?

Programmer - usefull application in java

Programmer Question

I am a java devloper and i am doing java programming from my college days.
I know jsp,hibernate, core java.I have developed my project in java which was a web based project.
I want to devlop something as a hobby which will help people as well as i can get some money from it.But dont know what to devlop.
I like core java and dont like jsp too much.
I dont know swing.



Can any one suggeet me wht to do?

Programmer - Taking user input with pointers

Programmer Question

I'm trying to get better at using pointers, and not using array notation. So I have a function to read user input and return a pointer to that array. I can do it like this and it seems to work ok:



float *GetValues(float *p, size_t n) 
{

float input;
int i = 0;

if ((newPtr = (float *)malloc(n * sizeof(float))) == NULL) {
cout << "Not enough memory\n";
exit(EXIT_FAILURE);
}
cout << "Enter " << n << " float values separated by whitespace: \n";

while (scanf("%f", &input) == 1) {
p[i] = input;
i++;
cout << *p;
}
return p;
}


But then if I do this:



float *GetValues(float *p, size_t n) 
{
float *newPtr;
float input;

if ((newPtr = (float *)malloc(n * sizeof(float))) == NULL) {
cout << "Not enough memory\n";
exit(EXIT_FAILURE);
}
cout << "Enter " << n << " float values separated by whitespace: \n";

while (scanf("%f", &input) == 1) {
*newPtr++ = input;
}
return newPtr;
}


I get just 0s entered into p. Why is that?



Also, do I have to allocate memory here for an array of size n? I first tried it with the method above using pointers and not allocating memory but just set p = to input and I was getting garbage values. Thanks!



Edited: Sorry, I allocated a new ptr and was returning the wrong one like you said. I was just trying to input the numbers into my pointer and display it back on the screen to myself and wasn't paying attention to the return type and I was getting an output of 0 when I would cout << *newPtr.

Thursday, February 18, 2010

Programmer - python timer mystery

Programmer Question

Well, at least a mystery to me. Consider the following:



import time
import signal

def catcher(signum, _):
print "beat!"

signal.signal(signal.SIGALRM, catcher)
signal.setitimer(signal.ITIMER_REAL, 2, 2)

while True:
time.sleep(5)


Works as expected i.e. delivers a "beat!" message every 2 seconds. Next, no output is produced:



import time
import signal

def catcher(signum, _):
print "beat!"

signal.signal(signal.SIGVTALRM, catcher)
signal.setitimer(signal.ITIMER_VIRTUAL, 2, 2)

while True:
time.sleep(5)


Where is the issue?

Programmer - Silverlight stop page closing before being saved

Programmer Question

Here's a question for all you Silverlight guys.



In the old days for WinForms, if your user was creating/editing some information in a DialogBox, it was easy to detect the Window closing and if the data was dirty, ask if they wanted to save.



My question is, how do you approach this scenario in Silverlight where everything seems to be done in UserControls, which have no obvious way of knowing when the page is closing.



There must be some standard way of acheiving this?

Programmer - How to filter a listbox using a combobox

Programmer Question

How do I filter items in a listbox using a combobox using c# and windows forms?



the listbox contains files and the combobox needs to filter them by their extension



Please help I'm new to programming

Programmer - How do I determeine the source IP of a multicast packet in C#?

Programmer Question

I need to determine the IP of a machine that has sent me a multicast packet, so that I can respond to it via unicast.



I'm using the following csharp (.Net 3.5) code to receive the packets over a multicast connection (code has been edited for brevity, with error checking and irrelevant options removed):



IPEndPoint LocalHostIPEnd = new IPEndPoint(IPAddress.Any, 8623);
Socket UDPSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
UDPSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, 1);

UDPSocket.Bind(LocalHostIPEnd);

//Join the multicast group
UDPSocket.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse("225.2.2.6")));

IPEndPoint LocalIPEndPoint = new IPEndPoint(IPAddress.Any ,Target_Port);
EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;

// Create the state object.
StateObject state = new StateObject();
state.buffer.Initialize();
state.workSocket = UDPSocket;
state.id = "state0";
//Set up my callback
UDPSocket.BeginReceiveMessageFrom(
state.buffer,
0,
StateObject.BufferSize,
0,
ref LocalEndPoint,
new AsyncCallback(ReceiveCallback),
state);


And here's the callback, where I'm trying to get the source IP:



private void ReceiveCallback( IAsyncResult ar ) 
{
IPEndPoint LocalIPEndPoint = new IPEndPoint(IPAddress.Any, Target_Port);
EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;

// Read data from the remote device.
// The following code attempts to determine the IP of the sender,
// but instead gets the IP of the multicast group.
SocketFlags sFlags = new SocketFlags();
IPPacketInformation ipInf = new IPPacketInformation();

int bytesRead = client.EndReceiveMessageFrom(ar, ref sFlags,
ref LocalEndPoint, out ipInf);

log.Warn("Got address: " + ipInf.Address.ToString());
}


I know the correct source IP is in the IP header, since I can clearly see it there when I sniff the packet in wireshark. However, instead of printing out the IP of the sending system (192.168.3.4), the above code prints out the IP of the multicast group that I am subscribed to (225.2.2.6). Is there a way to get the source IP instead?

Programmer - Fixing pointers in binary tree delete function (node with 2 children)

Programmer Question

Hi,



I'm a having a little trouble thinking how the hell do I fix the appropriate pointers when trying to delete a node from a binary tree where that node has 2 children.



I understand the basic concept and I'm basically just having trouble fixing the pointers...



So, basically, my delete function is mostly done and every case is already working (as far as my extensive testing go, everything worked OK), I'm only missing the case node with 2 children. Let's say we are inside the else if that deals with that case:



I will have 2 pointers there, currPtr which holds the node to be deleted, prevPtr which holds the parent node. I also have a variable named fromLeft which defines if the currPtr parent comes from the left or right pointer on prevPtr. Then, I have a call to another function named extractMin(Tree *t) which extracts the lowest value in the tree. If I cann this function with currPtr->right as argument, the successor of currPtr is going to be extracted from the tree (the function will deleted it from tree, fix the pointers and return the node pointer). The successor pointer is going to be saved on tempPtr.



Here's the structure of my tree:



typedef int TreeElement;

typedef struct sTree {
TreeElement item;

struct sTree *left;
struct sTree *right;
} Tree;


And the code for the extract function:



Tree *extractMin(Tree *tree) {
Tree *prevPtr = NULL;
Tree *currPtr = tree;

while(currPtr->left) {
prevPtr = currPtr;
currPtr = currPtr->left;
}

if(prevPtr) prevPtr->left = currPtr->right;

// inorder successor
return currPtr;
}


The code above is missing the case here the tree only has one node, the root node, it won't work properly and it also doesn't check if the tree has any nodes at all but, it works when a tree has a few nodes.



So, how do I fix the necessary pointers on the else if for the node deletion? Also, remember that the left and right pointers on the tree nodes will always be pointing somewhere or be NULL.



By the way, I want to do this iterative.

Programmer - Jquery ajax posting wrong data

Programmer Question

I have a a form:



    <form id="deletesubmit" style="display:inline" >

<input style="width:50px" type="text" id="delcustomerid" name="delcustomerid" value="'.$row['customersid'].'">

<button type="submit" class="table-button ui-state-default ui-corner-all" title="delete"><span class="ui-icon ui-icon-trash"></span></button>

</form>


The form gets the customers id and inserts it as value. It shows the correct customer is for that row everything is fine. Then when i post the form via ajax somehow it posts the id of a diffent row. This is the script:



    $("form#deletesubmit").submit(function() {

var delcustomerid = $('#delcustomerid').attr('value');
$.ajax({


type: "POST",
url: "delete/process.php",
data: "delcustomerid="+ delcustomerid,
success: refreshTable
});
return false;
});
});


And finally here is the php to post the form:



<?php include("../../config/config.php"); ?>


<?php

$deleteid = htmlspecialchars(trim($_POST['delcustomerid']));


mysql_send("DELETE FROM customers where id='$deleteid'");

?>


I have tested it without the ajax and it works fine. There must be something missing. It is not posting the correct value. Spent days trying to work it out.

LinkWithin

Related Posts with Thumbnails