q:
I want to be able to use a function such as writefln() but without having to add import std.stdio at the top of the file.

Another way to explain it is the way you do it in C++. You can type std::cout << "Test"; and that will stop you from having to add using namespace std;. I want to do the same thing, but in D.

[A]
I don't think you can do that. The
```
import
```
statement in D does more than the
```
using namespace
```
statement does in C++. It also replaces the
```
#include
```
preprocessor directive.


q:
I am using running a simple find all and paginating with willpaginate, but I'd also like to have the query sorted by the user. The first solution that came to mind was just use a params[:sort]

http://localhost:3000/posts/?sort=created_at+DESC

@posts = Post.paginate :page => params[:page], :order => params[:sort]

But the problem with his approach is that the query is defaulting as sorting by ID and I want it to be created_at.

Is this a safe approach to sorting and is there a way to default to created_at?

[A]
In general, the way to supply default values for Hash and Hash-like objects is to use
```
fetch
```
:
```
```
params.fetch(:sort){ :created_at }
```
```
A lot of people just use
```
||
```
though:
```
```
params[:sort] || :created_at
```
```
I prefer
```
fetch
```
myself as being more explicit, plus it doesn't break when
```
false
```
is a legitimate value.

s: huggingface

c: devops

d: intermediate


q:
I have an old ASP.NET 1.1 site that I am maintaining.  We are working with Google to place analytics code on all pages.  Since I can't take advantage of master pages in 1.1, I have my pages include headers/footers/sidebars with User Controls.

What came to mind first is to place the JavaScript in my footer ascx control so it appears on every page.  But I don't think I can link to a JavaScript file from a user control.

Any ideas on what I can do to get this js code placed on every page in my site?

[A]
What keeps you from simply referencing your script in the user control?
```
```
<asp:SomeControl ID="SomeControl1" runat="server>
  <script src="some.js" type="text/javascript"></script>
</asp:SomeControl>
```
```
You could also do this:
```
```
protected void Page_Load(object sender, EventArgs e)
{
  Literal some_js = new Literal();
  some_js = "<script type='text/javascript' src='some.js'></script>";
  this.Header.Controls.Add(some_js);
}
```
```
(Obviously, the second approach would still force you to modify the pages themselves, unless they inherit from a common parent you control.)


q: Sharepoint isn't the speediest of server applications, and I've read about a few tips to speed it up. What steps do you think are necessary to increase performance so it can be used to host a high traffic site?

[A]
At the end of the day SharePoint is just a complicated web site with all the standard components.
In order to optimize performance you need to analyze each component and determine which one is a problem, and then adjust it accordingly.
We're in the process of implementing a 1000 concurrent user sharepoint website, which may or may not be large, however some steps we are taking are:
Implementing a detailed caching strategy, to cache webpart content intelligently.
Use load balanced servers to ensure all our hardware is utilised rather then lying idle.
We've undertaken capacity planning given the existing solution, so we have a good idea which component is the bottleneck for us. (The SQL Server), so we will ensure the server can cope with expected load and future growth of the site.
We're also using hardware load balancers which will ensure our network and the related servers operate as expected, and again this is something to investigate before you implement a sharepoint website.
We're also ensuring our webparts don't generate unnecessary html, and don't return unnecesary data, as this will slow down loading times.
Something which I definately think is a good idea is to have a goal to work towards, as you can spend a huge amount of money and time optimizing SharePoint, which may prove unnecessary.


q:
Is the asp.net membership system used over wcf (transport security turned on) enough for high security internet scenarios with thousands of clients spread all over the internet?

I'm just evaluating possible solutions and wanted to know if this might fit in this category.

If not, what would be the best method to provide high security access over wcf for internet scenarios?

[A]
Yes it will work; and with SSL/transport security the authentication will be protected by the transport. Will it scale? That's harder to say; it depends on too many factors.
OK so by high security you're looking for non-repudiation? That's trickier; because of course people can share usernames and passwords. But even if you also used client certificates, well people share certificates. I'd certainly look at
WCF auditing
in combination with the authentication and set SupressAuditFailure to be false.


q:
I have a ListCtrl that displays a list of items for the user to select. This works fine except that when the ctrl is not large enough to show all the items, I want it to expand downwards with a vertical scoll bar rather than using a horizontal scroll bar as it expands to the right.

The ListCtrl's creation:

self.subjectList = wx.ListCtrl(self, self.ID_SUBJECT, style = wx.LC_LIST | wx.LC_SINGLE_SEL | wx.LC_VRULES)

Items are inserted using wx.ListItem:

item = wx.ListItem()
item.SetText(subject)
item.SetData(id)
item.SetWidth(200)
self.subjectList.InsertItem(item)

[A]
Use the
wxLC_REPORT
style.
```
```
import wx

class Test(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.test = wx.ListCtrl(self, style = wx.LC_REPORT | wx.LC_NO_HEADER)

        for i in range(5):
            self.test.InsertColumn(i, 'Col %d' % (i + 1))
            self.test.SetColumnWidth(i, 200)

        for i in range(0, 100, 5):
            index = self.test.InsertStringItem(self.test.GetItemCount(), "")
            for j in range(5):
                self.test.SetStringItem(index, j, str(i+j)*30)

        self.Show()

app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()
```
```


q:
Can someone tell me how i can change the .xml file that a flash movie loads using c#.  ie: i would like an ActionScript variable that defines the location of the flash movie. I would like to be able to change this variable using c# if possible.

i dont really know how it would look, but something like:

<object xmlpath='" + myCSharpVar + "'" ...></object>

I just starting this, but my ultimate goal is to create a .swf movie that can load an xml file that specifies images, etc.  However i want to use the same .swf file in multiple places and only have to change a ref to what xml file it uses - and my Flash/ActionScript skills are very rusty.

To clear it up a bit, in AS you can do something like:

loader.load( new URLRequest("IWantThisNameDynamic.xml") );

how can i define that xml file in my c# code?

[A]
I'm quite sure you cannot "create" your own attributes for the object tag. At least not without consulting with the w3c ;-)
Passing values to flash is done via the "flashvar"-param:
```
```
<object ...>
    <param name="flashvars" value="&xmlpath=<path to xml>"/>
  </object>
```
```
In the flash-movie you can now access the path to your xml via the "xmlpath"-variable.


q:
I have the following javascript:

$.ajax({
  type: "POST",
  dataType: "json",
  url: "/Home/Submit",
  data: {
    email: strEmail,
    message: strMessage
  },
  success: function(result) {
    //alert('here');
    alert(result.message);
  },
  error: function(error) {
    alert(error);
  }
});

This makes a call to this function:

public JsonResult Submit(string Email, string Message) {
  return Json(new {
    message = "yep"
  });
}

This works fine in debug mode on the inbuilt webserver.

However if I go to the virtual dir directly it does not and hits the error bit. I attached to the process and the code behind never gets hit.

I am using Vista.

Additionally how do you get the error description in the bit where it says  alert(error);

Thanks,

Alex

[A]
Predicate is a delegate. You can not inherit from a delegate type.
If you want to get the inverted value, use the following:
```
```
Predicate<T> p;
Predicate<T> inverted = t => !p(t);
```
```


q: For example, I want just the "filename" of a file in a field.  Say I have myimage.jpg  I only want to display "myimage"  How do I get just that?

[A]
Use the List functions to your advantage.
```
```
<cfset FileName = ListDeleteAt(FileFullName, ListLen(FileFullName, "."), ".")>
```
```
Be aware that this only works for file names that actually
have
a file extension (that is defined as the thing after the last dot). To make it safer, the following is better:
```
```
<cfset ExtensionIndex = ListLen(FileFullName, ".")>
<cfif ExtensionIndex gt 1>
  <cfset FileExt  = ListGetAt(ExtensionIndex , ".")>
  <cfset FileName = ListDeleteAt(FileFullName, ExtensionIndex, ".")>
<cfelse>
  <cfset FileExt  = "">
  <cfset FileName = FileFullName>
</cfif>
```
```
To complicate things a bit further: There may be files that start with a dot. There may be file names that contain many adjacent dots. List functions return wrong results for them, as they ignore empty list elements. There may also be files that have dots, but no extension. These can only be handled if you provide an extension white list:
```
ListFindNoCase(FileExt, "doc,xls,ppt,jpg")
```
. If you want to account for all of this, you probably need to resign to a reguar expression:
```
```
<cfset FileExtRe = "(?:\.(?:doc|xls|ppt|jpg))?$">
<cfset FileName  = REReplaceNoCase(FileFullName, FileExtRe, "")>
```
```
To split file name from path, ColdFusion provides distinct functions that also handle platform differences:
```
GetFileFromPath()
```
and
```
GetDirectoryFromPath()
```


q:
Is there a way to change the colors used by plain Win32 menus (background, text, and highlight) for a single process, without using SetSysColors?

(SetSysColors does a global change, which is bad, and if you crash or forget to set the colors back with SetSysColors again before exiting, they will not be restored until you logout.)

[A]
The SetMenuInfo() API is your friend. It lets you apply any brush to paint your menu's background.
Something along these lines should solve your problem:
```
```
MENUINFO mi = { 0 };
mi.cbSize = sizeof(mi);
mi.fMask = MIM_BACKGROUND|MIM_APPLYTOSUBMENUS;
mi.hbrBack = hBrush;

HMENU hMenu = ::GetMenu(hWnd);
SetMenuInfo(hMenu, &mi);
```
```


q:
I'm trying this:

Type ThreadContextType = typeof(Application).GetNestedType("ThreadContext", System.Reflection.BindingFlags.NonPublic);
MethodInfo FDoIdleMi = ThreadContextType.GetMethod("FDoIdle", BindingFlags.NonPublic |
    BindingFlags.Instance, null, new Type[] { typeof(Int32) }, null);

ThreadContextType is ok but FDoIdleMi is null. I know there is something wrong in the GetMethod call because FDoIdle comes from the UnsafeNativeMethods.IMsoComponent interface.

How to do that? Thanks.

[A]
You need to fully-qualify the method name, because they're using explicit interface implementation:
```
```
Type type = typeof( Application ).GetNestedType( "ThreadContext",
    BindingFlags.NonPublic );
MethodInfo doIdle = type.GetMethod(
    "System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle",
    BindingFlags.NonPublic | BindingFlags.Instance );
```
```
For the record, reflecting on non-public members is generally bad practice, but you probably already know that.
EDIT
In the spirit of teaching a person to fish, I figured this out by calling
```
GetMethods(...)
```
on the type object, and examining the returned array to see how the methods were named. Sure enough, the names included the complete namespace specification.


q:
I'm using a ListView in C# to make a grid.  I would like to find out a way to be able to highlight a specific cell, programatically.  I only need to highlight one cell.

I've experimented with Owner Drawn subitems, but using the below code, I get highlighted cells, but no text!  Are there any ideas on how to get this working?  Thanks for your help.

//m_PC.Location is the X,Y coordinates of the highlighted cell.

void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
    if ((e.ItemIndex == m_PC.Location.Y) && (e.Item.SubItems.IndexOf(e.SubItem) == m_PC.Location.X))
        e.SubItem.BackColor = Color.Blue;
    else
        e.SubItem.BackColor = Color.White;
    e.DrawBackground();
    e.DrawText();
}

