Thursday, May 27, 2010

Hyphen in Array keys

Programmer Question

All,



I have an array with hyphens in the key name. How do I extract the value of it in PHP? It returns a 0 to me, if I access like this:



print $testarray->test-key;


This is how the array looks like



 testarray[] = {["test-key"]=2,["hotlink"]=1}


Thanks



Find the answer here

How do I maintain rows when sorting a matrix in MATLAB?

Programmer Question

I have a 2-by-3 matrix, and I want to sort it according to the first column. Here's an example:



data   will change to -->  new data
11 33 10 22
22 44 11 33
10 22 22 44


I have this code for sorting a matrix A but it doesn't work well:



sort(A,1,'ascend');


Find the answer here

Subroutine to apply Daylight Bias to display time in local DST?

Programmer Question

UK is currently 1 hour ahead of UTC due to Daylight Savings Time. When I check the Daylight Bias value from GetTimeZoneInformation it is currently -60. Does that mean that translating UTC to DST means DST = UTC + -1 * DaylightBias, ie negate and add?



I thought in this case for instance adding Daylight Bias to UTC is the correct operation, hence requiring DaylightBias to be 60 rather than -60.



Find the answer here

WPF storyboard animation issue when using VisualBrush

Programmer Question

Hey guys,
I was playing around with storyboards, a flipping animation, and visual brushes. I have encountered an issue though. Below is the xaml and code-behind of a small sample I quickly put together to try to demonstrate the problem.



When you first start the app, you are presented with a red square and two buttons. If you click the "Flip" button, the red square will "flip" over and a blue one will appear. In reality, all that is happening is that the scale of the width of the StackPanel that the red square is in is being decreased until it reaches zero and then the StackPanel where a blue square is, whose width is initially scaled to zero, has its width increased. If you click the "Flip" button a few times, the animation looks ok and smooth.



Now, if you hit the "Reflection" button, a reflection of the red/blue buttons is added to their respective StackPanels. Hitting the "Flip" button now will still cause the flip animation but it is no longer a smooth animation. The StackPanels width often does not shrink to zero. The width shrinks somewhat but then just stops before being completely invisible. Then the other StackPanel appears as usual. The only thing that changed was adding the reflection, which is just a VisualBrush.



Below is the code. Does anyone have any idea why the animations are different between the two cases (stalling in the second case)?



Thanks.










































Here are the button click handlers:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;

namespace WpfFlipTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

bool flipped = false;
private void FlipButton_Click(object sender, RoutedEventArgs e)
{
Storyboard sbFlip = (Storyboard)Resources["sbFlip"];
Storyboard sbFlipBack = (Storyboard)Resources["sbFlipBack"];

if (flipped)
{
sbFlipBack.Begin();
flipped = false;
}
else
{
sbFlip.Begin();
flipped = true;
}
}

bool reflection = false;
private void ReflectionButton_Click(object sender, RoutedEventArgs e)
{
if (reflection)
{
reflection = false;
redRefelction.Visibility = Visibility.Collapsed;
blueRefelction.Visibility = Visibility.Collapsed;
}
else
{
reflection = true;
redRefelction.Visibility = Visibility.Visible;
blueRefelction.Visibility = Visibility.Visible;
}
}
}
}









UPDATE:



I have been testing this some more to try to find out what is causing the issue I am seeing and I believe I found what is causing the issue.



Below I have pasted new xaml and code-behind. The new sample below is very similar to the original sample, with a few minor modifications. The xaml basically consists of two stack panels, each containing two borders. The second border in each stack panel is a visual brush (a reflection of the border above it). Now, when I click the "Flip" button, one stack panel gets its ScaleX reduced to zero, while the second stack panel, whose initial ScaleX is zero, gets its ScaleX increased to 1. This animation gives the illusion of flipping. There are also two textblocks which display the scale factor of each stack panel. I added those to try to diagnose my issue.



The issue is (as described in the oringal post) that the flipping animation is not smooth. Every time I hit the flip button, the animation starts but whenever the ScaleX factor gets to around .14 to .16, the animation looks like it stalls and the stack panels never have there ScaleX reduced to zero, so they never totally disappear. Now, the strange thing is that if I change the Width/Height properties of the "frontBorder" and "backBorder" borders defined below to use explict values instead of Auto, such as Width=105 and Height=75 (to match the button in the border) everything works fine. The animation stutters the first two or three times I run it but after that the flips are smooth and flawless. (BTW, when an animation is run for the first time, is there something going on in the background, some sort of initialization, that causes it to be a little slow the first time?)



Is it possible that the Auto Width/Height of the borders are causing the issue? I can reproduce it everytime but I am not sure why Auto Width/Height would be a problem.



Below is the sample. Thanks for the help.













































Code-behind:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;

namespace FlipTest
{
///
/// Interaction logic for Window1.xaml
///

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

bool flipped = false;
private void FlipButton_Click(object sender, RoutedEventArgs e)
{
Storyboard sbFlip = (Storyboard)Resources["sbFlip"];
Storyboard sbFlipBack = (Storyboard)Resources["sbFlipBack"];

if (flipped)
{
sbFlipBack.Begin();
flipped = false;
}
else
{
sbFlip.Begin();
flipped = true;
}
}
}
}


Find the answer here

Doctype, HTML 5

Programmer Question

Hi,



i have two questions:



1) was HTML released and if yes, when?



2) is doctype HTML 5 in use? or is it better to use one of these:
- HTML 4.01 Strict,
- HTML 4.01 Transitional,
- HTML 4.01 Frameset,
- XHTML 1.0 Strict,
- XHTML 1.0 Transitional,
- XHTML 1.0 Frameset,
- XHTML 1.1



Find the answer here

Wednesday, May 26, 2010

Asp.Net Program Architecture

Programmer Question

I've just taken on a new Asp.Net MVC application and after opening it up I find the following,




  1. [Project].Web

  2. [Project].Models

  3. [Project].BLL

  4. [Project].DAL



Now, something thats become clear is that there is the data has to do a hell of a lot before it makes it to the View (Database>DAL>Repo>BLL>ConvertToModel>Controller>View). The DAL is Subsonic, the repositorys in the DAL return the subsonic entities to the BLL which process them does crazy things and converts them into a Model (From the .Models) sometimes with classes that look like this



public DataModel GetDataModel(EntityObject Src)
{
var ReturnData = new DataModel():
ReturnData.ID = Src.ID;
ReturnDate.Name = Src.Name;

//etc etc
}


Now, the question is, "Is this complete overkill"? Ok the project is of a decent size and can only get bigger but is it worth carrying on with all this? I dont want to use AutoMapper as it just seems like it makes the complication worse. Can anyone shed any light on this?



Find the answer here

Tuesday, May 25, 2010

Figuring out if overflow:auto would have been triggered on a div

Programmer Question

Hi folks,



// Major edit, sorry in bed with back pain, screwed up post



One of the ad agencies I code for had me set up an alternate scrolling solution because you know how designers hate things that just work but aren't beautiful.



The scrolling solution is applied to divs with overflow:hidden and uses jQuery's scrollTo(). It's a set of buttons top and bottom that handle moving the content.



