Sunday, October 31, 2010

rails, rolling my own authentication system, what are security issues I should be taking into consideration?

Programmer Question

Here is a list of security issues that my authentication system has to address (I know there are already plugins for this, I want to create my own -- I'm just like that! ((especially since I want to learn how to do it)).




  1. using rails form forgery protection

  2. storing a guid as the auth_token in the cookie, not the user id. Have this token expire every x time, and regenerate a new one.

  3. store failed_login attempts, and lock the account

  4. store encrypted passwords in the db, with each user having their own salt



Is there anything else that comes to mind? I'm looking over authlogic right now to see what else they may be doing.



Find the answer here

How to Background time/IO-consuming operations across a firewall in ASP.NET C#

Programmer Question

Summary

We have an ASP.NET application that allows users to query a SQL Server Database through a middle layer (pretty standard stuff). When the user attempts to generate a PDF for the rows that were returned to them. Each set of rows with a common identifier will "turn into" a separate page in the resulting PDF.



Originally, I assumed that the number of rows would be of an order of magnitude that was conducive to piping the end PDF into the ASP Response stream and letting the user download the file to their machine, but newer requirements indicate that the number of rows is very large and vastly outside of the scale for which I had designed this.



My current solution is as follows:




  1. If the returned row count is larger than a configured threshold value, the user gets a message that asks whether or not they want to generate the PDF's in the background and be notified by email with a URL when its done, so they can download them.


  2. If acceptable to the user, I create two DataTables: One with the actual data, and one with MetaData such as where to save the resulting PDF, the name, and other meta-type information.


  3. I can then use DataTable.WriteXML to generate a "job" file in a particular folder.


  4. This is all done in a separate Thread, so the User can continue doing what they want.




Problem:

I really want to store the job xml file on a machine inside our firewall (shared network folder), but It seems I cannot for security reasons. I have been told I might want to use Impersonation and have tried but could not get it to work.



The other part of this application is something that "listens in" to the "input" folder, and processes these "job" files once every hour (or similar schedule), moves the generated PDF file to the requisite location and emails the user.



I have gotten the part that reads job files and generates the PDF working, and the part that creates the job files works (when I run it inside the firewall), but when I run it outside the firewall, even attempting impersonation, it does not work. (keeps saying "Network location not found".



Question(s):

Am I going about this the right way?

How do I write these files across the firewall?

Any design ideas or suggestions?



Thanks in advance.



Find the answer here

Saturday, October 30, 2010

What is the best way to handle a ConstraintViolationException with EJB3 and entitymanager in an SLSB

Programmer Question

here is my code snippet:



@Stateless
public class mySLSB {

@PersistenceContext(unitName = "db")
private EntityManager myEntityManager;

public void crud(MyEntity myEntity) throws MyException {
myEntityManager.merge(myEntity);
}
}


However this merge can cause a ConstraintViolationException, which does not throw MyException (which is caught in the calling servlet).



What is the best way to catch hibernate exceptions ?



Find the answer here

How to script gdb? Example add breakpoints, run, what breakpoint did we hit?

Programmer Question

Hi



How can I script gdb to do some basic stuff for me?



I would like to write some kind of script for gdb that more or less does this:




  1. Add a couple of breakpoints

  2. Start the program

  3. When we stop, where did it stop (get the frame info)

  4. Quit.



Today I'm trying to do this with



gdb --batch --command=commands.gdb


But it is not working...



Any ideas?



Thanks
Johan



Find the answer here

Is there a better way to shell out a command in C++ than system()?

Programmer Question

I have a C++ windows service that sometimes crashes when I call the system() function to shell out a command. I've run the exact text of the command in the windows command-line, and it runs just fine, but for some reason it fails when system() is run.



To make matters worse, I can't seem to get any information as to why system() is failing. There doesn't seem to be an exception raised, because I'm doing a catch(...) and nothing's getting caught. My service just stops running. I know that it's the call to system() that is failing because I've put logging information before and after the call, and anything after just doesn't log anything.



So, is there a different way that I can shell out my command? At the very least, something that will give me some information if things go wrong, or at least let me handle an exception or something.



Find the answer here

make sounds (beep) with c++

Programmer Question

Hi,
How to make the hardware beep sound with c++?



Thanks



Find the answer here

Cache Refresh in Chrome

Programmer Question

I dunno what exactly it's called, by cache refresh I mean, refresh the page after clearing its cache. I don't want to clear the entire browser cache.



I prefer Chrome's Dev panel against firebug... don't ask me why. But I can't seem to cache refresh my pages. In FF, I know it to be Shift+Refresh.



In chrome, I've tried Ctrl+R, Ctrl+Refresh, Alt+Refresh, Shift+Refresh but none of them work.



EDIT: I got a Notable Question Badge for the lamest question I've ever asked. FML.



Find the answer here

Thursday, October 28, 2010

Objective-C arrayWithPlist (that's already in an NSString)

Programmer Question

I have an NSString that already contains a pList.



How do I turn it into an NSArray?
(WITHOUT saving it to disk, only to reload it back with arrayWithContentsOfFile, and then have to delete it.)



Where is the make arrayWithPlist or arrayWithString method?
(Or how would I make my own?)



 NSArray *anArray = [NSArray arrayWithPlist:myPlistString];


Find the answer here

Is it possible to have same app running in multiple application domains in parallel?

Programmer Question

Let's say I have a windows service called "MyService" and an executable called "MyEXE"



Is it possible (from within "MyService") to start several instances of "MyEXE" running in seperate application domains in parallel?



I would apprecaiate if some one can also provide a small sample using .net.



Find the answer here

Help with the theory behind a pixelate algorithm?

Programmer Question

So say I have an image that I want to "pixelate". I want this sharp image represented by a grid of, say, 100 x 100 squares. So if the original photo is 500 px X 500 px, each square is 5 px X 5 px. So each square would have a color corresponding to the 5 px X 5 px group of pixels it swaps in for...



How do I figure out what this one color, which is best representative of the stuff it covers, is? Do I just take the R G and B numbers for each of the 25 pixels and average them? Or is there some obscure other way I should know about? What is conventionally used in "pixelation" functions, say like in photoshop?



Find the answer here

Maven Exec Plugin not using system path on windows?

Programmer Question

How can this not work in windows?




org.codehaus.mojo
exec-maven-plugin
1.2


deploy-dev-ssh
install

exec




echo

hello




I get this when I run it:



[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:exec (do-this) on project : Command execution failed. Cannot run program "echo" (in directory ""): CreateProcess error=2, The system cannot find the file specified -> [Help 1]



How can echo not be on the PATH?



Find the answer here

Are Visual Studio Express products really only for "hobbyists, students and novices" ?

Programmer Question

I have Visual Studio Professional 2008, and have been testing the free C# Express 2010 version. In general I'm amazed at how good it is for free, and how many of the full VS features it has. I'm thinking of using it for a commercial program and I know the license allows for that, it's just the description of it being for "non-professional developers like hobbyists, students and novice developers" concerns me a bit.



What I'm interested in knowing is what is stopping it being 'professional', that is:




  • Have you evaluated the express edition, and found a specific useful feature lacking that stopped you from using it ? Or did you initially use the express versions, but upgraded to full VS because of a feature lacking ? If so, what was that feature ?



I've searched for similar questions and found lists of differences between the full VS and express versions, but I'm more interested in knowing peoples personal experiences with it. It seems like many of the extra features in VS target developers working in large teams, so I'm mainly interested in hearing from either solo or small team developers where it seems like there's less compelling reasons to upgrade.



The limitations I've personally encountered are:




  • Extensions not being supported, though I can still use DotTrace, NUnit and an obfuscator outside of the VS integration, albeit it's a bit less convenient.

  • Limited refactoring, although the "Rename" and "Extract Method" are still there and I think they're the most useful. No 'Encapsulate Field' is annoying though.

  • More limited debugging for multi-threaded apps.

  • Edit: Another is that you can't easily switch between targeting "Any CPU/x86/x64" in Express like you can in VS. It is possible, but needs manually editing your project file to do so.



But the pluses seem to outweigh the minuses so far. Is there anything you found was a deal-breaker for you ?



Find the answer here

Wednesday, October 27, 2010

Change schema in Solr without reindex

Programmer Question

First of all, sorry about my english:



In Solr, if we have a field in the schema with stored="true" and we change the analyzer associated with that field, are any posibility of update just this field without reindex all the documents ? Using the "stored" values of the field with the new analyzer without any datasource or external data.



Thanks !!



Find the answer here

Why is WebKit written in C++ and not in ObjectiveC

Programmer Question

Apple is the backing force of ObjectiveC.



However WebKit is written in C++.



Apart from portability (not all systems have ObjectiveC compilers/runtimes) is there any other valid reason for this? Performance, features?



Lately Apple does not seem to care of other languages than ObjectiveC.



Find the answer here

Tuesday, October 26, 2010

What is the difference between '\n' or "\n" in C++?

Programmer Question

I've seen the new line \n used 2 different ways in a few code examples I've been looking at. The first one being '\n' and the second being "\n". What is the difference and why would you use the '\n'?



I understand the '\n' represents a char and "\n" represents a string but does this matter?



Find the answer here

jquery + Zend - Making a splash screen before loading the page

Programmer Question

Hello all,



I have to do a splash screen, with two moments (one image on each - with some fade in fade out between them). After it, I need to show the page.



I'm not sure where on the a Zend framework, should that splash screen be placed...



Can I have a push about some ideas please?



Thanks.



Find the answer here

Better way of refactoring this ?

Programmer Question

I have the following classes:



public abstract class BaseClass
{
private readonly double cachedValue;

public BaseClass()
{
cachedValue = ComputeValue();
}

protected abstract double ComputeValue()
}


public class ClassA : BaseClass
{
protected override double ComputeValue() { ... }
}

public class ClassB : BaseClass
{
protected override double ComputeValue() { ... }
}


where ComputeValue() is a time consuming computation.



Problem is, there are other methods in the ClassA and ClassB which require the value returned from ComputeValue(). I was thinking of adding a protected property named 'CachedValue' in BaseClass but I find this approach to be redundant and confusing to other programmers who might not be aware of its existence, and might call ComputeValue() directly.



The second option is to use nullable type at the derived class level as I don't necessarily require the computation to be done in the constructor in BaseClass, lazy computation might be a better option:



protected override double ComputeValue()  
{
if(cachedValue.HasValue)
{
return (double) cachedValue;
}

// Do computation
cachedValue = ...

return cachedValue;
}


but I feel I could do better.



What are your thoughts on this ?



Thank you.



Edit: Just to clarify, I'm trying to prevent ComputeValue() from getting called more than once by enforcing the use of 'cachedValue'.



Find the answer here

Writing unicode strings via sys.stdout in Python

Programmer Question

Assume for a moment that one cannot use print (and thus enjoy the benefit of automatic encoding detection). So that leaves us with sys.stdout. However, sys.stdout is so dumb as to not do any sensible encoding.



Now one reads the Python wiki page PrintFails and goes to try out the following code:



$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout);


However this too does not work (at least on Mac). Too see why:



>>> import locale
>>> locale.getpreferredencoding()
'mac-roman'
>>> sys.stdout.encoding
'UTF-8'


(UTF-8 is what my terminal understands).



So one changes the above code to:



$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \
sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout);


And now unicode strings are properly sent to sys.stdout and hence printed properly on the terminal (sys.stdout is attached the terminal).



Is this the correct way to write unicode strings in sys.stdout or should I be doing something else?



EDIT: sometimes sys.stdout.encoding will be None (example: when piping the out through less). in this case, the above code will fail.



Find the answer here

cross thread call. pls help

Programmer Question

using System;
using System.Windows.Forms;
using agsXMPP;
using System.Text;
namespace iTalk2
{
public partial class Main : Form
{
agsXMPP.XmppClientConnection objXmpp;

public Main()
{
InitializeComponent();
}


private void Form1_Load(object sender, EventArgs e)
{

Console.WriteLine("Logging in. Please wait...");
Console.ReadLine();
objXmpp = new agsXMPP.XmppClientConnection();
agsXMPP.Jid jid = null;
jid = new agsXMPP.Jid("username" + "@gmail.com");
objXmpp.Password = "password";
objXmpp.Username = jid.User;
objXmpp.Server = jid.Server;
objXmpp.AutoResolveConnectServer = true;

try
{
objXmpp.OnMessage += messageReceived;
objXmpp.OnAuthError += loginFailed;
objXmpp.OnLogin += loggedIn;
objXmpp.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}

private void messageReceived(object sender, agsXMPP.protocol.client.Message msg)
{
string[] chatMessage = null;
chatMessage = msg.From.ToString().Split('/');
agsXMPP.Jid jid = null;
jid = new agsXMPP.Jid(chatMessage[0]);
agsXMPP.protocol.client.Message autoReply = null;
autoReply = new agsXMPP.protocol.client.Message(jid, agsXMPP.protocol.client.MessageType.chat, "This is a test");
objXmpp.Send(autoReply);
}

private void loginFailed(object o, agsXMPP.Xml.Dom.Element el)
{
Console.WriteLine("Login failed. Please check your details.");
}

private void loggedIn(object o)
{
Console.WriteLine("Logged in and Active.");
lblStatus.Text = "Online";
}

private void txtUsername_TextChanged(object sender, EventArgs e)
{

}

private void label1_Click(object sender, EventArgs e)
{

}

private void label2_Click(object sender, EventArgs e)
{

}

private void txtPassword_TextChanged(object sender, EventArgs e)
{

}

private void btnlogin_Click(object sender, EventArgs e)
{

}

}

}


This code is not working. the function 'loggedIn(object o)' is not working. it says the lblStatus (which is a label) is on another thread. the error window says "Cross-thread operation not valid: Control 'lblStatus' accessed from a thread other than the thread it was created on." thanks in advance.



Find the answer here

Monday, October 25, 2010

NSDictionaryController Selection as the Content of another NSDictionaryController

Programmer Question

Basically I have two combo boxes whose content is bound to two NSDictionaryControllers, However the content of the second combo box depends on the selection of the first. How can I accomplish this in interface builder taking advantage of the fact that my objects are implement KVO pattern. It seems that the bookComboBox selection changing does impose a selection on the BookDictionaryController. I checked this by looking at [BookDictionaryController selection] inside the selectionDidChange delegate method of the bookComboBox, which was empty.



The object model looks like



subject = top level object that has a dictionary called books
books = dictionary of book objects, with the book title as the key.
book = book object with a title property and a dictionary called chapters
chapters = dictionary of Chapter objects, with the chapter name as the key
chapter = a chapter object.



In interface builder I did this:



BookDictionaryController content{

bound to : applicationController

model key path: subject.chapters

}



bookComboBox content{

bound to: BookDictionaryController

controller key: arrangedObjects

model key path: key

}//same for content values



ChapterDictionaryController{

bound to: BookDictionaryController

controller key: selection

model key path: value.chapters

}



chapterComboBox content{

bound to: ChapterDictionaryController

controller key: arrangedObjects

model key path: key

}//same for content values



Find the answer here

Sunday, October 24, 2010

Drupal .htaccess

Programmer Question

I am using Drupal in my website but there are some folders outside drupal. I want to exclude those folders from rewrite rules.



I already tried :




  • RewriteCond %{REQUEST_URI} !^/admin/ in .htaccess

  • Options +MultiViews in apache config



Find the answer here

Saturday, October 23, 2010

Simplest way to show a clock in C++ and Linux.

Programmer Question

I'm using C++ under Linux compiling with standard GCC. In my program I want to add a simple clock showing HH:MM:SS. What's the easiest way to do that?



Find the answer here

MSBuild: transform paths to namespaces

Programmer Question

I have list of items like this:








And I want to transform that to a list of items like this:



clojure.core clojure.set clojure.zip clojure.test.junit



Is there a way to do this with MSBuild transforms? I tried but I can only get at the file name; the extension and the root path, and I can change the separator. But not the path separators.



If not, any other solution that avoids using custom tasks is appreciated.



Find the answer here

Retrieve country name from iPhone gps without internet!

Programmer Question

Hello,



In my application on the iPhone and iPod Touch I want to be able to retrieve the country a person is in without accessing the internet. I know how to do this with internet, so I know how to retrieve the longitudes and latitudes, I've read something about a file with the world borders included, but I don't know how to use this in objective-c on the iPhone.



Does anybody know a fairly easy solution to retrieve the country name from the iPhone's GPS-coordinates without using internet?



Thanks in advance,



Fabian



Find the answer here

zend database error output

Programmer Question

Hi,
I cant see my error of Sql. It cuts my queries, and the error is meaningless except it informs there is an error.
Like
error in statement "select * from o.."



how can I get full query, so i can investigate how the error occured?



Find the answer here

Friday, October 22, 2010

how to return a dynamic result set in Oracle function

Programmer Question

I found a string tokenizer query on the net and packaged it into the below function, which return the dynamic set of tokens. The function compiles successfully but somehow I get the error "ORA-00933: SQL command not properly ended". Can someone please help me debug this? Thank you.



CREATE OR REPLACE TYPE KEY_VALUE_TYPE is object (k varchar2(4000), v varchar2(4000));
CREATE OR REPLACE TYPE KEY_VALUE_TABLE is table of key_value_type;
CREATE OR REPLACE FUNCTION StrTokenizer
(string IN VARCHAR2, delimiter IN VARCHAR2)
RETURN key_value_table AS
v_ret key_value_table;
BEGIN
SELECT
CAST(
multiset(
SELECT
LEVEL k,
SUBSTR(STRING_TO_TOKENIZE,
DECODE(LEVEL, 1, 1, INSTR(STRING_TO_TOKENIZE, DELIMITER, 1, LEVEL-1)+1),
INSTR(STRING_TO_TOKENIZE, DELIMITER, 1, LEVEL)
- DECODE( LEVEL, 1, 1, INSTR(STRING_TO_TOKENIZE, DELIMITER, 1, LEVEL-1)+1)) v
FROM
(
SELECT
':string'||':delimiter' AS STRING_TO_TOKENIZE , ':delimiter' AS DELIMITER
FROM
DUAL
)
CONNECT BY INSTR(STRING_TO_TOKENIZE, DELIMITER, 1, LEVEL)>0
ORDER BY level ASC)
As key_value_table)
INTO
v_ret
FROM dual;
return v_ret;
END;

select * from strtokenizer('a,b,c',',')
ORA-00933: SQL command not properly ended


Find the answer here

Thursday, October 21, 2010

Closing Java InputStreams

Programmer Question

Good afternoon all.



I have some questions about the usage of the close() method when using Java InputStreams. From what I see and read from most developers, you should always explicitly call close() on an InputStream when it is no longer needed. But, today I was looking into using a Java properties file, and every example I have found has something like this:



Properties props = new Properties();
try {
props.load(new FileInputStream("message.properties"));
//omitted.
} catch (Exception ex) {}


With the above example, there is now way to explicitly call close() because the InputStream is unreachable after it is used. I have seen many similar uses of InputStreams even though it seems to contradict what most people say about explicitly closing. I read through Oracle's JavaDocs and it does not mention if the Properties.load() method closes the InputStream. I am wondering if this is generally acceptable or if it is preferred to do something more like the following:



Properties props = new Properties();
InputStream fis = new FileInputStream("message.properties");
try {
props.load(fis);
//omitted.
} catch (Exception ex) {
//omitted.
} finally {
try {
fis.close();
} catch (IOException ioex) {
//omitted.
}
}


Which way is better and/or more efficient? Or does it really matter? Thanks!



Find the answer here

How to handle service-layer validation in MVC3

Programmer Question

I am working on a project which requires different validation sets for the same model, and we're trying to find the best solution to handle it.



A simplified example could be using our Customer DTO:



public class Customer
{
[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }

[Required] // Only required on some views
public string Title { get; set; }
}


In our first view, all fields are required, as they're shown in the DTO using DataAnnotations.



In our second view, FirstName and LastName may be required, but Title is optional, and may not even be represented on the view.



The complication comes in, that we want to have validation rules live in our service layer (so that we can provide an API at a later point utilizing the same validation), which can access the data annotations, and validate against them, reporting back up to the UI if they don't validate.



So far, the winning method is:




  • Every view has a dedicated viewmodel, which the DataAnnotations exist on.

  • The viewmodel then maps our domain objects using something like Automapper.

  • The domain objects are then passed to the repositories and services to have actions taken upon them.



This also means:




  • Validation would not occur in the service layer, since by the time the objects got there, they would be domain objects instead of viewmodels.



Is there some better way that we should be handling this for an enterprise application? We have yet to find a solution.



Find the answer here

What exactly does using?

Programmer Question

Hi,
On MSDN I can read what it does, but I would like to know what it does technically (tells compiler where to look for types..)? I mean using as a directive.



Find the answer here

How to get the html text to just stay in one place

Programmer Question

I am making a site from html and I am putting a heading on top of an object, when I shrink the window enough the object and the text interfere



is there anyway I can have the text just stay in one spot without ending lines if there is no space left in the browser



I have tried using fixed as a position property in css but the same thing happpened



Find the answer here

get string after and before word

Programmer Question

i need to get a set of values after certain 14 length of a string and before the last 5 stringss.



eg:



Theboyisgoingt9123holdi: so i need to get the value 9123
iamfullofmeats89holdi: i need to extract value 89



so the algorithm here is, i am trying to extract the values that comes after the 14th length of the string and just before the last 5 characters of the same string.
its always whats between 14th and last 5 characters.



i am coding in vb.net.
any ideas is great appreciated.



Find the answer here

Tuesday, October 19, 2010

Get the extents on a drawing using the database without opening the drawing

Programmer Question

In the AutoCAD .NET API, while you have a drawing open, you can get the extents using the environment variables EXTMAX and EXTMIN. However, these variables don't supply correct values when you do NOT have the drawing open. How do you get these same extents without opening the drawing (AKA using the Database)?



Find the answer here

JSF: Why prependId = false in a form?

Programmer Question

I know what prependId=false does. It set the flag so that the id of the form does not prepend the id of the form child, but why? any particular reason why you do or dont want to prepend id?



Find the answer here

Sunday, October 17, 2010

What are some better alternatives to help files?

Programmer Question

Does anyone have any piece of software that actually does a good job of help?
I've seen some good ideas out there but by and large help files do not do "what it says on the tin" i.e. They just aren't "helpful."



Lets face it, help files are so 80s, does anyone read them? As software developers we know people don't read them, so we don't take pride in writing them. This lack of pride means they have become even more worthless and ... we are stuck in an endless cycle of bad help.



Here's a few of good ideas I've seen:




  • I like the idea behind visual studio's dynamic help (multiple help
    topics for each context with less
    specific topics appearing further
    down the list)


  • Ableton Live shows help in a small window while you are clicking around
    in the software and you keep noticing
    new useful things it says. Also has
    some training videos built in.


  • Putting training videos on Youtube




But apart from that it's mainly just tat. (Yes even including clippy!!)



OK that's my rant over, the question is simply this...



-Does anyone out there have any good ideas for how to do help?
-OR Has anyone seen any good examples of better help?



I'm trying to build a new way of doing help for the software we write at my company and I have some ideas but I'm eager to see what people are doing out there that works.



Thanks,
Mike G



Find the answer here

Password hashing - how to upgrade?

Programmer Question

There's plenty of discussion on the best algorithm - but what if you're already in production? How do you upgrade without having to reset on the user?



Find the answer here

Saturday, October 16, 2010

Expection Handling

Programmer Question

catch (Exception ex)
{
DBGlobals.Error("OHMjson.Graph.saveLastGraphName - Error: " + ex.getMessage());
msg = "Unable to save data";
status = false;
}


This piece of code would throw an status as false, if i encounter an error.



Instead should i thrown New expection.
Is this the right way.
How can i handle exception in a better way.



Find the answer here

Basic 2d collision detection

Programmer Question

Where can I go to read more about basic 2d collision detection for games or just applications that have some interactivity?



Edit: How about javascript for Canvas games?



Find the answer here

How can i invoke the Webkit Inspector via Javascript

Programmer Question

I don't want to use the "Inspect Element" menu item to show the Webkit Inspector.
How can i invoke him via Javascript?



Find the answer here

Where is the object explorer in visual studio C# 2010 express edition?

Programmer Question

I am not sure that this is the right place to ask this, but because all here are programmers, maybe someone could help me.



I always used 2008 express, I decided to try the 2010 version today. The problem now is that I need to check something in the object explorer, but I can't find it anywhere.



Find the answer here

android: audiotrack to voice call

Programmer Question

hi all,
i'm trying to play a sample to voice call uplink stream...



int minSize =AudioTrack.getMinBufferSize( 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT );
final AudioTrack track = new AudioTrack( AudioManager.STREAM_VOICE_CALL, 44100,
AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,
minSize, AudioTrack.MODE_STREAM);
track.play();



and then send data to the stream...but it does not play to the calling phone...



is it maybe a problem with AudioManager, but how may i configure the routing process?



thanks in advance,
regards



Find the answer here

Friday, October 15, 2010

How to get result of the previous action

Programmer Question

Hi Inside rails console you can get the result of the previous operation with _ Is there any way to do such a thing inside ruby program?



Find the answer here

JSON Schema Builder Program

Programmer Question

Is there an existing program that helps forming a JSON Schema?



Find the answer here

another strange UI exception ,also could not reproduce it in dev environment

Programmer Question

Exception type: System.Reflection.TargetInvocationException
Exception message: Exception has been thrown by the target of an invocation.



Exception local date & time: 14.Oct.2010 10:22:35.587



Exception stack trace:



at System.RuntimeMethodHandle._SerializationInvoke(Object target, SignatureStruct& declaringTypeSig, SerializationInfo info, StreamingContext context)
at System.Reflection.RuntimeConstructorInfo.SerializationInvoke(Object target, SerializationInfo info, StreamingContext context)
at System.Runtime.Serialization.ObjectManager.CompleteISerializableObject(Object obj, SerializationInfo info, StreamingContext context)
at System.Runtime.Serialization.ObjectManager.FixupSpecialObject(ObjectHolder holder)
at System.Runtime.Serialization.ObjectManager.DoFixups()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Resources.ResourceReader.DeserializeObject(Int32 typeIndex)
at System.Resources.ResourceReader.LoadObjectV2(Int32 pos, ResourceTypeCode& typeCode)
at System.Resources.ResourceReader.LoadObject(Int32 pos, ResourceTypeCode& typeCode)
at System.Resources.RuntimeResourceSet.GetObject(String key, Boolean ignoreCase, Boolean isString)
at System.Resources.RuntimeResourceSet.GetObject(String key, Boolean ignoreCase)
at System.Resources.ResourceManager.GetObject(String name, CultureInfo culture, Boolean wrapUnmanagedMemStream)
at System.Resources.ResourceManager.GetObject(String name)
at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
at System.Windows.Forms.Control.WndProcException(Exception e)
at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.RunDialog(Form form)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at DevExpress.XtraEditors.BaseButton.OnClick(EventArgs e)
at DevExpress.XtraEditors.BaseButton.OnMouseUp(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at DevExpress.Utils.Controls.ControlBase.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)



at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)



Inner exception: System.ComponentModel.Win32Exception
The operation completed successfully
at System.Drawing.Icon.Initialize(Int32 width, Int32 height)
at System.Drawing.Icon..ctor(SerializationInfo info, StreamingContext context)



At first I thought it was a question of proper disposing the Graphics instances we used,so now we call them everywhere with using in order to enforce proper disposing.
But the error still appears from time to time.
Also vague, but have you encountered this before?



Find the answer here

wpf scrollviewer and sizechanged event question

Programmer Question

Can anyone explain to me the relationship between scrollviewer and SizeChanged event? Whenever I put a scrollViewer around a grid, numerous SizeChanged event gets fired. What is the relationship between the two? Thanks a lot.



EDIT:



From mdm20's comment, I noticed that the ActualWidth and ActualHeight of the grid increases continuously if I wrap the grid around a ScrollViewer. Can anyone explain why this is the case? Do I need to have hard values for the width and height of the grid?



Find the answer here

Standard library tags

Programmer Question

I use tag files for code completion and for a quick, inline view of parameters, overloads, files (where declared), etc. Where can I find freely available tags for the C99, C++03, and C++0x standard libraries? (C89 would be better than nothing, but I'd rather have C99.)



I prefer tags without cruft; e.g. implementations use reserved names for parameters, so instead of "std::min(_M_a, _M_b)", I'd rather see "std::min(a, b)". This and other issues rule out generating from actual implementations. Though I suppose some postprocessing might clean those up (especially the identifier issue), it almost seems like it would be easier to write from scratch.



Find the answer here

Thursday, October 14, 2010

How to construct a repeating equation?

Programmer Question

Suppose two rational integers x and N.



I'm trying to determine how to construct an algorithm that would return an integer of the value x repeated N times.



So if x was 9 and N was 4, the equation would return 9999.

And if x was 9 and N was 5, the equation would return 99999. (ad nauseum)



I hope this isn't completely absurd or out of place on SO. :)



Find the answer here

How to bring JOption pop up window to front?

Programmer Question

I am working on my first project and it requires a JOption window to open for user input. it works but the window is behind everything else so I have to minimize the editor to input the info. How do I bring the window to the top?



Find the answer here

Wednesday, October 13, 2010

Why do I need to use .d to access data returned by jQuery AJAX?

Programmer Question

I've put together some jQuery AJAX code using some tutorials I found on the internet. I'm new to jQuery and want to learn how to do things betters. I have a coworker who put together a beautiful web application using a lot of jQuery.



The thing I'm most confused about here is: why is it necessary to use the ".d" when referring to the response of my web method and what does it stand for?



    // ASP.net C# code
[System.Web.Services.WebMethod]
public static string hello()
{
return ("howdy");
}

// Javascript code
function testMethod() {
$.ajax({
type: "POST",
url: "ViewNamesAndNumbers.aspx/hello",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg); // This doesn't display the response.
alert(msg.d); // This displays the response.
} // end success:
}) // end $.ajax


Find the answer here

Post build event to include a file to the project

Programmer Question

I'd like to copy a file and include the file in the web project and would like to do this as a part of the Pre/Post build events.



My understanding is that these events support DOS commands and I can use xcopy for copying a file, but I am not sure how I would update the csproj file to include the file in the project.



Find the answer here

Difference between cloud providers

Programmer Question

I am familiar with Amazon EC2. But how is it different from Azure, AppEngine and SalesForce?



Find the answer here

Should I add (check in) my project management system backup to repository?

Programmer Question

Hello,

I installed and set up Redmine project management application. Now I need to setup its backups (which include database dump + "files" directory). But I have a question:

Do I have to check in my Redmine backups into my SVN repository or not?



Find the answer here

Programmatically generate JavaDoc files.

Programmer Question

Is it possible to programmatically generate JavaDoc files by passing in a class? If so how?



Find the answer here

Tuesday, October 12, 2010

How can I put only value after decimal

Programmer Question

I have got output and I want to use only three values after decimal. How can i do that in Python?



Find the answer here

Sunday, October 10, 2010

Please help me on choosing right classifer

Programmer Question

Hi all,



I am facing a problem on selecting correct classifier for my data-mining task.



I am labeling webpages using statistical method and label them using a 1-4 scale,1 being the poorest while 4 being the best.



Previously,I used SVM to train the system since I was using a binary(1,0) label then.But now since I switch to this 4-class label,I need to change classifier,because I think the SVM classifier will only work for two-class classification(Please correct me if I am wrong).



So could you please offer some suggestion here on what kind of classifier is most approriate here for my classification purpose.



Thanks in advance for suggestions.



Find the answer here

MySQL cartesian product conditions

Programmer Question

Hi



I need alittle help with a mysql query.
I have 3 tables



x1 x2 x3
1 1 1
2 2 2
2 2 2


and I have 2 joins



select distinct

x1.int1 as a,
x2.int1 as b,
x3.int1 as c

from
x1
JOIN
x2
JOIN
x3


but I would like to generate the cartesian product with the condition that the results
should contain just the just the 3 numbers from x1 (1,2,2) in all orders and I don't know what condition to put in the query



it's a permutation simulation of three elements(1,2,2)
result should be
1,2,2
2,1,2
2,2,1



Thanks



Find the answer here

findPattern() Python Code...not executing correctly?

Programmer Question

Hi all, my homework assignment was to: "write a function called findPattern() which accepts two strings as parameters, a filename and a pattern. The function reads in the file specified by the given filename and searches the file�s contents for the given pattern. It then returns the line number and index of the line where the first instance of this pattern is found. If no match is found, your function should return -1 for both the line number and index."



I was fairly certain that my code was accurate until it would execute the first commands and then just ignore the rest of the code. I tried a couple different ways of writing it, but all three yielded the result of...not working.



I'll post the two relevant codes below:



Code 1:



def findPattern (filename, pattern):
f=open(filename)

linecount = 0
lettercount = 0


for line in f:
lineCount +=1
for letter in range(len(line)):
if line(letter)==pattern:
letterCount+=1
return[lineCount,line]
return "Did not find " + pattern


Code 2:



print
filename = raw_input("Enter a file name: ")
pattern = raw_input("Enter a pattern: ")

def findPattern (filename,pattern):
f=open(filename)

lineCount = 0
letterCount = 0

for line in f:
lineCount +=1
for lettern in range(len(line)):
if line(letter)==pattern:
letterCount+=1
print ("Found pattern " + pattern + " at " + str((lineCount, letter)))


I think code 2 would be more likely to work but it isn't yielding any results. Any input would be appriciated.



-Thanks!



Find the answer here

reducing execution time of indivual php files that are not mandatory to the system like Ajax JSON requests.

Programmer Question

I want to make sure AJAX responses from dynamic JSON pages does not slow down the server when the SQL queries take too long. I'm using PHP, MySQL with Apache2. I had this idea to use ini_set() to recude the execution of this pages with the inline use of the mentioned method or the set_time_limit() method. Is this effective? Are their any alternatives or a mysql syntax equivalent for query time?



these are being used for example with jquery ui autosuggestions and things like that which is better to not work if they are gonna slow down the server.



Find the answer here

Friday, October 8, 2010

Cannot access the selected items collection when the ListView is in virtual mode ?

Programmer Question

I have a ListView in Virtual Mode. I wanna to access SelectedItems property.

But when I use ListView1.SelectedItems , I receive the following Exception :



Cannot access the selected items collection when the ListView is in virtual mode


How can I access to ListView1.SelectedItems in VirtualMode.



Find the answer here

Thursday, October 7, 2010

Latex \newcommand for \end{verbatim} et.al not working

Programmer Question

I'm trying to make Latex usable, by introducing some timesavers, but I'm having trouble with defining new commands that terminate environments, completely at random.



This works:

\newcommand{\bcv}{\ensuremath{\begin{smallmatrix}}}
\newcommand{\ecv}{\ensuremath{\end{smallmatrix}}}

\newcommand{\be}{\begin{enumerate}}

\newcommand{\ee}{\end{enumerate}}



This does not work:

\newcommand{\bal}{\begin{align*}}

\newcommand{\eal}{\end{align*}}


\newcommand{\verbass}[1]{\begin{verbatim} #1 \end {verbatim}}



Specifically, I think the \end value is just ignored?



When I try to use \verbass{Halp} I get an error: !File ended while scanning use of \@xverbatim.



Obviously I can use \begin{foo} ... \end{foo} at all locations as needed, but really, this should work!



Find the answer here

Wednesday, October 6, 2010

VS2008 "must implement" fake errors?

Programmer Question

Hi.
I have a VS 2008 VB.NET Solution, which is quite large. Every once in a while, if I take latest code from source control, I get hundreds of errors. These aren't real errors. They are all about classes not implementing functions/events from interfaces (which they DO implement).



"Class [class name] must implement [event or function name] for interface [interface name]"



I usually end up spending couple of hours doing a combination of: building/rebuilding the solution project by project, cleaning the solution, deleting everything locally, taking latest... etc. At some point, everything just magically builds. Does anyone have any idea what is causing this? Other people on my team experience this as well. I do not see any circular references. Any help is greatly appreciated.



Find the answer here

Difficulty with Silverlight and Azure Table Storage

Programmer Question

I have a Silverlight app that I want to be hosted on Azure. I have a data entity that represents a type of data I want to store. This tutorial tells me I need to make that class inherit from Entity. I'm not sure what that class is. Has it been renamed to TableStorageEntity?



TableStorageEntity is from Microsoft.WindowsAzure.StorageClient.dll, but I can't add a reference to it from my Silverlight project. (It says that only certain DLLs are allowed to work with Silverlight.) What am I supposed to be doing here? Make a different project?



Find the answer here

Hibernate two tables and one object

Programmer Question

Hello,



I have this situtation:



Table1: 
tab_id
field11
field12


Table2
id
tab_id
field21
field22


I have to create one object on this two tables for example:



object: 

@Id
tabId

@Colummn(name="field11")
field11

@Colummn(name="field12")
field12

@Colummn(name="field21")
field21


When i update field21 table2 should update this field, but table1 doesn't have any information about table2, only table2 hat foreign key to table1



Any idea how i should this make ?



I cannot change table structure, i can only create new class in java.



Find the answer here

Tuesday, October 5, 2010

How can I force SQL Server Group By to respect column order when grouping?

Programmer Question

I am using SQL Server 2005.



SEE END OF THIS POST REGARDING BAD TABLE DESIGN.



I have two columns. I would like to group by the first column with respect to the order of the second column. Microsofts documentation states that GROUP BY clause does not care about order, how can I enforce this??



Here is my pseudo query:



SELECT col_1,
MIN(col_2),
MAX(col_2)
FROM someTable
GROUP BY col_1 (*** WITH RESPECT TO ORDER OF col_2***)


If I ran the query on the following table:



Col_1    Col_2
A 1
A 2
A 3
B 4
C 5
C 6
B 7
A 9


I should get the following results:



Col_1  Min   Max
A 1 3
B 4 4
C 5 6
B 7 7
A 9 9


The key part is that I CAN NOT have all 4 records of A lumped together in the result set. When the table/subquery is queried against, it is sorted by col_2, each new instance of col_1 should result in a new grouping. Thanks, I could not find anything on this.



I can do NOTHING with the table design. This was a table that was created by an outside vendor that is used with their proprietary software. I repeat I can do nothing about the table design!!!!



Find the answer here

.NET 4.0 has a new GAC, why?

Programmer Question

%windir%\Microsoft.NET\assembly\ is the new GAC, does it mean now we have to manage two GACs, one for .NET 2.0-3.5 apps and the other for .NET 4.0 apps?



The question is, why?



Find the answer here

Upload a file to a web server using C++

Programmer Question

Hi,



I want to upload files from a client location to a server. At present, I have a client-server socket program by which I could send/receive files across, but I would like to improvise it.



My idea would be to transfer the file using HTTP PUT/POST from client (most of the coding on client side) to the server. Since I have no idea about HTTP programming, so I need some guidance on how to achieve that. I want to use C++ with BSD sockets in doing that, and no other libraries. My aim is to send the server a form, like as given below with a HTTP POST/PUT request, and get the file "main.cpp" uploaded to the server.



PUT http://localhost/ HTTP/1.0
Host: localhost
Content-type: form-data
Content-length: 90
FileUpload: /Users/SG/files/main.cpp


I was able to write a dummy program that does some PUT from a client, and the web server running Apache returns a HTTP 200. What I am failing to understand currently would be the following two things, which I guess are somewhat connected:




  1. How one could specify a file to be uploaded from the client in the form above?


  2. If I understand correctly, the file would be read at client site and then the file content would be sent to the server, where a server side script would read the bytes from client and create a copy of the file at the server. Is it correct?




Any help is appreciated.



Thanks,

Sayan



Find the answer here

Sunday, October 3, 2010

Adding uiview to a uiviewcontroller

Programmer Question

I'd like to add a 50x150 uiview that I will be using as a menu, and I want to overlay it on top of my uiviewcontroller. So far what I've done is declare a UIView IBOutlet in the UIViewController class file, and in that UIViewController xib file, I dragged a UIView from the library and hooked it up accordingly. Problem is its not showing up when trying to call it:



menu = [[UIView alloc] initWithFrame:CGRectMake(10,10,50,150)];
//[self.view insertSubview:menu atIndex:0];
[self.view addSubview:menu];
//[self.view bringSubviewToFront:menu];


I've tried different variations as you can see, all suggestions from other posts but I get nothing. Am I going down the wrong path here? What am i missing?



Find the answer here

Friday, October 1, 2010

Contenteditable reset text color after foreColor has been used without resetting other styles

Programmer Question

Changing the text color of text in a contenteditable div is easy - simply called document.execCommand("foreColor",false,"#FFF") to change text color to white.



However, I cannot find a way to reset this color back to its default value (or to the value of the parent element). document.execCommand("removeFormat",false,null) works perfectly, except that it will also remove any bold or italic styles, which is not what I want. Simply setting the color to black works, apart from if you have a link in the selection (which should stay the same color).



Is this possible?



Find the answer here

Maven reporting plugins do not execute if a unit test failure occurs

Programmer Question

None of the plugins in the reporting section of Maven execute if there is a unit test failure.



I found that I can set maven.test.failure.ignore=true here - http://jira.codehaus.org/browse/SUREFIRE-247 The problem to this approach is now our hudson builds are successful even if there are unit test failures.



What I would really like to do is set the reporting plugin maven-surefire-report-plugin to run with the build plugins on a phase but I can't get this to work.



Any idea on how to get the Maven reporting plugins to execute if a unit test failure occurs?



Find the answer here

Installing C++ Boost library on Windows without Visual Studio

Programmer Question

I would like to install Boost library without the need of Visual Studio compiler, preferably by downloading the pre-compiled binaries. We are working on a cross-platform C++ project in Eclipse, so VS is out of option.



About a year ago, I found an installer, but it does not longer exists.
The best match I have found so far is from:
http://www.boostpro.com/download/
but it seems like this one includes a lot of stuff related to VS.



If there is no installer available, is there an easy way of compiling it like the on *NIX platforms?



(I know that the majority of the library is header-only, but I would like some parts which are not)



Find the answer here

JQuery ajax can't find elements in returned HTML

Programmer Question

I have a simple



$.ajax({
url: someUrl,
method: 'get',
dataType: 'html',
success: function(data) {
$('#someId').append($(data));
}
});


The problem is I can't find elements simply within the returned data. If there's an input with id="myInput" I can't get it with $('#myInput') or $('input[id=myInput]'). I CAN find it with:



$('input').each(function(i,e){ if($(e).attr('id') == 'myInput'){ doStuff(e); } });


But who wants to do that each time? I saw this question but the solutions provided didn't work for me. In addition to what's up there I've tried



$('#someId').html(data);
$(data).appendTo($('#someId'));


and I'm using jQuery 1.4.2. Thoughts, suggestions?



Find the answer here

adding on ?v=1 to urls

Programmer Question

As seen in the code from http://html5boilerplate.com/ (ctrl+f "?v=1")
What does ?v=1 do exactly? It's tacked on to the external css and js urls.



Find the answer here

LinkWithin

Related Posts with Thumbnails