[A]
You can do this without owner-drawing the list:
```
```
// create a new list item with a subitem that has white text on a blue background
ListViewItem lvi = new ListViewItem( "item text" );
lvi.UseItemStyleForSubItems = false;
lvi.SubItems.Add( new ListViewItem.ListViewSubItem( lvi,
    "subitem", Color.White, Color.Blue, lvi.Font ) );
```
```
The Color arguments to the ListViewSubItem constructor are controlling the foreground and background color of the subitem. The critical thing to do here is set
```
UseItemStyleForSubItems
```
to False on the list item, otherwise your color changes will be ignored.
I think your owner-draw solution would have worked as well, but you have to remember to change the text (foreground) color when you change the background to blue, otherwise the text will be hard to see.


q:
We need to implement a large-scale key-value store (let's say up to 500GB) and BerkeleyDB seemed like it might be a decent option, but we would really like it to be network accessible. This led me to look at memcachedb. I haven't found much on the web where people talk about actual experiences with memcachedb, so my questions are, if you've used memcachedb:

would you recommend using it for a large k-v store?

if not, why not?

Thanks in advance!

Francis

[A]
I have used memcached a little bit in one of my projects. I think it's a very efficient and scalable caching platform. By changing small configurations, you're able to replicate the cached objects in more than one server. Facebook uses memacached for their in-memory storage and it's a large scale entity on the web. This gives a thumb up for memcahced.
The only problem I faced in implementation is that doesn't automatically accept objects to store. You will need to serialize the objects before storing which may be a little bit confusing at the beginning.
FYI, there is a nother caching platform produced by Microsoft called: Velocity. You may need to take a look on it:
http://www.microsoft.com/downloads/details.aspx?FamilyId=B24C3708-EEFF-4055-A867-19B5851E7CD2&displaylang=en


q: I know a fair bit about the Windows Task Manager in XP, but I would like to understand it better in Vista.  What is the difference between "Working Set (Memory)" and "Memory (Private Working Set)".  What is the Paged Pool, what is the NP Pool (Non-Paged?).  How do I use these to determine what is going on with memory usage?  As an aside, when you minimize a program it frequently returns 90% of the memory it is using.  Is there any way to do this without minimizing it?

[A]
This MSDN blog entry
might be informative on the first part of the question. A brief excerpt:
Working set is the subset of virtual pages that are resident in physical memory only; this will be a partial amount of pages from that process.
As discussed in the article, the part about private versus not-private has to do with memory used by the process that can be shared by other processes. If you can't share the memory (perhaps the memory is used by the image of a DLL had to be relocated in memory), it becomes private. Heap memory is also always going to be private.
The reason you see the memory drop dramatically when minimizing a program is that Windows automatically trims the working set of a process whenever it its main window is minimized. See
this Microsoft KB article
for more, including instructions on how to do this yourself.
The paged pool and non-paged pool memory refers to kernel memory used by the process. Memory from the paged pool can be paged out (removed from physical memory when memory pressure increases). Memory from the non-paged pool will always remain in physical memory, so generally it's preferable for this to stay small. Unless you're writing device drivers, though, as a user-mode application developer you generally won't need to worry about these two items.


q:
First some background. I recently went for an interview and some of the questions asked to me was about Enterprise Content Management. Obviously, I did not have any experience and did not get the offer.

But, it increased my curiosity and tried Internet to get some info on the topic. Wikipedia made me more confused with even more buzzwords. Most of the stuff on the web is marketing related and relevant to specific products like Sharepoint or Drupal etc.

I need some help in understanding more about the topic or the domain in simpler terms. What is the requirement to use it? What kind of companies use it? What are the problem areas it tries to address? Any popular use cases? Any places where it looks like a good fit but it is not actually?

Lastly, any good book or articles on the topic without being specific to any product?

[A]
CMS (Content Management System) describe systems that are used to manage content :-) as for example Joomla, Drupal, Sharepoint and etc.
Content management means document, records, processes and other information related to your company business management.
Enterprise Content Management, as far as I know is this "Content management" concept applied to a organization. The mainly focus is to Capture, Manage, Store, Preserve, and Deliver content and documents related to the organization.


q: I need a regex that matches all strings ending in .cs, but if they end in .g.cs they should not match. I'm using .NET regular expressions.

[A]
This will match the end if it's .cs but not .g.cs
```
```
(?<!\.g)\.cs$
```
```
For the entire string start to finish, something like this:
```
```
^.*(?<!\.g)\.cs$
```
```


q: I have a fairly simple addition to the HTTP standard.  An ambitious goal I know, but I'd at least like to submit a proposal and get feedback on the idea.  What is the proper forum/method of doing so?

[A]
According to W3C's
HTTP page
:
Now that both HTTP extensions and
  HTTP/1.1 are stable specifications,
  W3C has closed the HTTP Activity. The
  Activity has achieved its goals of
  creating a successful standard that
  addresses the weaknesses of earlier
  HTTP versions.
An effort to revise HTTP/1.1 started
  in the
IETF httpbis Working Group
The page from the latter link has a mailing list you can join, as well as the scope of the working group. You may well be able to get feedback about the merit of your idea in the abstract, but certainly don't get your hopes up at effecting change.


q:
The calculations in my code are well-tested, but because there is so much GUI code, my overall code coverage is lower than I'd like. Are there any guidelines on unit-testing GUI code? Does it even make sense?

For example, there are graphs in my app. I haven't been able to figure out how to automate the testing of the graphs. It takes a human eye, AFAIK, to check if the graph is correct.

(I'm using Java Swing)

[A]
Designs like MVP and MVC typically try to abstract as much logic out of the actual GUI as possible. One very popular article about this is
"The Humble Dialog Box"
by Michael Feathers. Personally I've had mixed experiences with trying to move logic out of the UI - sometimes it's worked very well, and at other times it's been more trouble than it's worth. It's somewhat outside my area of expertise though.


q:
In VS2008 I have written a C# service, an installer, and have created a setup package to install it. The service needs to load an xml file to operate. Where is the best place to put this file in the various filesystem folders offered by the VS setup project, and how do I then refer to these paths from my code?

I should point out the the service runs as LocalService, which means that the ApplicationData folder offered by the "User's Application Data Folder" item in the VS setup project is not accessible, even when "Install for all users" is used during installation. I could easily hack around this, but would like to understand best practice.

[A]
I am not sure which place is better to store the XML file. I don't think it will matter alot. But if you need to get special folder path in the system you can use Environment class to do so. The following line of code get the path of the Program Files:
```
```
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
```
```


q: In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance?

[A]
The official tutorial
may be of some use to you.
Class
Package
Subclass
(same pkg)
Subclass
(diff pkg)
World
```
public
```
+
+
+
+
+
```
protected
```
+
+
+
+
no modifier
+
+
+
```
private
```
+
+ : accessible
blank : not accessible


q:
It's been my experience that some security software (like Symantec's Norton AntiVirus) oftentimes prohibit their removal from a Windows system via the "Add or Remove Programs" utility, going so far as to occasionally require a removal program obtained from Symantec's homepage.  (I assume this it to prevent a malicious program from disabling the security software... any other reason?)

How can a program be configured to resist removal via a system's uninstall utility, or via deleting the program's directory?  Is Norton the only software suite that employs this technique, or is this widespread amongst security software?  Are there similar techniques that can be used on Unix / -like systems?

[A]
Norton is not the only one that does this, however McAfee and Norton are the only ones who make it almost impossible to remove the software.  Not because they care about viruses or security threats, they don't want to give up control of the system.  Many other Antivirus software that works just as well if not better than Norton, like AVG, Avast, and others do allow you to uninstall from the add remove.  If they tell you anything different they are just lying because you have to physically click the add remove programs to run the uninstall process.  There is no programmatic way to do this.
They do this by just hijacking the uninstall with a custom process.  There is not really a standardized uninstall method.  The closest to that is the MSI package that Microsoft provides, however that doesn't have to be used, and even if they do use it they can customize the operations to do whatever they want when uninstalling.
In NTFS you can lock folders and files that are currently executing in memory.  Norton either uses this method or uses the service running in the background to prevent it.
Norton and McAfee are some of the most invasive resource hogs that you can never get out of your system once installed.  They don't do this for security.  They do this because they are in a market that has Free alternatives that are 20 times better than their legacy software.  So they strike deals with the OEM's to install their software by default in the hopes that people will continue to pay yearly subscriptions to them.  On top of that if they make it really hard to remove, some people won't be bothered and just pay up.


q:
I am working on a winforms html editor with multiple editor windows as each editor window will be written to a database field.

I am creating the editor windows as a control array and was hoping to just have one toolbar above them that would handle the events such as apply bold, italic... based on the window I was currently in. Unfortunately obviously the event handler of an event on the toolbar doesn't know what the control selected before it was.

Is there a way to get this or should I be adding an onenter event to each editor window and storing statically the last editor window used.

[A]
I'm not familiar with the types of events you mention, and I'm probably missing something, but it's common in WinForms development to have events fire and provide information about the sender as well as the event, conforming to the
EventHandler
delegate?
```
```
[SerializableAttribute]
[ComVisibleAttribute(true)]
public delegate void EventHandler(
    Object sender,
    EventArgs e
)
```
```
This is how
System.Windows.Forms.Control.Click
operates.
Could you follow this example, where
```
sender
```
would be the editor window in each case?