So, this is married in places to their CMS. What I have not been able to sort yet is how to hide the scrolling UI when overflow:auto would not have been triggered by the CMS content and the buttons are not needed.



The divs have set heights and widths. Can i detect hidden content? Or measure the div contents' height?



Any ideas?



TIA



JG



Find the answer here

How to call a FileReference.browse() from JavaScript?

Programmer Question

Hello,



I am trying to call the browse() method of the FileReference class from JavaScript (a user clicks on a text that uses the ExternalInterface to call a method in Flash).



Unfortunately, I receive an error that tells me it has to be a direct action of the user (like clicking a button). I have searched through Google and realized this is a new security feature in Flash 10.



The only solutions I could find was to put a Flash button or to have a hidden flash button over the text, that will call the browse() method.



I wanted the browser only to show JavaScript and all the Flash code only called from JavaScript.



Is there please any way I could please do that?



Thank you very much,
Rudy



Find the answer here

Unresponsive threading involving Swing and AWT-EventQueue

Programmer Question

I have an application that is unresponsive and seems to be in a deadlock or something like a deadlock. See the two threads below. Notice that the My-Thread@101c thread blocks AWT-EventQueue-0@301. However, My-Thread has just called java.awt.EventQueue.invokeAndWait(). So AWT-EventQueue-0 blocks My-Thread (I believe).



My-Thread@101c, priority=5, in group 'main', status: 'WAIT'
blocks AWT-EventQueue-0@301
at java.lang.Object.wait(Object.java:-1)
at java.lang.Object.wait(Object.java:485)
at java.awt.EventQueue.invokeAndWait(Unknown Source:-1)
at javax.swing.SwingUtilities.invokeAndWait(Unknown Source:-1)
at com.acme.ui.ViewBuilder.renderOnEDT(ViewBuilder.java:157)
.
.
.
at com.acme.util.Job.run(Job.java:425)
at java.lang.Thread.run(Unknown Source:-1)

AWT-EventQueue-0@301, priority=6, in group 'main', status: 'MONITOR'
waiting for My-Thread@101c
at com.acme.persistence.TransactionalSystemImpl.executeImpl(TransactionalSystemImpl.java:134)
.
.
.
at com.acme.ui.components.MyTextAreaComponent$MyDocumentListener.insertUpdate(MyTextAreaComponent.java:916)
at javax.swing.text.AbstractDocument.fireInsertUpdate(Unknown Source:-1)
at javax.swing.text.AbstractDocument.handleInsertString(Unknown Source:-1)
at javax.swing.text.AbstractDocument$DefaultFilterBypass.replace(Unknown Source:-1)
at javax.swing.text.DocumentFilter.replace(Unknown Source:-1)
at com.acme.ui.components.FilteredDocument$InputDocumentFilter.replace(FilteredDocument.java:204)
at javax.swing.text.AbstractDocument.replace(Unknown Source:-1)
at javax.swing.text.JTextComponent.replaceSelection(Unknown Source:-1)
at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(Unknown Source:-1)
at javax.swing.SwingUtilities.notifyAction(Unknown Source:-1)
at javax.swing.JComponent.processKeyBinding(Unknown Source:-1)
at javax.swing.JComponent.processKeyBindings(Unknown Source:-1)
at javax.swing.JComponent.processKeyEvent(Unknown Source:-1)
at java.awt.Component.processEvent(Unknown Source:-1)
at java.awt.Container.processEvent(Unknown Source:-1)
at java.awt.Component.dispatchEventImpl(Unknown Source:-1)
at java.awt.Container.dispatchEventImpl(Unknown Source:-1)
at java.awt.Component.dispatchEvent(Unknown Source:-1)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source:-1)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source:-1)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source:-1)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source:-1)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source:-1)
at java.awt.Component.dispatchEventImpl(Unknown Source:-1)
at java.awt.Container.dispatchEventImpl(Unknown Source:-1)
at java.awt.Window.dispatchEventImpl(Unknown Source:-1)
at java.awt.Component.dispatchEvent(Unknown Source:-1)
at java.awt.EventQueue.dispatchEvent(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source:-1)
at java.awt.EventDispatchThread.run(Unknown Source:-1)


Here is the TransactionalSystemImpl.executeImpl method:



private synchronized Object executeImpl(Transaction xact, boolean commit) {
final Object result;

try {
if (commit) { // this is line 134
clock.latch();
synchronized(pendingEntries) {
if (xactLatchCount > 0) {
pendingEntries.add(xact);
} else {
xactLog.write(new TransactionEntry(xact, clock.time()));
}
}
}

final TransactionExecutor executor = transactionExecutorFactory.create(
xact.getClass().getSimpleName()
);

if (executor == null) {
throw new IllegalStateException("Failed to create transaction executor for transaction: " + xact.getClass().getName());
}

result = executor.execute(xact);

} finally {
if (commit) clock.unlatch();
}

return result;
}


Does anyone know what's going on here or how to fix it?



Find the answer here

Monday, May 24, 2010

Now() In ODBC SQL Query?

Programmer Question

I'm trying to update a database field to the current time, but can't pass "now()". I get the following error:



'now' is not a recognized built-in function name.



The method I'm using to query the database is as follows:



Public Sub main()

Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset

Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordset

cnn.Open "ConnectionName"
rst.ActiveConnection = cnn
rst.CursorLocation = adUseServer

rst.Source = "Update Table ..."
rst.Open

Set rst = Nothing
Set cnn = Nothing
End Sub


Find the answer here

serial port in C

Programmer Question

I have written a program in C to send a byte to serial port (com).
I have used BIOSCOM to send data
but I guess that it doesn't open the port.
Please tell how I can open and close a com port in C.



My code is here:



#define COM1 1;
bioscom (1 , 65 , COM1);


Please help me...



Find the answer here

What is the best way to store a 16 � (2^20) matrix in matlab?

Programmer Question

I am thinking of writing the data to a file. Does anyone have an example of how to write a big amount of data to a file?



edit 1: Most elements in the matrix are zeroes, others are uint32. I guess the simplest save() and load() would work, as @Jonas suggested.



Find the answer here

Unresponse threading involving Swing and AWT-EventQueue

Programmer Question

I have an application that is unresponsive and seems to be in a deadlock or something like a deadlock. See the two threads below. Notice that the My-Thread@101c thread blocks AWT-EventQueue-0@301. However, My-Thread has just called java.awt.EventQueue.invokeAndWait(). So AWT-EventQueue-0 blocks My-Thread (I believe).



My-Thread@101c, priority=5, in group 'main', status: 'WAIT'
blocks AWT-EventQueue-0@301
at java.lang.Object.wait(Object.java:-1)
at java.lang.Object.wait(Object.java:485)
at java.awt.EventQueue.invokeAndWait(Unknown Source:-1)
at javax.swing.SwingUtilities.invokeAndWait(Unknown Source:-1)
at com.acme.ui.ViewBuilder.renderOnEDT(ViewBuilder.java:157)
.
.
.
at com.acme.util.Job.run(Job.java:425)
at java.lang.Thread.run(Unknown Source:-1)

AWT-EventQueue-0@301, priority=6, in group 'main', status: 'MONITOR'
waiting for My-Thread@101c
at com.acme.persistence.TransactionalSystemImpl.executeImpl(TransactionalSystemImpl.java:134)
.
.
.
at com.acme.ui.components.MyTextAreaComponent$MyDocumentListener.insertUpdate(MyTextAreaComponent.java:916)
at javax.swing.text.AbstractDocument.fireInsertUpdate(Unknown Source:-1)
at javax.swing.text.AbstractDocument.handleInsertString(Unknown Source:-1)
at javax.swing.text.AbstractDocument$DefaultFilterBypass.replace(Unknown Source:-1)
at javax.swing.text.DocumentFilter.replace(Unknown Source:-1)
at com.acme.ui.components.FilteredDocument$InputDocumentFilter.replace(FilteredDocument.java:204)
at javax.swing.text.AbstractDocument.replace(Unknown Source:-1)
at javax.swing.text.JTextComponent.replaceSelection(Unknown Source:-1)
at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(Unknown Source:-1)
at javax.swing.SwingUtilities.notifyAction(Unknown Source:-1)
at javax.swing.JComponent.processKeyBinding(Unknown Source:-1)
at javax.swing.JComponent.processKeyBindings(Unknown Source:-1)
at javax.swing.JComponent.processKeyEvent(Unknown Source:-1)
at java.awt.Component.processEvent(Unknown Source:-1)
at java.awt.Container.processEvent(Unknown Source:-1)
at java.awt.Component.dispatchEventImpl(Unknown Source:-1)
at java.awt.Container.dispatchEventImpl(Unknown Source:-1)
at java.awt.Component.dispatchEvent(Unknown Source:-1)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source:-1)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source:-1)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source:-1)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source:-1)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source:-1)
at java.awt.Component.dispatchEventImpl(Unknown Source:-1)
at java.awt.Container.dispatchEventImpl(Unknown Source:-1)
at java.awt.Window.dispatchEventImpl(Unknown Source:-1)
at java.awt.Component.dispatchEvent(Unknown Source:-1)
at java.awt.EventQueue.dispatchEvent(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source:-1)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source:-1)
at java.awt.EventDispatchThread.run(Unknown Source:-1)


Here is the TransactionalSystemImpl.executeImpl method:



private synchronized Object executeImpl(Transaction xact, boolean commit) {
final Object result;

try {
if (commit) { // this is line 134
clock.latch();
synchronized(pendingEntries) {
if (xactLatchCount > 0) {
pendingEntries.add(xact);
} else {
xactLog.write(new TransactionEntry(xact, clock.time()));
}
}
}

final TransactionExecutor executor = transactionExecutorFactory.create(
xact.getClass().getSimpleName()
);

if (executor == null) {
throw new IllegalStateException("Failed to create transaction executor for transaction: " + xact.getClass().getName());
}

result = executor.execute(xact);

} finally {
if (commit) clock.unlatch();
}

return result;
}


Does anyone know what's going on here or how to fix it?



Find the answer here

Saturday, May 22, 2010

IIS 6.0 Load Balancing and ASP.NET In-Proc Session

Programmer Question

We have three web servers in our web farm that are load balanced using the Network Load Balancing Manager in Windows 2003. The sites that run on these boxes use In-Proc ASP.NET session. Our assumption is that the balancing uses a "sticky" session because users seem to be assigned to a given server during their use of the application as well as there doesn't appear to be any session error where the session data is residing on a previous machine. My question is how can I 1) verify that our balancing configuration is using "sticky" sessions and 2) can someone explain the load balancing feature in Windows 2003 relative to ASP.NET web applications?



Find the answer here

Silverlight 4 and Youtube flash player

Programmer Question

hi



I'm trying to make a small silverlight application but i became across a problem, playing videos from youtube.
I tried a method with a html conteiner to embed the youtube flash player, but with this method i need to activate the option windowsless, and thats is not a good ideia for my web site.
If anyone have a good ideia,I'm glad to hear



thanks
BasicSide



Find the answer here

Friday, May 21, 2010

Adding an integer onto an array

Programmer Question

I'm trying to add random numbers onto the end of this array when ever I call
this function. I've narrowed it down to just this so far.
when ever I check to see if anything is in the array it says 0.
So now i'm quite stumped. I'm thinking that MutableArray releases the contents of it before I ever get to use them. problem is I don't know what to use. A button calls the function and pretty much everything else is taken care of its just this portion inside the function.



NSMutableArray * choices;

-(void) doSomething {

int r = arc4random() % 4;
//The problem...
[choices addObject:[NSNumber numberWithInt:r]];

int anInt = [[choices objectAtIndex:1] integerValue];
NSLog(@"%d", anInt);
//I'm getting nothing no matter what I do.

//some type of loop that goes through the array and displays each element
//after it gets added

}


Find the answer here

.NET TreeView causes application to crash when trying to check Parent node

Programmer Question

I have a TreeView with check boxes, and when a user checks a child node, I want to go up the tree and check each parent. However, for some reason my application blows up whenever I touch the parent node. For the nodes in my tree, I've extended TreeNode to create my own objects with some data that I need to store in them, but I still reference them as TreeNodes when checking/unchecking. My code looks like this:



//checkBox checked event handler
if (node.Parent != null)
{
checkAllParents(node.Parent);
}
//

private void checkAllParents(TreeNode node)
{
node.Checked = true;
if (node.Parent != null)
{
checkAllParents(node.Parent);
}
}


Find the answer here

Multiple Queues in jQuery

Programmer Question

I am having problems using multiple queues in jQuery. Consider the following example:



$('#example').click(function() {
$(this).delay(1000, 'fx2').queue('fx2', function() {
alert('here');
});
});


The alert never fires. Why?



Find the answer here

How do you identify users when using PayPal?

Programmer Question

From this article on CodeGuru about PayPal IPN, I see there are two fields, payer_email and payer_id, that can be used to identify the user. Is there anything else I'm missing? Do you use these fields to identify the user or how do you do it?



Thanks



Find the answer here

Looking for a good course/book/resource on modern databases

Programmer Question

This is slightly embarrassing. I'm a professional developer working at one of the big tech companies and I've never used a database. I've got an idea for a website I want to build as a learning experience and possibly as a business, but I don't have the faintest idea what database to use, let alone how to fix/debug the database when I run into problems.



I'm looking for a course, a website, a book, etc., that will give me an overview of modern database technology (SQL vs. NOSQL vs. relational vs. non-relational (I only have a vague idea what these even mean)). I'm starting by googling/wikipediaing all of these terms, but if there are better, comprehensive resources available that I should be aware of, I'd love to hear about them.



Find the answer here

Thursday, May 20, 2010

Bind Object to WPF TreeView

Programmer Question

I would like to know how to bind a custom datatype to a treeview.



The datatype is basically arraylists of objects that contain other arraylists. Access to would look something like this.



foreach (DeviceGroup dg in system.deviceGroups)
{
foreach (DeviceType dt in dg.deviceTypes)
{
foreach (DeviceInstance di in dt.deviceInstances)
{

}
}
}