q:
Some iPhone applications, such as Pandora seem to directly manipulate the hardware volume and respond to physical volume button. How is this done?

AudioSessionServices allows you to get the current hardware output volume with the kAudioSessionProperty_CurrentHardwareOutputVolume property, but it is (allegedly) read-only.

[A]
They use the MPVolumeView, simple add it and it's makes the rest when the user touch it. Note: Doesn't work in iPhone Simulator. I think the release note also mentioned do not use it direct in Interface Builder.
```
```
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];
[self.view addSubview:volumeView];
[volumeView release];
```
```


q:
So am I crazy for considering doing a beta/production release on Glassfish V3 Prelude?
Since all of my content is dynamic, I'm not even thinking of bothering to set up apache in front either.  Doing so complicates the setup by requiring something like AJP or mod_jk and will not offer us much in terms of capability.

So there will be three war files on deployment.
3 JNDI data sources with about 90 connections parked, scaling up to 160 to a PGSQL datastore....

The three wars comprise a CMS system and a grails application?

Is my logic fatally flawed that I don't need to put apache in front of this setup?


q:
I'd like to create a script to manipulate Apache2 configuration directly, reading and writing its properties (like adding a new VirtualHost, changing settings of one that already exists).

Are there any libs out there, for Perl, Python or Java that automates that task?

[A]
This is the ultimate Apache configurator:
http://perl.apache.org/
exposes many if not all Apache internals to programs written in Perl.
For instance:
http://perl.apache.org/docs/2.0/api/Apache2/Directive.html
(Of course that it can do much much more than just configuring it).
On the other hand, it needs to be loaded and runs within Apache, it's not a config file parser/editor.


q: From what I understand, the parent attribute of a db.Model (typically defined/passed in the constructor call) allows you to define hierarchies in your data models. As a result, this increases the size of the entity group. However, it's not very clear to me why we would want to do that. Is this strictly for ACID compliance? I would like to see scenarios where each is best suited or more appropriate.

[A]
The only purpose of entity groups (defined by the parent attribute) is to enable transactions among different entities. If you don't need the transactions, don't use the entity group relationships.
I suggest you re-reading the
Keys and Entity Groups
section of the docs, it took me quite a few reads to grasp the idea.
Also watch these talks, among other things they discuss transactions and entity groups:
Building Scalable Web Applications with Google App Engine
Under the Covers of the Google App Engine Datastore


q:
What is the purpose of the colon before a block in Python?

Example:

if n == 0:
    print "The end"

[A]
The colon is there to declare the start of an indented block.
Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the
Python koan
“explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so
any
statement that
should
be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)
It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.
This question turns out to be a
Python FAQ
, and I found one of its answers by Guido
here
:
Why are colons required for the if/while/def/class statements?
The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:
```
```
if a == b
    print a
```
```
versus
```
```
if a == b:
    print a
```
```
Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.
Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.


q: What is a good resource to get started with Windows file system driver development for a newbie?

[A]
You might try
Windows Hardware Developer Central
, which has links to blogs, newsgroups, books, and other useful resources for driver authors.
I also recommend downloading and installing the
Windows DDK
and exploring some of the included samples. There should be various skeleton drivers that can be used as starting points for your custom work.


q:
Erlang support to partition its nodes into groups using the global_group module.
Further, Erlang supports adding nodes on the fly to the node-network. Are these two features usable with each other?

As far as I understand, you have to name every node on startup to use the global groups.

[A]
A node is an executing Erlang runtime
  system which has been given a name,
  using the command line flag -name
  (long names) or -sname (short names).
A hidden node is a node started with
  the command line flag -hidden.
  Connections between hidden nodes and
  other nodes are not transitive, they
  must be set up explicitly. Also,
  hidden nodes does not show up in the
  list of nodes returned by nodes().
  Instead, nodes(hidden) or
  nodes(connected) must be used. This
  means, for example, that the hidden
  node will not be added to the set of
  nodes that global is keeping track of.
So in short , yes, you need to give our node a name to be able other nodes to find it.
It feels that you either are asking without trying out or have a very complex question and maybe an example of what you are trying to accomplish could make it possible to give a better answer.


q:
How do I load MS Word document (.doc and .docx) to memory (variable) without doing this?:

wordApp.Documents.Open

I don't want to open MS Word, I just want that text inside.

You gave me answer for DOCX, but what about DOC? I want free and high performance solution - not to open 12.000 instances of Word to process all of them. :( Aspose is commercial product, and 900$ is a way too much for what I do.

[A]
If you are dealing with docx you can do this with out doing any interop with Word
.docx file actually a ZIP contains an XML file , you can read the XML
Please refer the below links
http://conceptdev.blogspot.com/2007/03/open-docx-using-c-to-extract-text-for.html
Office (2007) Open XML File Formats


q:
I am trying to use some pinvoke code to call a C function.  The function fills a buffer with data.

The structure is set up as a DWORD for the length, followed by a string.  How do I extract the string from the IntPtr?

 IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
 PInvokedFunction(buffer, nRequiredSize);
 string s = Marshal.PtrToStringAuto(buffer + 4); //this is an error.
 Marshal.FreeHGlobal(buffer);

[A]
The best I could come up with was the following, though the use of the UnmanagedMemoryStream seems a bit of a hack.
```
```
IntPtr buffer = Marshal.AllocHGlobal((int)nRequiredSize);
 PInvokedFunction(buffer, nRequiredSize);
 UnmanagedMemoryStream memStream = new UnmanagedMemoryStream(buffer.ToPointer(), nRequiredSize);
 memStream.Seek(4, SeekOrigin.Begin);
 IntPtr ptr = new IntPtr(memStream.PositionPointer);
 string s = Marshal.PtrToStringAuto(ptr);
 Marshal.FreeHGlobal(buffer);
```
```


q:
I'm having some trouble with Visual Studio 2008 on my Windows XP SP2 laptop.

What happens is that when I start a program with a few textboxes and stuff like that, the boxes are see-through. I can litteraly see through them and see what's on the underlaying screen. Like if I only have this Form showing and behind that my wallpaper, I can see my wallpaper through the Textbox, ComboBox, even through the small cracks between various elements.

i've searched the web but haven't encountered info on this yet. Does anybody know what might be causing this and how to solve it? I'm in the process of trying to see how the text in my TextBoxes is parsed, but I can't since I can't even enter anything. I click on the textbox and I'm focused on the desktop...

[A]
Hmmm... I'm not sure about this, but check the "Transparency" property of your main form. That's all I can think that it might be as of now...
Update: I meant the "
Opacity
" property, sorry.
Update 2: No, never mind, sorry. Right-click the "
TransparencyKey
" property, and press
```
Reset
```
to set it back to default.


q:
I have a std::multimap where key is a custom class. Something like this:

Class X {
public:
    std::string s;
    int x;
    operator <(const X& other) const { return s < other.s; }
};
std::multimap<X, int> mymap;

Now, I'd like to use upper_bound and lower_bound to iterate over all elements with the same value of "s". Do I need to implement some other operator for X (for example: ==). Or it will work properly just like this?

Also, what should I supply as argument for upper_bound and lower_bound? I assume I should create a dummy object with desired value of "s"?

[A]
you only need to provide an operator == and <.
upper_bound and lower_bound are just like any other find-type method, so you need the same kind of object to compare with - in your case, a 'dummy' object with the required value of s.
edit
: the comments are correct that you only need operator< for lower/upper_bound, and find. But if you want to call other methods on your container, you will need operator== as well. Eg. if you want to sort() your container, you will need operator==.
The 2 overloads you need for all STL containers are operator< and operator==. I find its best practise to implement them both.
Of course, the question could also be answered more fully by implementing a comparison functor in the map itself, not relying on the objects. This is often a good way to implement different ways of calling find() on the map.


q:
I still haven't got my head around decorators in Python.

I've already started using a lot of closures to do things like customize functions and classes in my coding.

Eg.

class Node :
    def __init__(self,val,children) :
        self.val = val
        self.children = children

def makeRunner(f) :
    def run(node) :
        f(node)
        for x in node.children :
            run(x)
    return run

tree=Node(1,[Node(2,[]),Node(3,[Node(4,[]),Node(5,[])])])

def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
printTree(tree)

As far as I can see, decorators are just a different syntax for doing something similar.

Instead of

def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)

I would write :

@makeRunner
def printTree(n) : print "%s," % n.val

Is this all there is to decorators? Or is there a fundamental difference that I've missed?

[A]
Are your examples real code, or just examples?
If they're real code, I think you overuse decorators, probably because of your background (i.e. you are used to other programming languages)
Stage 1: avoiding decorators
```
```
def run(rootnode, func):
    def _run(node): # recursive internal function
        func(node)
        for x in node.children:
            _run(x) # recurse
    _run(rootnode) # initial run
```
```
This run method obsoletes makeRunner. Your example turns to:
```
```
def pp(n): print "%s," % n.val
run(tree, pp)
```
```
However, this ignores completely generators, so…
Stage 2: using generators
```
```
class Node :
    def __init__(self,val,children) :
        self.val = val
        self.children = children

    def __iter__(self): # recursive
        yield self
        for child in self.children:
            for item in child: # recurse
                yield item

def run(rootnode, func):
    for node in rootnode:
        func(node)
```
```
Your example remains
```
```
def pp(n): print "%s," % n.val
run(tree, pp)
```
```
Note that the special method
```
__iter__
```
allows us to use the
```
for node in rootnode:
```
construct. If you don't like it, just rename the
```
__iter__
```
method to e.g.
```
walker
```
, and change the
```
run
```
loop into:
```
for node in rootnode.walker():
```
Obviously, the
```
run
```
function could be a method of
```
class Node
```
instead.
As you see, I suggest you use directly
```
run(tree, func)
```
instead of binding them to the name
```
printTree
```
, but you can use them in a decorator, or you can make use of the
```
functools.partial
```
function:
```
```
printTree= functools.partial(run, func=pp)
```
```
and from then on, you would just
```
```
printTree(tree)
```
```