I would like the treeview to look something like this:



DeviceGroup1



 --> DeviceType1
--DeviceInstance1
--DeviceInstance2
--> DeviceType2
--DeviceInstance1


DeviceGroup2



 --> DeviceType1
--DeviceInstance1
--> DeviceType2


Find the answer here

Add a method to array object

Programmer Question

I've found this post:



Array#add_condition
But i didn't understand to how implement it in my rails project



How can i do it?



thanks



Find the answer here

How can I filter a report with duplicate fields in related records?

Programmer Question

I have a report where I need to filter out records where there is a duplicate contract number within the same station but a different date. It is not considered a duplicate value becuase of the different date. I then need to summarize the costs and count the contracts but even if i suppress the "duplicate fields" it will summarize the value. I want to select the record with the most current date.



Station Trans-DT  Cost    Contract-No
8 5/11/2010 10 5008
8 5/12/2010 15 5008
9 5/11/2010 12 5012
9 5/15/2010 50 5012


Find the answer here

cant open device

Programmer Question

I have a little problem. I install this module into my kernel and its written under /proc



When I try to open() it from user mode I get the following message:




"Can't open device file: my_dev"




static int module_permission(struct inode *inode, int op, struct nameidata *foo)
{
//if its write
if ((op == 2)&&(writer == DOESNT_EXIST)){
writer = EXIST ;
return 0;
}
//if its read
if (op == 4 ){
numOfReaders++;
return 0;
}
return -EACCES;
}

int procfs_open(struct inode *inode, struct file *file)
{
try_module_get(THIS_MODULE);
return 0;
}

static struct file_operations File_Ops_4_Our_Proc_File = {
.read = procfs_read,
.write = procfs_write,
.open = procfs_open,
.release = procfs_close,
};

static struct inode_operations Inode_Ops_4_Our_Proc_File = {
.permission = module_permission, /* check for permissions */
};

int init_module()
{
/* create the /proc file */
Our_Proc_File = create_proc_entry(PROC_ENTRY_FILENAME, 0644, NULL);
/* check if the /proc file was created successfuly */
if (Our_Proc_File == NULL){
printk(KERN_ALERT "Error: Could not initialize /proc/%s\n",
PROC_ENTRY_FILENAME);
return -ENOMEM;
}

Our_Proc_File->owner = THIS_MODULE;
Our_Proc_File->proc_iops = &Inode_Ops_4_Our_Proc_File;
Our_Proc_File->proc_fops = &File_Ops_4_Our_Proc_File;
Our_Proc_File->mode = S_IFREG | S_IRUGO | S_IWUSR;
Our_Proc_File->uid = 0;
Our_Proc_File->gid = 0;
Our_Proc_File->size = 80;

//i added init the writewr status
writer = DOESNT_EXIST;
numOfReaders = 0 ;
printk(KERN_INFO "/proc/%s created\n", PROC_ENTRY_FILENAME);
return 0;
}


Find the answer here

Voting UI for showing like/dislike community comments side-by-side

Programmer Question

We want to add a comments/reviews feature to our website's plugin gallery, so users can vote up/down a particular plugin and leave an optional short comment about what they liked or didn't like about it.



I'm looking for inspiration, ideally a good implementation elsewhere on the web which isn't annoying to end users, isn't impossibly complex to develop, and which enables users to see both good and bad comments side-by-side, like this:



Like: 57 votes                           Dislike: 8 votes
--------------------------------- --------------------------------
"great plugin, saved me hours..." "hard to install"

"works well on MacOS and Ubuntu" "Broken on Windows Vista with
UAC enabled"
"integrates well with version 3.2"
More...
More...


Anyone know a site which does something like this particularly well? I don't need source code (since implementation will be simple), just looking for UI inspiration and best practices.



I'll accept the answer which refers me to the site which, in my biased opinion, is the best mix of usable (for end users reading comments) and addictive (for active users leaving comments).



Find the answer here

Wednesday, May 19, 2010

How do I name a variable with acronym?

Programmer Question

For example in Java for Data Transfer Object I use as:



ExampleDTO exampleDTO = new ExampleDTO();


So, if I am following PEP 8, what naming convention should I follow for similar in Python?



Find the answer here

.split("1px") into ["1px",1,"px"] in Javascript

Programmer Question

I'm rubbish at Regular Expressions, really!



What I'd like is to split a string containing a CSS property value into an array of [string,value,unit].



For example: if I supplied the .split() method with 1px it'd return ["1px",1,"px"]. If I were to supply, similarly, 10% it'd return ["10%",10,"%"].



Can this be done?



I appreciate all your help!



Update: I'd also like it to return ["1.5em",1.5,"em"] if 1.5em were supplied. But, if possible, still return null if supplied "yellow". Unfortunately /^([0-9].?[0-9])(.*)/ supplied with "yellow" would return y,,y!



Thanks so far guys!



Find the answer here

Debugging and Binary Search

Programmer Question

"Programming Pearls" in the column 2 ("AHA! Algorithm") talks about how binary search aids in various processes like sorting, tree traversals. But it mentions that binary seach can be used in "program debugging". Can somebody please explain how this is done?



Find the answer here

IIS Shared Configuration and Microsoft.Web.Administration.ServerManager Permission problem

Programmer Question

Hello,



I have a farm of web servers, and a web site who configures the IIS website using the class ServerManager. When I call the OpenRemote method on the ServerManager class I always get an error of type :



System.UnauthorizedAccessException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089


The corresponding message is :



Retrieving the COM class factory for remote component with CLSID {2B72133B-3F5B-4602-8952-803546CE3344} from machine 10.10.10.101 failed due to the following error: 80070005.


Did someone allready had this problem and know how to solve it ?



I try to give the domain admin role to my IIS user (impersonate) but even that did not work



Thanks !



Find the answer here

Tuesday, May 18, 2010

Need info on "set endian" on solaris machine

Programmer Question

Hi,



Can any 1 please tell or show the difference in the behaviour of any program before and after I "set endian little" in gdb on solaris machine?



I want to know the effect of changing it.



Thanks!



Find the answer here

IE status bar. I need to add a clickable icon to the status bar.

Programmer Question

My bho (Browser Helper Object) is a sidebar (right-sided iframe) that needs to be opened/closed by clicking the status bar icon in IE (IE8). I didn't find any informations for clickable icons. Anyone knows wich interface to use to do that. Thank you. (I'm using ATL: Active Template Library).
If anyone need precision, please ask. I'll be waiting for responses every single days.



Find the answer here

Monday, May 17, 2010

Complex JavaScript. What called me?

Programmer Question

Project I'm working on uses jQuery.



I have a series of Ajax calls being made that load() other HTML fragments which in turn load() other fragments. The whole thing is confusing. I didn't write the code.



Is there any tool which will allow me to walk the callstack so I can figure what is calling a method? any browser tools that would help me figure this out?



Find the answer here

Return to a removed view controller

Programmer Question

Here is the situation, I have a login page as the initial rootView of a tab bar. Once the login process is done, the view is removed from the navigation controller, so you don't navigate back to it. I have places in the app where you can logout. The logout process works fine, but when I try to forward the user back to the initial login view (the one we removed) from inside the same tab bar item, I can't seem to reset the view controller stack to contain only the desired element. Is this a question of where I am changing the view? It just doesn't seem to remove the current view. I have tried alot of stuff, popto, popview, and many others, and nothing seems to work properly. Has anyone had to deal with this?



Find the answer here

Most efficient way to move a few MS Sql tables to SQLite?

Programmer Question

I have a fairly large MS-Sql database; I'd like to pull 4 tables out and dump them directly into an sqlite.db for remote querying (via nightly batch).



I was about to write a script to step through(most likely on a unix host kicked off via cron); but there should be a simpler method to export the tables directly (SQLite not an option in the included DTS Import/Export wizard)



What would the most efficient method of dumping the MS Sql tables to SQLite via batch be?



Find the answer here

Decimal to Binary recursive method for Java [closed]

Programmer Question

Write a recursive method that converts a decimal number into a binary number as a string. The method header is as follows: public static String convertDecimalToBinary(int value)



This is what I have so far:



public static String convertDecimalToBinary(int value) {
if (value == 0)
return

convertDecimalToBinary(value / 2) + temp;
}


Find the answer here

Is there a way in Powershell to query the object Property Page Details

Programmer Question

Is there a way in Powershell to query the object Property Page Details to verify if the Copyright, Product name and File version are not empty. I want to be able to query this info when I'm looking for viruses



Find the answer here

Sunday, May 16, 2010

Using Qt Creator with Git version control

Programmer Question

I�ve recently installed git and initialized a git repo in my project folder. I can commit and checkout without any issues through the command line, but for some reason the gui in qt creator claims my connection has timed out. Im running windows�. Any ideas?



Error message(s):



21:15 Executing: git status �u
Unable to obtain the status: Error: Git timed out



Please let me know if any further clarification is needed!



I've posted this on both qt forums, but no one seems to know how to solve the issue. Thanks in advance!



Find the answer here

Keyup attribute 'name' change not working

Programmer Question

Hey guys, I've got what I imagine is a simple question, but for some reason, I can't get it working right.



Expected Behavior:
I type characters into a field, and, through a function, those characters are translated into the value of the name HTML attribute.



Actual Behavior:
Reflected in Firebug, the value doesn't change or update.



The Code:



$('input').live('keyup', function() {
var name_value = $(this).val().toLowerCase();
$(el).attr('name', name_value);
});


Just a side note: I'm using .live() because the element can be cloned, and those clones need to also be able to take on the properties of this .keyup event.



Any ideas?



Find the answer here

ABPeoplePickerNavigationController - get an address from the ABRecordRef

Programmer Question

Once I get an ABRecordRef from the ABPeopleNavigationController, how can I get the contact's street address(s) (if there is one)?



Find the answer here

Using a static library in QT Creator...

Programmer Question

Greetings,



I'm having a hell of a time finding documentation which clearly explains how to use a static library in QT Creator.



I've created and compiled my static library using QT Creator (New=>Projects\C++ Library=>Set type to "Statically Linked Library"). It compiles and spits out a ".a file".



The problem I encounter is when I try to use the library. I have another project that would like to use it (#include files in the library, etc) but I don't know the proper way to link with the library or include files from the library.



Any help is appreciated,
Dan O.



Find the answer here

C#: Making sure parameter has attribute

Programmer Question

I have an attribute lets call it SomeAttribute and a class i need to make sure the class is passed a type which has SomeAttribute. So this is how i do it now:



public class Test()
{
public Test(SomeType obj)
{
if(!obj.GetType().IsDefined(typeof(SomeAttribute), false))
{
throw new ArgumentException("Errormessage");
}
}
}


But this means that i don't get any errors at compile time but somewhere at runtime, if obj does not have the attribute. Is there a way to specify in the method declaration that the parameter must have some attribute ? So i get errors i compile time when using the wrong parameters, or do i have to use an empty interface ?



EDIT: I think the easiest solution would be an empty interface.



Find the answer here

Wednesday, May 12, 2010

How to profile my C++ application on linux

Programmer Question

HI,



I would like to profile my c++ application on linux.
I would like to find out how much time my application spent on CPU processing vs time spent on block by IO/being idle.



I know there is a profile tool call valgrind on linux. But it breaks down time spent on each method, and it does not give me an overall picture of how much time spent on CPU processing vs idle? Or is there a way to do that with valgrind.



Thank you.



Find the answer here

StringArray and StringBuilder Class

Programmer Question

can we append StringBuilder class Strings in String Array's string in asp.net?



Find the answer here

hp-ux how to get 2 hours ago bash datetime

Programmer Question

we are using hp-ux servers
we need to get 2 hours ago datetime value in bash shell script ?



how can i do that any experiences ?



Find the answer here

what does this do

Programmer Question

$top += $i ? 12 : 0;



Find the answer here

Monday, May 10, 2010

Django Formset validation with an optional ForeignKey field

Programmer Question

Having a ModelFormSet built with modelformset_factory and using a model with an optional ForeignKey, how can I make empty (null) associations to validate on that form?



Here is a sample code:



### model
class Prueba(models.Model):
cliente = models.ForeignKey(Cliente, null = True)
valor = models.CharField(max_length = 20)

### view

def test(request):
PruebaFormSet = modelformset_factory(model = Prueba, extra = 1)
if request.method == 'GET':
formset = PruebaFormSet()
return render_to_response('tpls/test.html', {'formset' : formset},
context_instance = RequestContext(request))
else:
formset = PruebaFormSet(request.POST)
# dumb tests, just to know if validating
if formset.is_valid():
return HttpResponse('0')
else:
return HttpResponse('1')


In my template, i'm just calling the {{ form.cliente }} method which renders the combo field, however, I want to be able to choose an empty (labeled "------") value, as the FK is optional... but when the form gets submitted it doesn't validate.



Is this normal behaviour? How can i make this field to skip required validation?



Find the answer here

what is the purpose of the #define directive in C++?

Programmer Question

Hi Guys !!well I wan't To now what is the role of The "#define" directive ???



Find the answer here

Sunday, May 9, 2010

What are some fun project ideas for a new Python developer?

Programmer Question


I'm new to Python 3 and so far it seems like a decent language. I really like the string manipulation methods you can use and they are pretty radical. :)



I'm stuck however in thinking of a project to do with Python. Is there a site similar to Coding4Fun but for Python?



Community Wiki because I think this question is really interesting. :D





Find the answer here

"possible loss of precision" is Java going crazy or I'm missing something?

Programmer Question


I'm getting a "loss of precision" error when there should be none, AFAIK.



this is an instance variable:



byte move=0;


this happens in a method of this class:



this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF);


move is a byte, move is still a byte, and the rest is being cast to a byte.



I get this error:



[javac] /Users/looris/Sviluppo/dumdedum/client/src/net/looris/android/toutry/Guy.java:245: possible loss of precision
[javac] found : int
[javac] required: byte
[javac] this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF);
[javac] ^


I've tried many variations but I still get the same error.



I'm now clueless.





Find the answer here