q:
What is the state of native SVG support in the most popular browsers in their latest releases?

Internet explorer

Firefox

Opera

Safari

Chrome

Konqueror

Camino

[A]
Opera has native
SVG support
Firefox has native
SVG support
Internet Explorer does NOT include
SVG support
natively.
Safari has native
SVG support
for images and Fonts since version 3.1.
Camino contains native
SVG support
as per its own documentation
Chrome uses an old version of Web Kit to support
SVG natively
Konqueror has SVG support via a plugin
KSVG2
From 2007 a
here
is a list of the state of SVG support in many browsers


q:
What the best way to get up to speed on MathML and its usage in the world?

In particular I mean:

What do you use for rendering/editing it

Is it used in any commercial/open source applications that you can point me to

Is it popular and used a lot?

Are there any viewers that can be used inside a C#, C++, Java, ... application?

... (any other info available about MathML)

[A]
The
W3C's MathML homepage
is of course a good place to start. They have a list of software using MathML. There are two portions to the MathML specification: the presentation set, which will tell a rendering engine how to typeset the equation (for instance, distinguishing between a stacked vs. beveled fraction), and the content set, which will tell calculation engines how to interpret the equation (is y(x) a function y of x or two variables being multiplied?). Most applications will focus on one subset of MathML or the other depending on the scope of the application.
MathML is being used more and more widely and with good reason - MathML has all of the advantages of XML (for more information, see our white paper
MathML is XML
).
Design Science makes
WebEQ
, which includes components for editing and displaying MathML on your website. We also have an SDK version if you would like to include these components in a desktop application. WebEQ is Java based.
Hope this helps, but if you have more questions, feel free to email support@dessci.com.
Best wishes,
Autumn Cuellar, XML Specialist at Design Science


q:
MTOM is the W3C Message Transmission Optimization Mechanism, a method of efficiently sending binary data to and from web services.

How does it work in general?

[A]
If you put
Wireshark
(or enabled
System.Net Logging
) on the non-MTOM enabled service, you should see the SOAP requests with the binary data encoded as BASE64. Sending it as BASE64 increases the size of the binary data but (I assume) makes it more interoperable.
With MTOM, the SOAP messages are sent as MIME messages with the BASE64 encoding being replaced with a placeholder. The binary data is then placed between delimiters (which happens for each piece of binary data), and then placed at the end of the SOAP request. The binary data is then sent unencoded. IIRC, MTOM also determines whether sending it as a MIME message will increase the size of the SOAP call and if doesn't provide a saving, it will send it as a normal SOAP message.
This
provides an example of what the message sent over the wire looks like.


q: Are there any other ways to avoid LazyInitializationExceptions in a Hibernate web application besides using the OpenSessionInView pattern? Are there any downsides to using OpenSessionInView?

[A]
When working on our web applications, we usually decide beforehand which objects/fields will be needed in the view pages and make sure that all the objecs are properly initialized  from the model before dispatching to the view.
This can be accomplished in (at least) three ways:
fetching
properties using eager strategy (i.e. with
```
FetchMode.JOIN
```
, if you're using the
Criteria API
)
explicitly initializing properties (i.e. with
```
Hibernate.initialize(property)
```
)
implicitly initializing properties by calling the appropriate property accessor
About the downsides of OpenSessionInView, have you checked out
this
page?


q:
If you have something like:

val myStuff = Array(Person("joe",40), Person("mary", 35))

How do you create an XML value with that data as nodes? I know how to use { braces } in an XML expression to put a value, but this is a collection of values. Do I need to iterate explicitly or is there something better?

val myXml = <people>{ /* what here?! */ }</people>

The resulting value should be something like:

<people><person><name>joe</name><age>40</age></person>
<person><name>mary</name><age>39</age></person></people>

[A]
As it's a functional programming language Array.map is probably what you're looking for:
```
```
class Person(name : String, age : Int){
    def toXml() = <person><name>{ name }</name><age>{ age }</age></person>
}

object xml {
    val people = List(
        new Person("Alice", 16),
        new Person("Bob", 64)
    )

    val data = <people>{ people.map(p => p.toXml()) }</people>

    def main(args : Array[String]){
        println(data)
    }
}
```
```
Results in:
```
```
<people><person><name>Alice</name><age>16</age></person><person><name>Bob</name><age>64</age></person></people>
```
```
A formatted result (for a better read):
```
```
<people>
   <person>
      <name>Alice</name>
      <age>16</age>
   </person>
   <person>
      <name>Bob</name>
      <age>64</age>
   </person>
</people>
```
```


q:
I've got an unmanaged Linux VPS running ubuntu that I'm using for the web server for a personal website.  I'd like to get a barebones email server up and running.  All the installation guides I've found so far are for a full-fledged email server with a webmail interface and everything.  That's a lot more than I need.  There's only two things I need:

My web application needs to be able to send email.  Specifically, it'll be emailing me when an exception occurs.

I want all email sent to [anything]@domain.com forwarded to my personal gmail account.  The server doesn't even need to retain the email or anything.

I want to reserve resources for the actual web app, so I don't want to install anything I won't need for this.

[A]
Your web application needs a SMTP server.  That server can be a hosted service like Google's or
MailHop
.  If you really want to be an email administrator postfix should be installed
HOWTO is here
.
If not:
```
```
sudo apt-get install postfix
```
```


q: When using XmlDocument.Load , I am finding that if the document refers to a DTD, a connection is made to the provided URI. Is there any way to prevent this from happening?

[A]
Use an
```
XMLReader
```
to load the document and set the
```
ValidationType
```
property of the reader settings to
```
None
```
.


q:
I have an s-expression bound to a variable in Common Lisp:

(defvar x '(+ a 2))

Now I want to create a function that when called, evaluates the expression in the scope in which it was defined.  I've tried this:

(let ((a 4))
  (lambda () (eval x)))

and

(let ((a 4))
  (eval `(lambda () ,x)))

But both of these create a problem: EVAL will evaluate the code at the top level, so I can't capture variables contained in the expression.  Note that I cannot put the LET form in the EVAL.  Is there any solution?

EDIT: So if there is not solution to the EVAL problem, how else can it be done?

EDIT: There was a question about what exactly I am try to do.  I am writing a compiler.  I want to accept an s-expression with variables closed in the lexical environment where the expression is defined.  It may indeed be better to write it as a macro.

[A]
CLISP implements an extension to evaluate a form in the lexical environment. From the fact that it is an extension, I suspect you can't do that in a standard-compliant way.
```
```
(ext:eval-env x (ext:the-environment))
```
```
See
http://clisp.cons.org/impnotes.html#eval-environ
.


q:
If I add an after_save callback to an ActiveRecord model, and on that callback I use update_attribute to change the object, the callback is called again, and so a 'stack overflow' occurs (hehe, couldn't resist).

Is it possible to avoid this behavior, maybe disabling the callback during it's execution? Or is there another approach?

Thanks!

[A]
Check out how
update_attribute
is implemented.  Use the send method instead:
```
```
send(name.to_s + '=', value)
```
```


q:
For performance reasons, I draw the strings for my UITableViewCell in a custom view that overrides its drawRect method to draw strings directly in the view rectangle using NSString:drawInRect. This is similar to Apple's TableViewSuite Example 5-CustomTableViewCell.

However, when I invoke setEditing on the cell to bring up the delete button, the view ends up with a squeezed appearance after the animation completes. To demonstrate this, invoke setEditing:YES on the CustomTableViewCell example mentioned above and observe the distortion. Is there any way around this or should I just revert back to using UILabels for my text?

[A]
I had this problem too, and in my case I fixed it by handling the 2 states in my drawRect method, one while editting, the other while not. In other words I accounted for the size of the delete button, and got my UI to repaint the cell differently. I'm not sure if it's the most efficient way to go, but here is the code that I used to force a repaint:
```
```
-(void)_refreshTableAndCells{
    //refresh the table
    [myCustomTableView reloadData];
    //refresh all the visible cells
    for (UITableViewCell *cell in myCustomTableView.visibleCells){
        LocationCellView *locationCell = [cell.contentView.subviews objectAtIndex:0];
        [locationCell setNeedsDisplay];
    }

}
```
```
I'm an Objective-C n00b though, so I'd be more than happy for someone to suggest a better way than this.


q:
I'm wondering if there's any way to have Firefox 3 (or IE 7 or safari 3.1 or Opera) flag that a redirect has occurred (i.e. any deltas between the hyperlink or URL entered into address bar, and the page you land on), whether you've arrived from a hyperlink or entering URL into address bar.

I've googled some, looked at the linker addon, but the rightclick is an additional step I don't want to have to do.

Edit: If anybody can point me at the mozilla docs that show how to track clicked links and pages landed on in different tabs, i'll take a crack at writing a bookmarklet.  TIA

[A]
I don't think this will help, since you don't want to do the right click for the linker add-on, but if I needed to do know if I was being redirected, I would use the
LiveHTTPHeaders
extension.  It supports regular expressions, so you can only get headers that include 'Location'.
The reason I don't think it is what you are looking for is that you have to open it before the link, it won't "flag" a redirect and pop a message up or anything.


q: I'm writing an application that processes PowerPoint presentations and I'm looking into ways of detecting whether or not a PowerPoint presentation has a password if it does then stop processing it.

[A]
It seems to me that there is
no way to check
if the presentation is password-protected. You have to open the document first to make properties accessible. You have to provide the password when you are opening the document.
There is a
Password Property
you can check.
I've found a
workaround on Expert Exchange
:
The problem is the following:
Visual
  Basic is a single threaded
  application
, this means that you cant
  put a certain procedure on hold and
  proceed with another (in the same
  application). When powerpoint has an
  "on open"-password set, the
  CreateObject procedure inside your
  application is put on hold untill
  powerpoint releases it, this is when
  the user types in a password. There is
  no way around this that I know off,
  but you can make a workaround:
Make 2 applications
, 1 application is
  the application you already have, the
  second one is a "powerpoint unlocker".
  You run the second program just before
  you open the protected powerpoint
  presentation in application 1. You can
  do that with the shell command. The
  "powerpoint unlocker" can be as
  advanced as you want it to be, you can
  for example provide command line
  parameters to specify which
  presentation must be unlocked with
  what password. Then you use the
findwindow api to get the window
  handle of the locked presentation
.
  Once you have that, you
use the
  sendmessage api
to input the password.
  After this the "powerpoint unlocker"
  unloads and the first application can
  resume with its excution.
I hope this helps!
Osmodean


q:
Does anyone know of any notepad++ plugin that saves a version of whatever I'm working on periodically? Ideally, it would save many versions with the automatic version number and the date in the title, and perhaps store them in a zipped archive to save space.

Does something like this exist already, or shold I attempt to write such a plugin myself?

Thanks,

Cameron

P.S. It should be freeware or (preferably) open-source.

[A]
You might be better off looking into something closer to "real" version control -
Mercurial
, perhaps. It doesn't require a server, and it's really easy to set up.
To automate it, you could turn on autosave in Notepad++, and set up a windows scheduled task to do an
```
hg commit
```
every few minutes.


q:
I am implementing a BFS, and what it is going to do is go through an ordered tree to find the shortest solution to a puzzle.

What i will be doing is creating a Snapshot object that holds the current position of each piece in a puzzle. I will add this Snapshot object into the queue and check if it is the solution. However, I am creating these snapshots on the fly. So is there some kind of way that will automatically generate the names of the Snapshot objects when they are put into the queue?

or do i have to keep track of how many declarations i have made and just hard code it by saying...

Snapshot snapshot2;
Snapshot snapshot3;
Snapshot snapshot4;
etc..

[A]
You could use a queue from the standard template library, then create a function that creates a Snapshot object and puts in into the queue.  Give this function a static variable which gets incremented every time it is called and written into an id field of the snapshot.
http://www.csci.csusb.edu/dick/samples/stl.html
http://www.cppreference.com/wiki/stl/queue/start


q:
I've read the documentation on WideCharToMultiByte, but I'm stuck on this parameter:

lpMultiByteStr
[out] Pointer to a buffer that receives the converted string.

I'm not quite sure how to properly initialize the variable and feed it into the function

[A]
You use the lpMultiByteStr [out] parameter by creating a new char array.  You then pass this char array in to get it filled.  You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.
Here are a couple of useful helper functions for you, they show the usage of all parameters.
```
```
#include <string>

std::string wstrtostr(const std::wstring &wstr)
{
    // Convert a Unicode string to an ASCII string
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

std::wstring strtowstr(const std::string &str)
{
    // Convert an ASCII string to a Unicode String
    std::wstring wstrTo;
    wchar_t *wszTo = new wchar_t[str.length() + 1];
    wszTo[str.size()] = L'\0';
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
    wstrTo = wszTo;
    delete[] wszTo;
    return wstrTo;
}
```
```
--
Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it.  The function will use that pointer to fill your variable.
So you can understand this better:
```
```
//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
  *pX = 10;
}

int main(int argc, char ** argv)
{
  int X;
  fillXWith10(&X);
  return 0;
}
```
```


q: It seems OpenLaszlo can run on AIR. What's less obvious is whether OpenLaszlo apps can use the AIR-specific APIs, like file system access. If so, how exactly is this done?

[A]
While I don't have any specifics, the article you linked mentions that his application window can be dragged and closed. Those are AIR-only APIs (see the NativeWindow class), so presumably what you're asking about must be possible to some extent.
However, my understanding is that OpenLaszlo tries not to implement things that can be done in Flash but not (say) DHTML, so it may be less obvious how to do things like local file access. Probably you'll want to download the source linked in the article and see how he implemented the window drag/close.


q:
My PHP/MS Sql Server 2005/win 2003  Application occasionally becomes very unresponsive, the memory/cpu usage does not spike. If i try to open any new connection from sql management studio, then the it just hangs at the open connection dialog box.
how to deterime the total number of active connections ms sql server 2005

[A]
This shows the number of connections per each DB:
```
```
SELECT
    DB_NAME(dbid) as DBName,
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE
    dbid > 0
GROUP BY
    dbid, loginame
```
```
And this gives the total:
```
```
SELECT
    COUNT(dbid) as TotalConnections
FROM
    sys.sysprocesses
WHERE
    dbid > 0
```
```
If you need more detail, run:
```
```
sp_who2 'Active'
```
```
Note:
The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)


q:
How hard would it be to use GCC instead of VC++ from within Visual Studio 2008? Obviously, some of the keywords won't match, and some may not get syntax highlighting (unless you made a new language service).

Is this what a 'makefile project' is for, pretty much?

[A]
There is no GCC plugin for Visual Studio as the one for example for Intel C++, which allows Intel's compiler to be used as a drop-in replacement for Visual C++.
You can use Makefile projects which allows you to use any external tool you like (make, SCons, jam, whatever) to do your build. If you don't like Makefiles, you may want to look at
CMake
which allows you to generate Makefiles or Visual Studio projects from a much simpler description. This also means that you're not bound to Makefiles or Visual Studio projects, but can switch between them as you like.


q:
Is there a better way to do the following:

$array = array('test1', 'test2', 'test3', 'test4', 'test5');
// do a bunch of other stuff, probably a loop
$array[] = 'test6';
end($array);
echo key($array); // gives me 6

This will give the key of the most recently add array element.

Is there a better way to do this?

[A]
You could also do:
```
```
$end = end(array_keys($array));
```
```
But I think your way makes it clear what you want to do, so you could whip something up like:
```
```
function array_last_key($array) {
    end($array);
    return key($array);
}
```
```
That's about it.


q:
Sometimes you're developing and you decide to commit, forgetting you created a few files on your project. Then a few days down the line your buddy gets your build out of Subversion and complains that some files appear to be missing. You realize, ah crap, I forgot to add those files!

How can I get a list of the files that are not under version control from Subversion so I'm sure I've added everything to the repository?

[A]
Use the
```
svn status
```
command:
```
```
svn status | grep ^?
```
```
Files that are not versioned are indicated with a ? at the start of the line.
If you find that you always have some specific files that should not be added to the repository (for example, generated binaries), you should set up the
```
svn:ignore
```
property on the containing directory so these files won't keep showing up when using
```
svn status
```
.


q:
I haven't found an answer to this particular question; perhaps there isn't one. But I've been wondering for a while about it.

What exactly causes a binary file to display as "gibberish" when you look at it in a text editor? It's the same thing with encrypted files. Are the binary values of the file trying to be converted into ASCII? Is it possible to convert the view to display raw binary values, i.e. to show the 1s and 0s that make up the file?

Finally, is there a way to determine what program will properly open a data file? Many times, especially with Windows, a file is orphaned or otherwise not associated w/ a particular program. Opening it in a text editor sometimes tells you where it belongs but most of the time doesn't, due to the gibberish. If the extension doesn't provide any information, how can you determine what program it belongs to?

[A]
The display looks interesting, because a binary file can contain non-printable characters. It is up to the displaying program to replace such characters with something else.
This can be prevented by using a hex editor. Such a program displays each byte from the file as its hexadecimal value. That makes for a nice tabular view of the file, but it is not easy for the average person to decipher this view, because we are not used to look at data that way.
There are a few ways to find out what program a file might belong to. You can look at the beginning of the file and with some knowledge, you might recognize the file type. There are some types that begin with the same characters (RAR, GIF etc.). For other types it might not be as easy.
In Linux you can use the "file" command to help you determine file type. There are probably programs for Windows that will do the same.


q:
I am parsing an input text file.  If I grab the input one line at a time using getline(), is there a way that I can search through the string to get an integer?  I was thinking something similar to getNextInt() in Java.

I know there has to be 2 numbers in that input line; however, these values will be separated by one or more white space characters, so I can't just go to a specific position.

[A]
If the only thing in there is whitespace and integers, just try something like this:
```
```
int i1, i2;
stringstream ss(lineFromGetLine);
ss >> i1 >> i2;
```
```
or easier:
```
```
int i1, i2;
theFileStream >> i1 >> i2;
```
```


q:
Is it possible to scale a UIView down to 0 (width and height is 0) using CGAffineTransformMakeScale?

view.transform = CGAffineTransformMakeScale(0.0f, 0.0f);

Why would this throw an error of "<Error>: CGAffineTransformInvert: singular matrix." ?

Update:
There is another way of scaling down a UIView to 0

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
view.frame = CGRectMake(view.center.x, view.center.y, 0, 0);

[UIView commitAnimations];

[A]
I'm not sure it's possible to do this; you'll start running into divide-by-zero issues. If you try to do this, you'll be creating a transform that looks like:
```
```
0  0  0
   0  0  0
   0  0  1
```
```
Which, when applied to ANY other transform, will produce the above transform.
Why not just hide the view (if you want to scale it out of sight) or set the scaling factor to something like 0.001 (if you want to scale it in)?


q: Looking for code samples to access a memory map file in C#

[A]
You can take a look at
this CodeProject article
which shows a simple array over MMF implementation using
Winterdom's FileMap library
- basically a wrapper around the Win32 APIs for memory mapped files.
Caveat emptor: 1) I have not used FileMap, so I can't vouch for it; 2) FileMap is under LGPL, if the licensing terms are of any concer of you.
You can also search on
http://pinvoke.net
for the P/Invoke definitions of the corresponding Win32 APIs and roll your own implementation.


q: Does anyone know of any good tools to view the store name, store location, or values of an X.509 Certificate?

[A]
i'm supposing that you are using Windows. So here it is
http://msdn.microsoft.com/en-us/library/aa529278.aspx
. It's a good tool, but to do it thru API is not hard and it's a good exercise to learn the API.
Regards,
Victor


q:
Are any of you aware of a library that helps you build/manipulate SQL queries, that supports JOIN's?

It would give a lot of flexibility i'd think if you have something where you could return an object, that has some query set, and still be able to apply JOIN's to it, subqueries and such.

I've search around, and have only found SQL Builder, which seems very basic, and doesn't support joins. Which would be a major feature that would really make it useful.

[A]
Maybe you can try an
ORM
, like
Propel
or
Doctrine
, they have a nice programmatic query language, and they return you arrays of objects that represent rows in your database...
For example with Doctrine you can do joins like this:
```
```
$q = Doctrine_Query::create();
$q->from('User u')
->leftJoin('u.Group g')
->innerJoin('u.Phonenumber p WITH u.id > 3')
->leftJoin('u.Email e');

$users = $q->execute();
```
```
And with Propel:
```
```
$c = new Criteria(AuthorPeer::DATABASE_NAME);

$c->addJoin(AuthorPeer::ID, BookPeer::AUTHOR_ID, Criteria::INNER_JOIN);
$c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::INNER_JOIN);
$c->add(PublisherPeer::NAME, 'Some Name');

$authors = AuthorPeer::doSelect($c);
```
```
and you can do a lot more with both...


q:
Does anybody know any resources on this subject?

I'm developing an embedded application for 2x16 LCD display. Ideally I would like to have a general (display independent) framework, that could be used virtually on any display - one or more segment(s) LED, 1x16, 2x16 LCD, etc.
Also would like to learn about general guidelines for such small user interfaces.

EDIT: I'm interested in high-level functionality, how to organize the user interface - the menus, options and the user input. We don't dicuss the LCD controller issues here.

[A]
If you're referring to a 2 line by 16 character display, they'll generally be pixel based and will have an integrated controller as they're much more complicated to control.  The 2x16 and 4x16 LCD devices I've used in the past actually have a nibble-wide interface, and the commands are sent to the device in
```
<command>[<address>][<data>]
```
style, with the number of nibbles required for a valid command being dictated by the command itself.  If would be helpful if you link to the target device as there really doesn't seem to be a standard from manufacturer to manufacturer.
With respect to segmented LEDs and LCDs, there is a standard layout for so-called seven segment devices that started back with the pixie tubes.  Here's a diagram that shows this segmentation:
```
```
a
  ---
f| g |b
  ---
e|   |c
  ---
   d
```
```
Another question is whether you want to drive the display directly or will use a controller IC.  It's pretty easy to drive a seven-segment LED as they generally have a common cathode or anode and you simply need to be able to sink or source enough current.  Driving an LCD directly is a little more complicated as the polarity applied to a pixel or segment has to constantly flipped to avoid damage to the device.  It's much easier to find a controller with an integrated clock that performs this function.


q:
I am writing a small program.  The interface I am writing to control each repository that is made defines a method of Save(IPublicObject).  I am using LINQ for the SQL Version of the repository CRUD.  My question is this.  I would like to have only the one method which accepts the interface type.  I want to think how I can best locate the Save action for the inherited type I then pass in.

In the book I am reading Patterns of Enterprise Application Architecture.  I am leaning on the Inheritance Maping.  So I create a derived object of

public class ConcretePublicObjectOne : IPublicObject{}

I want to then pass this into the Save Function of the respository.  It is at this point where I am trying to think how best to say, ok we need to use "WHAT?" Save Method etc...

Should I use a registry, configuration setting mapping the types?

[A]
What you wish to do is to have a:
```
```
Repository.Save(publicObject)
```
```
and the repository to call a method from publicObject?
If this is the requirement then you can define the Save method in repository as:
```
```
public class Repository {
    public void Save(IPublicObject publicObject) {
        publicObject.Save();
    }
}
```
```
where IPublicObject is defined as:
```
```
public interface IPublicObject {
    void Save();
}
```
```
But with this approach you will have to define a save method for each entity (like ConcretePublicObjectOne in your example)


q:
Is there a max length for an array in C++?

Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of?

Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way?

What I have to do is storing long long int on an array, I'm working in a Linux environment. My question is: what do I have to do if I need to store an array of N long long integers with N > 10 digits?

I need this because I'm writing some cryptographic algorithm (as for example the p-Pollard) for school, and hit this wall of integers and length of arrays representation.

[A]
There are two limits, both not enforced by C++ but rather by the hardware.
The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's
```
std::size_t
```
can take. This data type is large enough to contain the size in bytes of any object
The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a
```
vector<int>
```
of a given size
n
typically takes multiple times as much memory as an array of type
```
vector<char>
```
(minus a small constant value), since
```
int
```
is usually bigger than
```
char
```
. Therefore, a
```
vector<char>
```
may contain more items than a
```
vector<int>
```
before memory is full. The same counts for raw C-style arrays like
```
int[]
```
and
```
char[]
```
.
Additionally, this upper limit may be influenced by the type of
```
allocator
```
used to construct the
```
vector
```
because an
```
allocator
```
is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.
Apart from that, C++ doesn't enforce any limits.


q:
I'm creating a site where the user unfortunately has to provide a regex to be used in a MySQL WHERE clause. And of course I have to validate the user input to prevent SQL injection. The site is made in PHP, and I use the following regex to check my regex:

/^([^\\\\\']|\\\.)*$/

This is double-escaped because of PHP's way of handling regexes.
The way it's supposed to work is to only match safe regexps, without unescaped single quotes. But being mostly self-taught, I'd like to know if this is a safe way of doing it.

[A]
If it is anly for the purposes of display this reg expression then most programs simply Html Encode the value and store in the DB and then the Decode on the way out.  Again only for Display purposes though, if you need to use the reg exp that is submitted this won't work.
Also know there is a method where the person intent on injecting writes out there SQL, Converts it to varbinary and submits the exec command with the base 64 representation of the query which I have been hit with in the past.


q:
I want to apply a function to all columns in a matrix with MATLAB. For example, I'd like to be able to call smooth on every column of a matrix, instead of having smooth treat the matrix as a vector (which is the default behaviour if you call smooth(matrix)).

I'm sure there must be a more idiomatic way to do this, but I can't find it, so I've defined a map_column function:

function result = map_column(m, func)
    result = m;
    for col = 1:size(m,2)
        result(:,col) = func(m(:,col));
    end
end

which I can call with:

smoothed = map_column(input, @(c) (smooth(c, 9)));

Is there anything wrong with this code? How could I improve it?

[A]
If this is a common use-case for your function, it would perhaps be a good idea to make the function iterate through the columns automatically if the input is not a vector.
This doesn't exactly solve your problem but it would simplify the functions' usage. In that case, the output should be a matrix, too.
You can also transform the matrix to one long column by using
```
m(:,:) = m(:)
```
. However, it depends on your function if this would make sense.


q:
I have a very strange problem, when I try to var_dump (or print_r) a Doctrine Object, my Apache responses with an empty blank page (200 OK header). I can var_dump a normal php var like:

$dummy = array("a" => 1, "b" =>2);

And it works fine. But I can't with any object from any Doctrine class, (like a result from $connection->query(), or an instance of a class from my object model with Doctrine).

Anybody knows why this happens?

[A]
I've had that sometimes when trying to
```
print_r()
```
a self-referencing object - it gets into a loop and runs out of memory.  Possibly that's what's happening to you.
Try increasing the memory limit (
```
ini_set('memory_limit', '256M');
```
) and see if that fixes it.
Edit:   I don't think there's an actual fix for this - it's PHP's internal
```
var_dump
```
/
```
print_r
```
that don't limit depth on recursion (or don't do it properly, at least).  If you install the
XDebug
extension, this can replace the built-in
```
var_dump
```
with a version that handles recursion much better.


q:
As I understand it, when asked to reserve a larger block of memory, the realloc() function will do one of three different things:

if free contiguous block exists
    grow current block
else if sufficient memory
    allocate new memory
    copy old memory to new
    free old memory
else
    return null

Growing the current block is a very cheap operation, so this is behaviour I'd like to take advantage of.  However, if I'm reallocating memory because I want to (for example) insert a char at the start of an existing string, I don't want realloc() to copy the memory.  I'll end up copying the entire string with realloc(), then copying it again manually to free up the first array element.

Is it possible to determine what realloc() will do?  If so, is it possible to achieve in a cross-platform way?

[A]
No
- and if you think about it, it can't work. Between you checking what it's going to do and actually doing it, another process could allocate memory.
In a multi-threaded application this can't work. Between you checking what it's going to do and actually doing it, another thread could allocate memory.
If you're worried about this sort of thing, it might be time to look at the data structures you're using to see if you can fix the problem there. Depending on how these strings are constructed, you can do so quite efficiently with a well designed buffer.


q:
Highly embedded (limited code and ram size) projects pose unique challenges for code organization.

I have seen quite a few projects with no organization at all. (Mostly by hardware engineers who, in my experience are not typically concerned with non-functional aspects of code.)

However, I have been trying to organize my code accordingly:

hardware specific (drivers, initialization)

application specific (not likely to be reused)

reusable, hardware independent

For each module I try to keep the purpose to one of these three types.

Due to limited size of embedded projects and the emphasis on performance, it is often keep this organization.

For some context, my current project is a limited DSP application on a MSP430 with 8k flash and 256 bytes ram.

[A]
I've worked with some sensors like the Tmote Sky, I too have seen poor organization, and I have to admit i have contributed to it. Anyway I'd say that some confusion has to be, because loading too much modules or too much part of program will be (imho) resource killing too, so try to be aware of a threshold between organization and usability on the low resources.
Obviously this don't mean let caos begin, but for example try to get a look on the organization of the
tinyOS
source code and applications, it's an idea on what I'm trying to say.


q:
Is there a key shortcut for this in XCode?

Can I implement an Applescript for this and run it within XCode?

[A]
You can probably do that using a script (check out the relevent piece of Xcode documentation). Also see the "Insert Text Macro" menu item…
But you might find it to be more efficient to just use the auto-correct feature. I just type "[[F", then hit my auto-correct key (bound to F5 I believe, but I've changed it), type enough of the class name for it to be selected in the autocorrect popup. Hit space, start typing alloc but let auto correct kick in. Close the brace. Start typing init, use autocorrect again.
You generally shouldn't need to create macros/scripts for something this trivial. The autocorrect, placeholders and autofill features should be all you really need.


q: I have a groovy script with an unknown number of variables in context at runtime, how do I find them all and print the name and value of each?

[A]
Well, if you're using a simple script (where you don't use the "def" keyword), the variables you define will be stored in the binding and you can get at them like this:
```
```
foo = "abc"
bar = "def"

if (true) {
    baz = "ghi"
    this.binding.variables.each {k,v -> println "$k = $v"}
}
```
```
Prints:
```
```
foo = abc
    baz = ghi
    args = {}
    bar = def
```
```
I'm not aware of an easy way to enumerate through the variables defined with the "def" keyword, but I'll be watching this question with interest to see if someone else knows how.


q:
What is the best way to format a decimal if I only want decimal displayed if it is not an integer.

Eg:

decimal amount = 1000M
decimal vat = 12.50M

When formatted I want:

Amount: 1000 (not 1000.0000)
Vat: 12.5 (not 12.50)

[A]
```
```
decimal one = 1000M;
    decimal two = 12.5M;

    Console.WriteLine(one.ToString("0.##"));
    Console.WriteLine(two.ToString("0.##"));
```
```


q:
I am displaying a scrolled data table in a web page.  This table has several thousands of dynamic rows, so it is loaded from the server (via AJAX).

The user can scroll up and down, so what I need is to detect when the user reaches the end of the scrollbar (that is, the last row at the bottom of the table) in order to request and show more data.

You can find this effect in google reader, when you scroll down to the last post in a given feed, google requests and shows new posts in a transparent way, but I can't figure out how they achieve it.

By the way, right now I am using a YUI Datatable

[A]
I'm not familiar with the specific element you are using, but in order
 to implement this on a full size window, you can do the following:
```
```
$wnd.onscroll = function() {
    if (($wnd.height - $wnd.scrollTop) < SOME_MARGIN) then doSomething();
};
```
```
Where scrollTop is essentially "how many pixels have been scrolled".
I assume applying this to the table you are working with will do the job.


q: How would I go about adding enctype="multipart/form-data" to a form that is generated by using <% Html.BeginForm(); %>?

[A]
As part of htmlAttributes,e.g.
```
```
Html.BeginForm(
    action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
```
```
Or you can pass
```
null
```
for action and controller to get the same default target as for BeginForm() without any parameters:
```
```
Html.BeginForm(
    null, null, FormMethod.Post, new { enctype="multipart/form-data"})
```
```


q:
I'm having to start building the architecture for a database project but i really don't know the differences between the engines.

Anyone can explain whats the pros and bads of each of these three engines? We'll have to choose one of them and the only thing I actually know about them is this:

Mysql & Postgres:

Are free but not so good as oracle

Mysql as security problems (is this true?)

Oracle:

Best data base engine in the world

Expensive

Can someone clear out other differences between them? This is a medium/large (we're thinking of around some 100 to 200 tables) project with low budget, what would you choose? And with a higher budget?

[A]
See the comparison tables on wikipedia:
http://en.wikipedia.org/wiki/Comparison_of_object-relational_database_management_systems
&&
http://en.wikipedia.org/wiki/Comparison_of_relational_database_management_systems
Oracle may or may not be the best. It's expensive, but that doesn't mean best.
Have you looked at DB2? Sybase? Teradata? MS SQL?


q:
Does anyone know of a good dictionary API or ruby library to lookup the definitions of words?

I'm thinking it should work something like:

I call get_definition(word)

It returns the definition for that word (ideally in some way to easily format the definition for display.

Thanks

[A]
I discovered a webservice for this yesterday.
Go to the
British Council
homepage and double click on any word (that isn't already a hyperlink).
This should open a popup window with a Cambridge Dictionary definition in it. The API is relatively simple (and
it is
a public API, I checked it yesterday):
```
```
http://dictionary.cambridge.org/learnenglish/results.asp?searchword=SEARCH_PHRASE&dict=L
```
```
For reference, here's the code they use to launch this on double-click:
```
```
/* BC double-click pop-up dictionary */
var NS = (navigator.appName == "Netscape" || navigator.product == 'Gecko') ? 1 : 0;
if (NS) document.captureEvents(Event.DBLCLICK);
document.ondblclick = dict;
var dictvar;

function dict() {
    if (NS) {
        t = document.getSelection();
        pass_to_dictionary(t);
    } else {
        t = document.selection.createRange();
        if(document.selection.type == 'Text' && t.text != '') {
            document.selection.empty();
            pass_to_dictionary(t.text);
        }
    }
}

function pass_to_dictionary(text) {
    //alert(text);
    if (text > '') {
        window.open('http://dictionary.cambridge.org/learnenglish/results.asp?searchword='+text+ '&dict=L', 'dict_win', 'width=650,height=400,resizable=yes,scrollbars=yes');
    }
}
```
```


q:
How can I construct the following string in an Excel formula:

Maurice "The Rocket" Richard

If I'm using single quotes, it's trivial: ="Maurice 'The Rocket' Richard" but what about double quotes?

[A]
Have you tried escaping with an additional double-quote? By escaping a character, you are telling Excel to treat the " character as literal text.
```
```
= "Maurice ""The Rocket"" Richard"
```
```


q: Is there an Open Source Free Graph Control for Windows Forms .NET 2.0?

[A]
I have been using
ZedGraph
for a while. You can generate various types of graphs that look very professional.


q:
I have a table called logs which has a datetime field.
I want to select the date and count of rows based on a particular date format.

How do I do this using SQLAlchemy?

[A]
I don't know SQLAlchemy, so I could be off-target.  However, I think that all you need is:
```
```
SELECT date_formatter(datetime_field, "format-specification") AS dt_field, COUNT(*)
    FROM logs
    GROUP BY date_formatter(datetime_field, "format-specification")
    ORDER BY 1;
```
```
OK, maybe you don't need the ORDER BY, and maybe it would be better to re-specify the date expression.  There are likely to be alternatives, such as:
```
```
SELECT dt_field, COUNT(*)
    FROM (SELECT date_formatter(datetime_field, "format-specification") AS dt_field
              FROM logs) AS necessary
    GROUP BY dt_field
    ORDER BY dt_field;
```
```
And so on and so forth.  Basically, you format the datetime field and then proceed to do the grouping etc on the formatted value.


q: What is the best way to manage the JavaScript files and the functions/objects context in an ASP.NET MVC app?

[A]
I put all my js files in the Content/Js folder. Then add URL helpers that allow me to change this in the future. My code isn't online, but I stole the idea from
Rob Conery MVC Commerce demo
.
Not sure what you mean by "manage...the functions/objects context in ASp.NET MVC app"
I think you're asking how to segment/partition your scripts.
You should separate your JS files into separate chunks of functionality.


q: How do I get a status report of all files currently being uploaded via HTTP form based file upload on an Apache Server?

[A] I don't believe you can do this with Apache itself. The upload looks like nothing more than a POST as far as Apache cares. There are modules and other servers that do special processing to uploads so you may have some luck there. It would probably be easier to keep track of it in your application.


q:
When I run the following, PowerShell hangs waiting for the dialog to close, even though the dialog is never displayed:

[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )
$d = New-Object Windows.Forms.OpenFileDialog
$d.ShowDialog( )

Calling ShowDialog on a Windows.Forms.Form works fine. I also tried creating a Form and passing it as the parent to $d.ShowDialog, but the result was no different.

[A]
I was able to duplicate your problem and found a workaround.  I don't know why this happens, but it has happened to others.
If you set the ShowHelp property to $true, you will get the dialog to come up properly.
Example:
```
```
[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )
$d = New-Object Windows.Forms.OpenFileDialog
$d.ShowHelp = $true
$d.ShowDialog( )
```
```
Good Luck!


q:
I use MS SQL Server 2005 application roles in an application. I execute the sp_setapprole to start the SPs role and to finish  sp_unsetapprole.

"connection pooling doesn't work" with application pooling, and there is no way to react on connection "disconnect event" (execute sp_unsetapprole just before disconnection).

I decide to call sp_setapprole at the start of all my SPs and call sp_unsetapprole at the end of all SPs.

Have you used SQL application roles? What are your XPs? What about performance hits?

[A]
I have not used app roles before, but from what I know about the perf hit is that after setting the application role there is no way to revert to the prev. security context. Thus the connection cannot be reused in pooling. This alone is a huge perf. hit that forces you to think twice about using app roles.
However, the docs say that starting from SQL Server 2005 there is a way to remember the original security context in a kind of cookie returned from sp_setapprole and after that use sp_unsetapprole to revert back to it. So the pooling should work again. If I were you, I would compare the perf. with a couple of simple statements/sprocs.
Any reason you don't use the standard ASP.NET membership API on the application level instead of app roles?


q:
File formats I would like to play include .wav, .mp3, .midi.

I have tried using the Wireless Toolkit classes with no success. I have also tried using the AudioClip class that is part of the Samsung SDK; again with

[A]
Without source code to review, I would suggest using the wireles toolkit (from
http://java.sun.com)first
.
It contains the standard J2ME emulator for windows and example code that will allow you to play a wav file.
assuming that works OK for you, try the same code on your Samsung device (of course, the location of the wav file will probably change so you have a tiny modification to make in the example code).
Assuming that works, compare your code that doesn't with the example code.


q:
I know that this is a simple question for PHP guys but I don't know the language and just need to do a simple "get" from another web page when my page is hit. i.e. signal the other page that this page has been hit.

EDIT: curl is not available to me.

[A]
If curl wrappers are on (they are per default), you can use:
```
```
file_get_contents('http://www.example.org');
```
```
Note that this happens synchronous, so before the request has completed, your page won't either. It would be better to log access to a logfile (or database) and export the data occasionally. Alternatively, you could do the request after your page has completed, and output has been sent to the client.


q:
I'm looking for a straightforward example / tutorial for implementing a JAX-WS (soap1.1 and soap1.2) web service based on wsdl definition using spring, axis2 and tomcat.

hint anyone ?

-- Yonatan

[A]
There is no such thing as "straightforward" in the world of SOAP. Any example and tutorial is bound to be complex due to the overengineered nature of this beast.
If you can choose your technologies, I'd recommend putting axis aside, and using Tomcat 6 + Java 6 + Metro.
Metro
is Sun's latest, greatest Java web services  (jax-ws) stack. Coupled with JavaEE annotations, it's a
relatively
painless way to get a web service off the ground quickly.
Sorry to not answer the question directly.


q: What's the best way to get the last inserted id using sqlite from Java? Google is giving me different answers--some say select the last-insert-rowid; others say call statement.getGeneratedKeys(). What's the best route to take? (I just want to return the id, not use it for other inserts or anything.)

[A]
Use
```
getGeneratedKeys()
```
if your JDBC driver supports it.  You don't want to muck around trying to get the key yourself after the insert.  If your driver does not support
```
getGeneratedKeys()
```
then I would get the next value from the key before the insert.


q:
Yes that sounds backwards. I want to create an area or frame in my Silverlight app to host another page from my site. I've seen it done before but I can't seem to find any examples.

This way I can control the entire page layout using SL but still use existing aspx pages.

thanks

[A]
Yes, it can be done and its quite easy to do. I plan on blogging about my HtmlBrowser control and posting the source. The basics are to make sure the Silverlight control is hosted with the isWindowless parameter enabled and then you can at runtime through the HtmlPage class create an IFRAME element and set the src attribute to the HTML page location. The fun part is getting the sizing right, but its not too difficult.
Follow my blog
http://craign.net/
over the next couple of days as I'll post my control.


q: I keep wondering how does a debugger work? Particulary the one that can be 'attached' to already running executable. I understand that compiler translates code to machine language, but then how does debugger 'know' what it is being attached to?

[A]
The details of how a debugger works will depend on what you are debugging, and what the OS is. For native debugging on Windows you can find some details on MSDN:
Win32 Debugging API
.
The user tells the debugger which process to attach to, either by name or by process ID. If it is a name then the debugger will look up the process ID, and initiate the debug session via a system call; under Windows this would be
DebugActiveProcess
.
Once attached, the debugger will enter an event loop much like for any UI, but instead of events coming from the windowing system, the OS will generate events based on what happens in the process being debugged – for example an exception occurring. See
WaitForDebugEvent
.
The debugger is able to read and write the target process' virtual memory, and even adjust its register values through APIs provided by the OS. See the list of
debugging functions
for Windows.
The debugger is able to use information from symbol files to translate from addresses to variable names and locations in the source code. The symbol file information is a separate set of APIs and isn't a core part of the OS as such. On Windows this is through the
Debug Interface Access SDK
.
If you are debugging a managed environment (.NET, Java, etc.) the process will typically look similar, but the details are different, as the virtual machine environment provides the debug API rather than the underlying OS.


q:
There are some cool and exciting features in .NET 3.5/C# 3.0, and with those features comes some darn interesting ways to write the exact same line of code.

Using the above stated tool set (and by extension .NET 2.0 stuff), what are the different ways the below code snippet could reasonably be rewritten?

        string uploadDirectory = "c:\\some\\path\\";
        if (Directory.Exists(uploadDirectory)) {
            string[] files = Directory.GetFiles(uploadDirectory);
            foreach (string filename in files) {
                if (File.GetLastWriteTime(filename).AddHours(12) < DateTime.Now) {
                    File.Delete(filename);
                }
            }
        }

[A]
Lambda:
```
```
if (Directory.Exists(uploadDirectory))
  Directory.GetFiles(uploadDirectory)
    .Where(f => File.GetLastWriteTime(file) < DateTime.Now.AddHours(-12))
    .Each(f => File.Delete(f));
```
```
Edit: On 2nd thought, you can avoid the security lookups on each File access by using DirectoryInfo and FileInfo instead of the static File methods:
```
```
var di = new DirectoryInfo(uploadDirectory);
if (di.Exists()) {
   di.GetFiles()
     .Where(f => f.LastWriteTime < DateTime.Now.AddHours(-12))
     .Each(f=> f.Delete());
}
```
```
And for those missing their own Each method:
```
```
void Each<T>(this IEnumerable e, Action<T> action) {
  foreach (T t in e) {
    action(t);
  }
}
```
```
To make this really crazy, and fit the C# 3.0 theme, let's throw in an anonymous type:
```
```
di.GetFiles().Select(f => new() {
   Delete = f.LastWriteTime < DateTime.Now.AddHours(-12) ? f.Delete : () => { }
}).Delete();
```
```
But that just doesn't make any sense. ;)


q:
I'm currently using the following code to right-trim all the std::strings in my programs:

std::string s;
s.erase(s.find_last_not_of(" \n\r\t")+1);

It works fine, but I wonder if there are some end-cases where it might fail?

Of course, answers with elegant alternatives and also left-trim solution are welcome.

[A]
In the case of an empty string, your code assumes that adding 1 to
```
string::npos
```
gives 0.
```
string::npos
```
is of type
```
string::size_type
```
, which is unsigned. Thus, you are relying on the overflow behaviour of addition.


q:
I have a ASP.NET GridView with a column mapped to a boolean. I want do display "Yes"/"No" instead of "True"/"False". Well actually I want "Ja"/"Nej" (in Danish).

Is this possible?

<asp:gridview id="GridView1" runat="server" autogeneratecolumns="false">
    <columns>
        ...
        <asp:boundfield headertext="Active" datafield="Active" dataformatstring="{0:Yes/No}" />
        ...
    </columns>
</asp:gridview>

[A]
Nope - but you could use a template column:
```
```
<script runat="server">
  TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
     object o = DataBinder.Eval(Container.DataItem, field);
     if (converter == null) {
        return (TResult)o;
     }
     return converter((T)o);
  }
</script>

<asp:TemplateField>
  <ItemTemplate>
     <%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
  </ItemTemplate>
</asp:TemplateField>
```
```


q:
I'm wondering about the practical use of #undef in C. I'm working through K&R, and am up to the preprocessor. Most of this was material I (more or less) understood, but something on page 90 (second edition) stuck out at me:

Names may be undefined with #undef,
  usually to ensure that a routine is
  really a function, not a macro:

#undef getchar

int getchar(void) { ... }

Is this a common practice to defend against someone #define-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting getchar(), so it shouldn't come up.) With your own function names, do you feel the need to do this? Does that change if you're developing a library for others to use?

[A]
I only use it when a macro in an
```
#included
```
file is interfering with one of my functions (e.g., it has the same name). Then I
```
#undef
```
the macro so I can use my own function.


q:
I'm using the following regex to capture a fixed width "description" field that is always 50 characters long:

(?.{50})

My problem is that the descriptions sometimes contain a lot of whitespace, e.g.

"FLUID        COMPRESSOR                          "

Can somebody provide a regex that:

Trims all whitespace off the end

Collapses any whitespace in between words to a single space

[A]
Is there a particular reason you are asking for a regular expression? They may not be the best tool for this task.
A replacement like
```
```
s/[ \t]+/ /g
```
```
should compress the internal whitespace (actually, it will compress leading and trailing whitespace too, but it doesn't sound like that is a problem.), and
```
```
s/[ \t]+$/$/
```
```
will take care of the trailing whitespace. [I'm using
```
sed
```
ish syntax here. You didn't say what flavor you prefer.]
Right off hand I don't see a way to do it in a single expression.


q:
One of our providers are sometimes sending XML feeds that are tagged as UTF-8 encoded documents but includes characters that are not included in the UTF-8 charset. This causes the parser to throw an exception and stop building the DOM object when these characters are encountered:

DocumentBuilder.parse(ByteArrayInputStream bais)

throws the following exception:

org.xml.sax.SAXParseException: Invalid byte 2 of 2-byte UTF-8 sequence.

Is there a way to "capture" these problems early and avoid the exception (i.e. finding and removing those characters from the stream)? What I'm looking for is a "best effort" type of fallback for wrongly encoded documents. The correct solution would obviously be to attack the problem at the source and make sure that only correct documents are delivered, but what is a good approach when that is not possible?

[A]
You should manually take a look at the invalid documents and see what is the common problem to them. It's quite probable they are in fact in another encoding (most probably windows-1252), and the best solution then would be to take every document from the broken system and recode it to UTF-8 before parsing.
Another possible cause is mixed encodings (the content of some elements is in one encoding and the content of other elements is in another encoding). That would be harder to fix.
You would also need a way to know when the broken system gets fixed so you can stop using your workaround.


q:
What's the best way to pipe the output from an java.io.OutputStream to a String in Java?

Say I have the method:

  writeToStream(Object o, OutputStream out)

Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.

I'm considering writing a class like this (untested):

class StringOutputStream extends OutputStream {

  StringBuilder mBuf;

  public void write(int byte) throws IOException {
    mBuf.append((char) byte);
  }

  public String getString() {
    return mBuf.toString();
  }
}

But is there a better way? I only want to run a test!

[A]
I would use a
```
ByteArrayOutputStream
```
. And on finish you can call:
```
```
new String( baos.toByteArray(), codepage );
```
```
or better:
```
```
baos.toString( codepage );
```
```
For the
```
String
```
constructor, the
```
codepage
```
can be a
```
String
```
or an instance of
java.nio.charset.Charset
. A possible value is
java.nio.charset.StandardCharsets.UTF_8
.
The method
```
toString()
```
accepts only a
```
String
```
as a
```
codepage
```
parameter (stand Java 8).


q:
I've been looking around the System.Xml namespace, but don't see anything that would support this. Does anyone know if it's built into .Net, or would I have to obtain a third party library to do it?

NOTE: I wish it were as simple as generating  an xsd, but that won't do for my specific situation.

[A]
I'm not sure about DTD but you can generate XSD files from an xml file using the
Xsd.exe
tool. It usually lives in the following directory:
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\xsd.exe


q:
I have sets of values in rows in Excel
First row contains weights of how much each value in each column contributes to weighted total.
Now, I want to mark in each following row the value that contributed to the weighted total the most, by changing its background. I played with conditional formatting, but my Excel skills are modest, to say the least.
So, how do I do that?

[A]
Here's what I think you are trying to do: You have a list of numbers (they happen to be weights, but that's not important). You want the largest number to be highlighted differently.
Suppose the cells are in the range A1:A8.
Select the range A1:A8.
Select Conditional Formatting (Format | Conditional Formatting)
Enter the condition Cell Value is/Equal To/=MAX(A1:A8)
Click the Format... button and set the Pattern to affect the background.
(Tested on Excel 2003 on Windows.)


q: I'm new to .Net and do not understand the difference. Can someone point me in the right direction?

[A]
They are two different frameworks for writing services. WCF is generally more flexible and provides configurable options for what protocols are used, how the service is hosted and a variety of security options. ASMX offers SOAP based services. Generally WCF is also more
performant
. In general ASMX is easier to use and generally has less of a learning curve.
Here
is a MSDN forum discussion on the topic.
Here are the getting started pages for
ASMX
and
WCF
.