Turn database result into array

Programmer Question


Hi everyone,



I have just made the update/add/delete part for the "Closure table" way of organizing query hierarchical data that are shown on page 70 in this slideshare: http://www.slideshare.net/billkarwin/sql-antipatterns-strike-back



My database looks like this:



Table Categories:



ID         Name
1 Top value
2 Sub value1


Table CategoryTree:



child     parent     level
1 1 0
2 2 0
2 1 1


However, I have a bit of an issue getting the full tree back as an multidimensional array from a single query.



Here's what I would like to get back:



 array (

'topvalue' = array (
'Subvalue',
'Subvalue2',
'Subvalue3)
);

);


Update:
Found this link, but I still have a hard time to convert it into an array:
http://karwin.blogspot.com/2010/03/rendering-trees-with-closure-tables.html



Update2 :
I was able to add depths to each of the categories now, if that can be of any help.





Find the answer here

What is wrong with this simple update query?

Programmer Question


I get no error message, but the row is not updated. The rows integer is set 1 following the query, indicating that 1 row was affected.



String query = "UPDATE contacts SET contact_name = '" + ContactName.Text.Trim() + "', " +
"contact_phone = '" + Phone.Text.Trim() + "', " +
"contact_fax = '" + Fax.Text.Trim() + "', " +
"contact_direct = '" + Direct.Text.Trim() + "', " +
"company_id = '" + Company.SelectedValue + "', " +
"contact_address1 = '" + Address1.Text.Trim() + "', " +
"contact_address2 = '" + Address2.Text.Trim() + "', " +
"contact_city = '" + City.Text.Trim() + "', " +
"contact_state = '" + State.SelectedValue + "', " +
"contact_zip = '" + Zip.Text.Trim() + "' " +
"WHERE contact_id = '" + contact_id + "'";



String cs = Lib.GetConnectionString(null);
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
cmd.Connection.Open();
int rows = cmd.ExecuteNonQuery();




Find the answer here

How to properly align textboxes on a webpage with labels

Programmer Question


Hi, this is a CSS / design question. I have three textboxes that i want to be center aligned on a web page. Then i want a label description to the right of each one.



When i use attribute like text:align:centre because the labels are of different length it throws out the aligment of the textboxes [see image link below]



http://www.mediafire.com/imageview.php?quickkey=qcyoajm2iuk



Is there an easy way of keeping the textboxes aligned and then have the labels off the to the right without changing the textboxes?



Thanks.





Find the answer here

Saturday, May 8, 2010

Bulk get of child entities on Google app engine?

Programmer Question


On Google App Engine in Python, I have a Visit entity that has a parent of Patient. A Patient may have multiple visits.



I need to set the most_recent_visit (and some auxiliary visit data) somewhere for later querying, probably in another child entity that Brett Slatkin might call a "relationship index entity."



I wish to do so in a bulk style as follows:



1. get 100 Patient keys
2. get all Visits that have any of the Patients from 1 as an ancestor
3. go through the Visits and get the latest for each Patient


Is there any way to perform step 2 in a bulk get?



I know there is a way to bulk get entities from a list of keys, and there is a way to match a single entity by its ancestor.





Find the answer here

What's the correct way to instantiate an IRepository class from the Controller?

Programmer Question


I have the following project layout:



MVC UI
|...CustomerController (ICustomerRepository - how do I instantiate this?)

Data Model
|...ICustomerRepository

DAL (Separate Data access layer, references Data Model to get the IxRepositories)
|...CustomerRepository (inherits ICustomerRepository)


What's the correct way to say ICustomerRepository repository = new CustomerRepository(); when the Controller has no visibility to the DAL project? Or am I doing this completely wrong?





Find the answer here

Logic behind plugin system?

Programmer Question


I have an application in PHP (private CMS) that I would like to rewrite and add some new things - I would like to be able to extend my app in an easier way - through plugins



But the problem is - I don't know how to achieve "pluggability", how to make system that recognizes plugins and injects them into the app?



So, what's the logic of a simple plugin system?





Find the answer here

Automated Oracle Schema Migration Tool

Programmer Question


What are some tools (commercial or OSS) that provide a GUI-based mechanism for creating schema upgrade scripts? To be clear, here are the tool responsibilities:




  • Obtain connection to recent schema version (called "source").

  • Obtain connection to previous schema version (called "target").

  • Compare all schema objects between source and target.

  • Create a script to make the target schema equivalent to the source schema ("upgrade script").

  • Create a rollback script to revert the source schema, used if the upgrade script fails (at any point).

  • Create individual files for schema objects.



The software must:




  • Use ALTER TABLE instead of DROP and CREATE for renamed columns.

  • Work with Oracle 10g or greater.

  • Create scripts that can be batch executed (via command-line).

  • Trivial installation process.

  • (Bonus) Create scripts that can be executed with SQL*Plus.



Here are some examples (from StackOverflow, ServerFault, and Google searches):





Software that does not meet the criteria, or cannot be evaluated, includes:




  • TOAD

  • PL/SQL Developer - Invalid SQL*Plus statements. Does not produce ALTER statements.

  • SQL Fairy - No installer. Complex installation process. Poorly documented.

  • DBDiff - Crippled data set evaluation, poor customer support.

  • OrbitDB - Crippled data set evaluation.

  • SchemaCrawler - No easily identifiable download version for Oracle databases.

  • SQL Compare - SQL Server, not Oracle.

  • LiquiBase - Requires changing the development process. No installer. Manually edit config files. Does not recognize its own baseUrl parameter.



The only acceptable crippling of the evaluation version is by time. Crippling by restricting the number of tables and views hides possible bugs that are only visible in the software during the attempt to migrate hundreds of tables and views.





Find the answer here

UPDATE and INSERT differences in syntax is an inconvenience

Programmer Question


I was going through this article today.



http://vinothbabu.com/2010/05/08/update-and-insert-differences-in-syntax-is-an-inconvenience/



I was not able to understand this part of the code written by the author.



    list($sets,$cols,$values)=escape_arr($sets);

$insert_sql=�INSERT INTO `avatars` �.implode(�,',$cols).�
VALUES(�.implode(�,',$values).�)�;

$update_sql=�UPDATE `avatars` SET �.implode(�,',$sets).�
WHERE userid=$userid LIMIT 1?;


and finally the conclusion part of the article.





Find the answer here

Friday, May 7, 2010

Remove duplicate records/objects uniquely identified by multiple attributes

Programmer Question


I have a model called HeroStatus with the following attributes:




  • id

  • user_id

  • recordable_type

  • hero_type (can be NULL!)

  • recordable_id

  • created_at



There are over 100 hero_statuses, and a user can have many hero_statuses, but can't have the same hero_status more than once.



A user's hero_status is uniquely identified by the combination of recordable_type + hero_type + recordable_id. What I'm trying to say essentially is that there can't be a duplicate hero_status for a specific user.



Unfortunately, I didn't have a validation in place to assure this, so I got some duplicate hero_statuses for users after I made some code changes. For example:



user_id = 18
recordable_type = 'Evil'
hero_type = 'Halitosis'
recordable_id = 1
created_at = '2010-05-03 18:30:30'

user_id = 18
recordable_type = 'Evil'
hero_type = 'Halitosis'
recordable_id = 1
created_at = '2009-03-03 15:30:00'

user_id = 18
recordable_type = 'Good'
hero_type = 'Hugs'
recordable_id = 1
created_at = '2009-02-03 12:30:00'

user_id = 18
recordable_type = 'Good'
hero_type = NULL
recordable_id = 2
created_at = '2009-012-03 08:30:00'


(Last two are not a dups obviously. First two are.) So what I want to do is get rid of the duplicate hero_status. Which one? The one with the most-recent date.



I have three questions:




  1. How do I remove the duplicates using a SQL-only approach?


  2. How do I remove the duplicates using a pure Ruby solution? Something similar to this: http://stackoverflow.com/questions/2790004/removing-duplicate-objects.


  3. How do I put a validation in place to prevent duplicate entries in the future?






Find the answer here

What data (if any) persists across web-requests in Ruby on Rails?

Programmer Question


I decided to use the singleton design pattern while creating a view helper class. This got me thinking; will the singleton instance survive across requests? This led to another question, Which variables (if any) survive across web requests and does that change depending on deployment? (Fastcgi, Mongrel, Passenger, ...)



I know that Controller instance variables aren't persisted. I know Constants are persisted (or reloaded?). But I don't know about class variables, instance variables on a class, Eigenclasses, ...





Find the answer here

Random numbers from binomial distribution

Programmer Question


I need to generate quickly lots of random numbers from binomial distributions for dramatically different trial sizes (most, however, will be small). I was hoping not to have to code an algorithm by hand (see, e.g., this related discussion from November), because I'm a novice programmer and don't like reinventing wheels. It appears Boost does not supply a generator for binomially distributed variates, but TR1 and GSL do. Is there a good reason to choose one over the other, or is it better that I write something customized to my situation? I don't know if this makes sense, but I'll alternate between generating numbers from uniform distributions and binomial distributions throughout the program, and I'd like for them to share the same seed and to minimize overhead. I'd love some advice or examples for what I should be considering.





Find the answer here

What is the proper way to check the previous value of a field before saving an object? (Using Django)

Programmer Question


I have a Django Model with updated_by and an approved_by fields, both are ForeignKey fields to the built-in (auth) User models.



I am aware that with updated_by, it's easy enough to simply over-ride the .save() method on the Model, and shove the request.user in that field before saving.



However, for approved_by, this field should only ever be filled in when a related field (date_approved) is first filled in. I'm somewhat certain that I can check this logically, and fill in the field if the previous value was empty.



What is the proper way to check the previous value of a field before saving an object?



I do not anticipate that date_approved will ever be changed or updated, nor should there be any reason to ever update the approved_by entry.



UPDATE:

Regarding forms/validation, I should have mentioned that none of the fields in question are seen by or editable by users of the site. If I have misunderstood, I'm sorry, but I'm not sure how forms and validation apply to my question.





Find the answer here

Thursday, May 6, 2010

Proper binding data to combobox and handling its events.

Programmer Question


Hi guys.



I have a table in SQL Server which looks like this:



ID Code Name     Surname
1 MS Mike Smith
2 JD John Doe
3 UP Unknown Person


and so on...



Now I want to bind the data from this table into the ComboBox in a way that in the ComboBox I have displayed value from the Code column.



I am doing the binding in this way:



SqlDataAdapter sqlAdapter = new SqlDataAdapter("SELECT * FROM dbo.Users ORDER BY Code", MainConnection);
sqlAdapter.Fill(dsUsers, "Users");
cbxUsers.DataSource = dsUsers.Tables["Users"];
cmUsers = (CurrencyManager)cbxUsers.BindingContext[dsUsers.Tables["Users"]];
cbxUsers.DisplayMember = "Code";


And this code seems to work. I can scroll through the list of Codes. Also I can start to write code by hand and ComboBox will autocomplete the code for me.



However, I wanted to put a label at the top of the combobox to display Name and Surname of the currently selected user code.



My line of though was like that: "So, I need to find an event which will fire up after the change of code in combobox and in that event I will get the current DataRow..."



I was browsing through the events of combobox, tried many of them but without a success.



For example:



private void cbxUsers_SelectionChangeCommitted(object sender, EventArgs e)
{
if (cmUsers != null)
{
DataRowView drvCurrentRowView = (DataRowView)cmUsers.Current;
DataRow drCurrentRow = drvCurrentRowView.Row;
lblNameSurname.Text = Convert.ToString(drCurrentRow["Name"]) + " " + Convert.ToString(drCurrentRow["Surname"]);
}
}


This give me a strange results. Firstly when I scroll via mouse scroll it doesn't return me the row wich I am expecting to obtain. For example on JD it shows me "Mike Smith", on MS it shows me "John Doe" and on UP it shows me "Mike Smith" again!
The other problem is that when I start to type in ComboBox and press enter it doesn't trigger the event.



However, everything works as expected when I bind data to lblNameSurname.Text in this way:



lblNameSurname.DataBindings.Add("Text", dsusers.Tables["Users"], "Name");


The problem here is that I can bind only one column and I want to have two. I don't want to use two labels for it (one to display name and other to display surname).



So, what is the solution to my problem?



Also, I have one question related to the data selection in ComboBox. Now, when I type something in the combobox it allows me to type letters that are not existing in the list.
For example, I start to type "J" and instead of finishing with "D" so I would have "JD", I type "Jsomerandomtexthere". Combobox will allow that but such item does not exists on the list. In other words, I want combobox to prevent user from typing code which is not on the list of codes.



Thanks in advance for your time.





Find the answer here

DefaultStyledDocument.styleChanged(Style style) may not run in a timely manner

Programmer Question


I'm experiencing an intermittent problem with a class that extends javax.swing.text.DefaultStyledDocument. This document is being sent to a printer. Most of the time the formatting of the document looks correct, but once in a while it doesn't. It looks like some of the changes in the formatting have not been applied.



I took a look at the DefaultStyledDocument.styleChanged(Style style) code:



/**
* Called when any of this document's styles have changed.
* Subclasses may wish to be intelligent about what gets damaged.
*
* @param style The Style that has changed.
*/
protected void styleChanged(Style style) {
// Only propagate change updated if have content
if (getLength() != 0) {
// lazily create a ChangeUpdateRunnable
if (updateRunnable == null) {
updateRunnable = new ChangeUpdateRunnable();
}

// We may get a whole batch of these at once, so only
// queue the runnable if it is not already pending
synchronized(updateRunnable) {
if (!updateRunnable.isPending) {
SwingUtilities.invokeLater(updateRunnable);
updateRunnable.isPending = true;
}
}
}
}

/**
* When run this creates a change event for the complete document
* and fires it.
*/
class ChangeUpdateRunnable implements Runnable {
boolean isPending = false;

public void run() {
synchronized(this) {
isPending = false;
}

try {
writeLock();
DefaultDocumentEvent dde = new DefaultDocumentEvent(0,
getLength(),
DocumentEvent.EventType.CHANGE);
dde.end();
fireChangedUpdate(dde);
} finally {
writeUnlock();
}
}
}


Does the fact that SwingUtilities.invokeLater(updateRunnable) is called, rather than invokeAndWait(updateRunnable), mean that I can't count on my formatting changes appearing in the document before it is rendered?



If that is the case, is there a way to ensure that I don't proceed with rendering until the updates have occurred?





Find the answer here

Postgres 8.3: "ERROR: cached plan must not change result type"

Programmer Question


This exception is being thrown by the PostgreSQL 8.3 server to my application.
Does anyone know what this error means and what I can do about it?



ERROR:  cached plan must not change result type
STATEMENT: select code,is_deprecated from country where code=$1




Find the answer here

How can is add switch application functionality?

Programmer Question


How can I add a Switch application menu item on a Screen?





Find the answer here

Valid applications of member hiding with the new keyword in c#

Programmer Question


I've been using c# since version 1, and have never seen a worthwhile use of member hiding. Do you know of any?





Find the answer here

Wednesday, May 5, 2010

What's wrong with this C# CodeSnippet?

Programmer Question


I've made snippets before but I must be overlooking something really simple; I cannot figure out where the error is in this snippet...



<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>Throw NotImplementedException()</Title>
<Author>olaffuB</Author>
<Shortcut>nie</Shortcut>
<Description>Quickly add a new NotImplementedException() to code.</Description>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>TODO</ID>
<Default></Default>
</Literal>
</Declarations>
<Code Language="C#">
<![CDATA[throw new NotImplementedException("$TODO$"); // TODO: $TODO$]]>
</Code>
</Snippet>




Basically, when I got to import the snippet, it says that it is "invalid". The file name is "nie.snippet". Thanks!





Find the answer here

How do I truncate a .NET string?

Programmer Question


I apologize for such a question that likely has a trivial solution, but I strangely could not find a concise API for this problem.



Essentially, I would like to truncate a string such that it its length is not longer than a given value. I am writing to a database table and want to ensure that the values I write meet the constraint of the column's datatype.



For instance, it would be nice if I could write the following:



string NormalizeLength(string value, int maxLength)
{
return value.Substring(0, maxLength);
}


Unfortunately, this raises an exception because maxLength exceeds the string boundaries. Of course, I could write a function like the following, but I was hoping that something like this already exists.



string NormalizeLength(string value, int maxLength)
{
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}


Where is the elusive API that performs this task? Is there one?





Find the answer here

Apple Mac Software Development

Programmer Question


I'm planning on developing an Apple Mac application which will collect hardware information from the host Mac and also installed software info. The hardware and software info will be collected in an encrypted XML file and then posted back to a website. The application should run as a "service" or background process on the Mac and can be configured to collect the data on a frequent basis defined by another encrypted XML config file.



I've done plenty of Windows based software development but never on the Mac. Can anybody point me in the direction of any useful info on how to develop on the Mac, collect hardware and software info, export to an XML file, file encryption and packaging a compiled app to run as a service? Is either Objective C, Cocoa or Ruby a possible option?



Many thanks for your help in advance!





Find the answer here

Possible to assign a data type to an anonymous type's members in a linq query?

Programmer Question


If I have a linq query that creates the anonymous type below:



                    select new
{
lf.id,
lf.name,
lf.desc,
plf.childId
};


Is it possible to assign a specific type to one of the members? Specifically I would like to make lf.id a null-able int rather than an int...





Find the answer here

NoSQL for filesystem storage organization and replication?

Programmer Question


We've been discussing design of a data warehouse strategy within our group for meeting testing, reproducibility, and data syncing requirements. One of the suggested ideas is to adapt a NoSQL approach using an existing tool rather than try to re-implement a whole lot of the same on a file system. I don't know if a NoSQL approach is even the best approach to what we're trying to accomplish but perhaps if I describe what we need/want you all can help.




  1. Most of our files are large, 50+ Gig in size, held in a proprietary, third-party format. We need to be able to access each file by a name/date/source/time/artifact combination. Essentially a key-value pair style look-up.

  2. When we query for a file, we don't want to have to load all of it into memory. They're really too large and would swamp our server. We want to be able to somehow get a reference to the file and then use a proprietary, third-party API to ingest portions of it.

  3. We want to easily add, remove, and export files from storage.

  4. We'd like to set up automatic file replication between two servers (we can write a script for this.) That is, sync the contents of one server with another. We don't need a distributed system where it only appears as if we have one server. We'd like complete replication.

  5. We also have other smaller files that have a tree type relationship with the Big files. One file's content will point to the next and so on, and so on. It's not a "spoked wheel," it's a full blown tree.



We'd prefer a Python, C or C++ API to work with a system like this but most of us are experienced with a variety of languages. We don't mind as long as it works, gets the job done, and saves us time. What you think? Is there something out there like this?





Find the answer here

Tuesday, May 4, 2010

Are there any major problems with using .NET One-Click deployment?

Programmer Question


I'm deploying an app to an unknown number of clients. It'll be 5-10 to start, couple dozen eventually. I'm thinking of making a different web folder for each client, so I can control updates and roll them out in a gradual manner.



Are there any major known issues with One-Click deployment? Am I going to commit suicide shortly after golive?





Find the answer here

How to show div when user reach bottom of the page?

Programmer Question


When user scrolls to the bottom of the page I want to show some div, with jQuery of course. And if user scrolls back to he top, div fade out.
So how to calculate viewport (or whatever is the right name) :)



Thanks





Find the answer here

Quantum Computing and Encryption Breaking

Programmer Question


Ok, I read a while back that Quantum Computers can break most types of hashing and encryption in use today in a very short amount of time(I believe it was mere minutes). How is it possible? I've tried reading articles about it but I get lost at the a quantum bit can be 1, 0, or something else. Can someone explain how this relates to cracking such algorithms in plain English without all the fancy maths?





Find the answer here

Is there a way to put relationships/contraints into CSS?

Programmer Question


In every design tool or art principle I've heard of, relationships are a central theme. By relationships I mean the thing you can do in Adobe Illustrator to specify that the height of one shape is equal to half the height of another. You cannot express this information in CSS. CSS hard-codes all values. Using a language like LESS that allows variables and arithmetic you can get closer to relationships but it's still a CSS variant.



This inability in my mind is the biggest problem with CSS. CSS is supposed to be a language that describes the visual component of a Web page but it ignores relationships and contraints, ideas that are at the core of art.



How possible is it to imagine a new Web design language that can express relationships and contraints that can be implemented in JavaScript using the current CSS properties?





Find the answer here

Overriding classes/functions from a .dll.

Programmer Question


Say I have class A and class B. B inherits from class A, and implements a few virtual functions. The only problem is that B is defined in a .dll. Right now, I have a function that returns an instance of class A, but it retrieves that from a static function in the .dll that returns an instance of class B. My plan is to call the created object, and hopefully, have the functions in the .dll executed instead of the functions defined in class A. For some reason, I keep getting restricted memory access errors. Is there something I don't understand that will keep this plan from working?





Find the answer here

LinkWithin

Related Posts with Thumbnails