q:
Wordpress provides a function called "the_permalink()" that returns, you guessed it!, the permalink to a given post while in a loop of posts.

I am trying to URL encode that permalink and when I execute this code:

<?php
print(the_permalink());
$permalink = the_permalink();
print($permalink);
print(urlencode(the_permalink()));
print(urlencode($permalink));
$url = 'http://wpmu.local/graphjam/2008/11/06/test4/';
print($url);
print(urlencode($url));
?>

it produces these results in HTML:

http://wpmu.local/graphjam/2008/11/06/test4/
http://wpmu.local/graphjam/2008/11/06/test4/
http://wpmu.local/graphjam/2008/11/06/test4/
http://wpmu.local/graphjam/2008/11/06/test4/
http%3A%2F%2Fwpmu.local%2Fgraphjam%2F2008%2F11%2F06%2Ftest4%2F

I would expect lines 2, 3 and 5 of the output to be URL encoded, but only line 5 is so.  Thoughts?

[A]
According to the docs,
```
the_permalink
```
prints the permalink vs returns it. So,
```
urlencode
```
isn't getting anything to encode.
Try
```
get_permalink
```
.
[
EDIT
]
A little late for an edit, but I didn't realize the print counts were such an issue.
Here's where they're all coming from:
```
```
<?php
print(the_permalink());                                // prints (1)
$permalink = the_permalink();                          // prints (2)
print($permalink);                                     // nothing
print(urlencode(the_permalink()));                     // prints (3)
print(urlencode($permalink));                          // nothing
$url = 'http://wpmu.local/graphjam/2008/11/06/test4/';
print($url);                                           // prints (4)
print(urlencode($url));                                // prints (5)
?>
```
```


q:
I'm looking for some image library that can work with multiple formats (jpg,gif,png), and is fast at displaying the images to the screen.

Also, it would be nice if I could specify only part of the image to render to the screen.

In the end I want to have lots of images on the screen that I can pan and zoom about.

This is for a personal project on my ppc powerbook, and I'd prefer if the library be in c++.

[A]
FreeImage.
That's for loading.
For displaying, you can either use the FreeImage methods to make a bitmap that you can then display in some control (depending on your UI).
For the real hotness in display, you'll then want to use
OpenGL
.
Also, in the meantime, I've discovered
CImg
, which isn't a library so much as a framework for doing lots of common imaging applications and works in C++.

s: huggingface

c: devops

d: intermediate


q:
I can't for the life of me find a way to make this work.

If I have 3 divs (a left sidebar, a main body, and a footer), how can I have the sidebar and main body sit next to each other without setting their positions as "absolute" or floating them? Doing either of these options result in the footer div not being pushed down by one or the other.

How might I accomplish this regardless of what comes before these elements (say another header div or something)?

In case it helps, here's an illustration of the two cases I'm trying to allow for:

Here's a simplified version of the HTML I currently have set up:

<div id="sidebar"></div>
<div id="content"></div>
<div id="footer"></div>

[A]
You need to specify the footer to clear the float:
```
```
#footer{
 clear: both;
}
```
```
This forces it under floated elements.
Other options for clear are left and right.


q: Is it acceptable to submit from an http form through https?  It seems like it should be secure, but it allows for a man in the middle attack (here is a good discussion).  There are sites like mint.com that allow you to sign-in from an http page but does an https post.  In my site, the request is to have an http landing page but be able to login securely.  Is it not worth the possible security risk and should I just make all users go to a secure page to login (or make the landing page secure)?

[A]
Posting a form from an http page to an https page does encrypt the data in the form when it is transmitted in the most simple terms. If there is a man-in-the-middle attack, the browser will warn you.
However, if the original http form was subjected to man-in-the-middle and the https post-back address was modified by the attacker, then you will get no warning. The data will still actually be encrypted, but the man-in-the-middle attacker would be able to decrypt (since he sent you the key in the first place) and read the data.
Also, if the form is sending things back through other means (scripted connections) there may be a possibility of unencrypted data being sent over the wire before the form is posted (although any good website would never do this with any kind of sensitive data).


q: Does anyone know of an already implemented money type for the .NET framework that supports i18n (currencies, formatting, etc)? I have been looking for a well implemented type and can't seem to find one.

[A]
I think you want to use the decimal data type, and use the appropriate overload for
ToString()
.
```
```
CultureInfo current  = CultureInfo.CurrentCulture;
decimal myMoney = 99.99m;

//formats as money in current culture, like $99.99
string formattedMoney = myMoney.ToString("C", current);
```
```


q: Just as an example, if I have a Book model and a BooksController, autotest, part of the ZenTest suite will pick up the association between the two and load test/unit/book_test.rb and test/functional/books_controller_test.rb into the test suite. On the other hand, if I have a Story model and a StoriesController, autotest refuse to "notice" the test/functional/stories_controller_test.rb


q:
Is which IPs are assigned to which ISPs public information?  How do geo IP services obtain this information and maintain this information?

How can I personally figure out where a certain IP belongs without using one of these services?

[A]
Beware, the data is often slow to be updated, and even slower to replicate.  My work place changed ISPs a number of years ago, and we were assigned a block of formerly Canadian IP addresses (we're based in the US), for months Google continued to give us google.ca as our default search engine.  About 1/2 the time my home IP address comes up as being from my town, the other 1/2 from a town in another state.
Jason is right that the process is the same, but the updates are even slower and the data less accurate.


q: Is there any benefit on Windows to use the WSA winsock functions compared to the BSD-style ones?

[A] Only if you plan to deploy to a legacy platform like Windows 95 or there is something in the winsock API that you absolutely cannot live without and you don't want to roll yourself (<-- doubtful tho).


q: I know that I need to tell my UITextField to resign first responder when I want to dismis the keyboard, but I'm not sure how to know when the user has pressed the "Done" key on the keyboard. Is there a notification I can watch for?

[A]
If you connect the DidEndOnExit event of the text field to an action (IBAction) in InterfaceBuilder, it will be messaged when the user dismisses the keyboard (with the return key) and the sender will be a reference to the UITextField that fired the event.
For example:
```
```
-(IBAction)userDoneEnteringText:(id)sender
{
    UITextField theField = (UITextField*)sender;
    // do whatever you want with this text field
}
```
```
Then, in InterfaceBuilder, link the DidEndOnExit event of the text field to this action on your controller (or whatever you're using to link events from the UI). Whenever the user enters text and dismisses the text field, the controller will be sent this message.


q: How would one create fancy UIs in .NET, with glossy buttons and smooth animations?  You can point me to 3rd party frameworks, but I would like to understand the technical details also.

[A]
Maybe take a look at
WPF
.
In terms of 3rd party libraries:
DevExpress
Telerik
Infragistics


q:
When you lock an object is that object locked throughout the whole application?

For Example, this snippet from C# 3.0 in a Nutshell Section 19.6.1 "Thread Safety and .NET Framework Types":

static void AddItems(  )
  {
    for (int i = 0; i < 100; i++)
      lock (list)
        list.Add ("Item " + list.Count);

    string[] items;
    lock (list) items = list.ToArray(  );
    foreach (string s in items) Console.WriteLine (s);
  }

Does the first lock:

lock (list)
        list.Add ("Item " + list.Count);

prevent another thread from accessing:

lock (list) items = list.ToArray(  );

or can both be executed at the same time?

And does the CLR automatically make your static methods thread safe? Or is that up to the developer?

Thanks,
John

[A]
The CLR doesn't automatically make static methods thread-safe; you must do it yourself.
lock(list) uses that object as a lock, so if a different thread reaches another point with lock(list) (with the same 'list' object), the other thread will block until the first thread releases the lock.
To be clear, lock(foo) doesn't "lock the foo object", rather it acquires the lock associated with the foo object so that the critical section (the statement in the construct "lock(o) stmt") runs only when the current thread has acquired the lock.


q: Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn't a built-in function to do this directly. What options do I have (if any)?

[A]
```
```
interface IInterface
{
}

class TheClass implements IInterface
{
}

$cls = new TheClass();
if ($cls instanceof IInterface) {
    echo "yes";
}
```
```
You can use the "instanceof" operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a particular interface.


q:
ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db.  What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it.  Now I need to pass the string into a function that
does this operation:

strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30)

I get this error:

chr() arg not in range(256)

If I try to encode the string as latin-1 first I get this error:

'latin-1' codec can't encode characters in position 0-3: ordinal not
  in range(256)

I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it!

[A]
Your first error 'chr() arg not in range(256)' probably means you have underflowed the value, because chr cannot take negative numbers. I don't know what the encryption algorithm is supposed to do when the inputcounter + 33 is more than the actual character representation, you'll have to check what to do in that case.
About the second error. you must decode() and not encode() a regular string object to get a proper representation of your data. encode() takes a unicode object (those starting with u') and generates a regular string to be output or written to a file. decode() takes a string object and generate a unicode object with the corresponding code points. This is done with the unicode() call when generated from a string object, you could also call a.decode('latin-1') instead.
```
```
>>> a = '\222\222\223\225'
>>> u = unicode(a,'latin-1')
>>> u
u'\x92\x92\x93\x95'
>>> print u.encode('utf-8')
ÂÂÂÂ
>>> print u.encode('utf-16')
ÿþ
>>> print u.encode('latin-1')

>>> for c in u:
...   print chr(ord(c) - 3 - 0 -30)
...
q
q
r
t
>>> for c in u:
...   print chr(ord(c) - 3 -200 -30)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: chr() arg not in range(256)
```
```


q:
Is anyone aware of any gems, tutorials, or solutions enabling a user to sign in to a website at one domain and automatically given access to other partner domains in the same session?

I have two rails apps running, let's call them App-A and App-B. App-A has a database associated with it, powering the registration and login at App-A.com. I'd now like to give all of those users with App-A.com accounts access to App-B.com, without making them reregister or manually login to App-B.com separately.

Thanks in advance for any help!
--Mark

[A]
You can set the same session_key in both apps. In appA environment.rb change the session_key, like this
```
```
Rails::Initializer.run do |config|
   ...
 config.action_controller.session = {
   :session_key => '_portal_session',
   :secret      => '72bf006c18d459acf51836d2aea01e0afd0388f860fe4b07a9a57dedd25c631749ba9b65083a85af38bd539cc810e81f559e76d6426c5e77b6064f42e14f7415'
  }
  ...
end
```
```
Do the same in AppB. (remember to use the very same secret)
Now you have shared sessions. Let's say you use restfull_authentication, wich sets a session variable called
user_id
. When you authenticate in appA it sets the user_id in the session. Now, in appB you just have to verify if user_id exists in the session.
This is the overall schema, you can elaborate more using this idea.


q: How can I know in a C#-Application, in which direction the screen of the mobile device is orientated? (i.e. horizontal or vertical).

[A]
Just guessing but my first attempt would be:
```
```
var rect = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
// or var rect = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;

var ratio = rect.Width / rect.Height;

if (ratio == 1.0) // square screen.
if (ratio > 1.0) // landscape.
if (ratio < 1.0) // portrait.
```
```


q:
I'm using QT's QGLFramebufferObject for off-screen rendering.

After rendering to the buffer I read the result using glReadPixels()

The problem is that sometimes the background color I read is just 0 (transparent black) and sometimes it is 0xFF000000 (opaque black)

This seem to be related to the time the buffer is initialized. If the buffer is a member of the class inherited from QGLWidget then it is 0. If it is initialized anywhere else it's 0xFF000000.

Does anybody have any idea what's going on here? What is the good expected result of this read?

[A]
Do you set up the correct clear color (glClearColor) and actually do a clear (glClear)? Are you making sure that your color write (glColorMask) mask is fully enabled (it also affects clears). Next you can check if QT sets up some weird pixel copy transfer (other than the default, see glPixelStore, glPixelTransfer and glPixelMap). Are you sure you are getting (and reading into) an RGBA buffer in both cases, not just RGB? Lastly, it is very well possible that the framebuffer object extension is buggy on your particular graphics card/driver combination, more so if there is no primary visible window. At least check cards from both vendors. And of course always check glGetError after all potentially failing operations.
After re-reading your question, do you get any other valid rendering in the non QGLWidget case at all? Does clear to say green, return green? Because it might very well be that you just did not initialize any valid OpenGL context to begin with in that case. Framebuffer objects, unlike pbuffers need an external context.


q:
How to, in C# round any value to 10 interval? For example, if I have 11, I want it to return 10, if I have 136, then I want it to return 140.

I can easily do it by hand

return ((int)(number / 10)) * 10;

But I am looking for an builtin algorithm to do this job, something like Math.Round(). The reason why I won't want to do by hand is that I don't want to write same or similar piece of code all over my projects, even for something as simple as the above.

[A]
Rounding a float to an integer is similar to (int)(x+0.5), as opposed to simply casting x - if you want a multiple of 10, you can easily adapt that.
If you just want to do integer math and are rounding it to ten, try (x+10/2)/10*10.
Edit:
I noticed that this response doesn't meet the original's author's request, and is also a biased form of rounding that I prefer not to do.  However, another accepted response already stated Math.round(), a much better solution.


q:
I have some question:

How to make a role based web application? Such as in forum sites, there is many user types, admin, moderator etc... is the roles of these user types stored in database or web.config? And when a user login to our site, how to control this users roles? In short I want to learn about authorization and authentication.

Thanks..

[A]
Check this articles and videos:
Introduction to Membership
Managing Authorization Using Roles
Creating the Application Services Database for SQL Server
Examining ASP.NET 2.0's Membership, Roles, and Profile
Membership and Role Providers in ASP.NET 2.0
(Tutorial)
ASP .NET Security Videos


q:
I would like to create a DLNA server in VB.NET.
Since a lot of multimedia devices start supporting DLNA, i would like to see what is possible. Not only streaming video/audio and pictures but see what else can be done.

Anybody any starting points? protocol info, some basic code to get started?

DLNA is based on UPnP so i geuss that is the direction i have to start looking.

[A]
You have to be a member of the DLNA community or pay $500 to be able to get a full specification of the protocol according to their
homepage
.
Intel has a
tool
for generating source code which is DLNA compliant at their hompepage. That could be a good start for just playing around and trying your ideas without having to buy the specification.


q:
I'm trying to figure out how all these work together. I know that a DTO is basically just a container of data for the Domain Objects to pass back and forth to forms and such. Does the Domain object contain a DTO or do the DTO and the Domain Object happen to just have all of the same properties that will be mapped manually?

If I am exposing my DTO type in a service, how do I use the getters and setters without creating a round trip for each get/set operation on the client? I know that you can have one long constructor, but that can get ugly if you have more than 7 properties.

When implementing the Repository pattern, do I pass in the DTO or the Domain Object?

[A]
I think it's better to have the DTO contain a reference to the Domain object so that the DTO's consumers can begin using the Domain object. That said, if the DTO's consumers must not mutate the Domain object, you may need to have the DTO contain the values encapsulated in the Domain object. This can be difficult since you may need to do a deep copy of the Domain object.
I'm not sure why it's a problem that exposing a DTO type as a service would cause use of its getters/setters to do a round trip. If the service is a remote service, the returned DTO is serialized anyway and your getters/setters will get the copy of the values. If the service is not remote, it doesn't seem to be much of penalty to do a "round trip" since the client and the service are in the same process space.


q:
When copying large files using shutil.copy(), you get no indication of how the operation is progressing..

I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of open().read() and .write() to do the actual copying. It displays the progress bar using sys.stdout.write("\r%s\r" % (the_progress_bar)) which is a little hackish, but it works.

You can see the code (in context) on github here

Is there any built-in module that will do this better? Is there any improvements that can be made to this code?

[A]
Two things:
I would make the default block size a
lot
larger than 512. I would start with 16384 and perhaps more.
For modularity, it might be better to have the
```
copy_with_prog
```
function not output the progress bar itself, but call a callback function so the caller can decide how to display the progress.
Perhaps something like this:
```
```
def copy_with_prog(src, dest, callback = None):
    while True:
        # copy loop stuff
        if callback:
            callback(pos, total)

prog = ProgressBar(...)
copy_with_prog(src, dest, lambda pos, total: prog.update(pos, total))
```
```


q:
if Form.Release is called after using the form, it will free all related memory but not set the form variable to nil.

if not assigned (Form1) then
  begin
    Application.CreateForm(Tform1, Form1);
    try
      // Do something
    finally
      Form1.Release
    end;
  end;

To be able to call the same code again, Form1 would have to be set to nil at some point. From the description of Release I cannot do

Form1 := nil;

right after Release, because the Release procedure will return directly after being called and before the form is actually freed. I cannot detect when Form.Release is finished to set the form var to nil.

What is the best way to do this?

[A]
In Delphi Win32, the appropriate way to free objects is to call
```
```
FreeAndNil(Form1)
```
```
This does both jobs in a single call.
However, I have a sneaking feeling there's more to your question than meets the eye. Are you using Delphi for .NET - and if so, which version?


q:
Am working with django Publisher example, I want to list all the publishers in the db via my list_publisher.html template, my template looks like;

{% extends "admin/base_site.html" %}
{% block title %}List of books by publisher{% endblock %}
{% block content %}

<div id="content-main">
<h1>List of publisher:</h1>

{%regroup publisher by name as pub_list %}

{% for pub in pub_list %}

<li>{{ pub.name }}</li>

{% endfor %}
</div>
{% endblock %}

but when I run "http://127.0.0.1:8000/list_publisher/" the template just prints the page title with no error! What am I doing wrong?

[A]
A few suggestions:
check that  your base_site.html does define a
```
{% block content %}{% endblock %}
```
section to be refine by your my list_publisher.html
check the cardinality of your list:
```
{%regroup publisher by name as pub_list %}{{ pub_list|length }}
```
. That should at least display the length of your list. If is is '0'... you know why it does not display anything
check that your list is indeed sorted by name before using regroup, or use a
```
{% regroup publisher|dictsort:"name" by name as pub_list %}
```
to be sure
If the length is '0', you have to make sure publisher is defined (has been initialized from the database), and sorted appropriately.
In other word, do you see anywhere (in your template or in the defined templates):
```
```
publisher = Publisher.objects.all().order_by("name")
```
```
?
(again, the order by name is important, to ensure your regroup tag works properly)


q: The ASP.NET team released the script combining feature in 3.5 SP1 as detailed here http://www.asp.net/Learn/3.5-SP1/video-296.aspx. Is there a similar feature already for the MVC framework? If not, is this in scope or is it possible to somehow leverage the webforms capability in MVC? I see this site uses a custom jquery.package.master which, I assume, they have rolled themselves (maybe into the build cycle, however it is not all minified therefore I think they have manually appended the scripts together rather than some automated minify & combine task). Would be interested in any ideas how to accomplish this in MVC but I dont want to begin rolling any of my own functionality in case I will be duplicating work in progress.

[A]
Here's what I do, in case it's helpful.
In my postbuild I call a
command line version
of
Dean Edwards's Packer
.  It combines the scripts and packs them for me.
For now though, I keep all of my stuff seperate and use a Helper method to include my scripts, and if the debug flag is not present it will include the packed versions, otherwise it includes the unpacked.


q:
Is there an easy way to verify that a given private key matches a given public key?  I have a few *.puband a few *.key files, and I need to check which go with which.

Again, these are pub/key files, DSA.

I would really prefer a one-liner of some sort...

[A]
Encrypt something with the public key, and see which private key decrypts it.
This
Code Project article
by none other than
Jeff Atwood
implements a simplified wrapper around the .NET cryptography classes. Assuming these keys were created for use with RSA, use the asymmetric class with your public key to encrypt, and the same with your private key to decrypt.


q: How can I debug a MinGW EXE with the Microsoft Visual C++ debugger?

[A] You can attach the Visual C++ debugger to any process running on the system (from the Visual C++ menu). But for being able to step through your source code Visual C++ would have to load the symbol file (.pdb if I remember correctly) and I don't think GCC generates those files.


q:
Can someone please derive a concrete example from the following:

http://www.urdalen.com/blog/?p=210

..that shows how to deal with one-to-many and many-to-many relationships?

I've emailed the author some time ago but received no reply.  I like his idea, but can't figure out how to implement it beyond simple single table relations.

Note: I don't want to use a full-blown ORM.  I like doing my SQL by hand.  I would like to improve the design of my app code though.  Right now each domain object has its own class full of queries wrapped in static methods.  They just return scalar, 1d-array (record) or 2d-array (recordset) depending on the query.

[A]
The problem of ORM's (The impedance mismatch, as it's called) is precisely with relations. In an object graph (In-memory objects), relationships are pointers to other objects. In a relational database, relationships are reversed; This makes it impossible to do a simple mapping between the two models, and that is why ORM's are so complex.
If you want to stay close to the database (avoiding an ORM), then you shouldn't try to abstract relationships away. The way I write datamappers is something like the following:
```
```
$car42 = $car_gateway->fetch(42);
$wheels = $wheel_gateway->selectByCar($car42);
```
```
In contrast to the ORM way:
```
```
$car42 = $car_gateway->fetch(42);
$wheels = $car42->selectWheels();
```
```
This does mean that the gateways end up in your client-code, but it also keeps things very transparent and close to the database.


q: Is there an intuitive way, or a good mnemonic, for understanding the correspondence between colors and their hexadecimal values?

[A] Hexadecimal colours are of the form #RRGGBB where RR is red, GG is green and BB is blue. Since they're hexadecimal they range from 00-FF. It should be fairly easy from that to gauge roughly what kind of colour you're dealing with for example #FF12A3 is going to be fairly red.


q:
I'm trying to setup a bidirectional localConnection (LC) between two flash objects on the same web page. One object is AS2 and the other AS3.

I'm using one LC object to send and receive data on each swf. (This shouldn't matter, right? I tried using two objects, one for sending and one for receiving, but got the same problem).

They .connect() properly so that they both listen.
But I'm getting errors when I'm trying to send data from the AS2 SWF to the AS3 LC.
This happens 95% of the time, but sometimes it DOES work, so I know it's not a problem with the LC names (I checked, obviously)

Sometimes one or two messages go through and consequtive messages fail.

Any idea on what might cause it?

I'm aiming to create a many-to-one connection map so that many AS2 swfs could connect to the one AS3 swf. Will that be a problem?

[A]
One possible cause is that I've noticed that multiple listeners to the same LC name seem not to work. To see what I mean, open
this page
on two different tabs, and you should see that both of the "sending" SWFs work, but the message is only received on the first tab you opened. I guess you're only using two SWFs, but if they're both trying to listen to the same LC name, perhaps you're seeing something similar?
Also, I believe LC is, in some way, disabled for SWFs that are inside invisible page elements, or possibly even just offscreen. Are you doing anything like that?


q: In c++ what is object slicing and when does it occur?

[A]
Third match in google for "C++ slicing" gives me this Wikipedia article
http://en.wikipedia.org/wiki/Object_slicing
and this (heated, but the first few posts define the problem) :
http://bytes.com/forum/thread163565.html
So it's when you assign an object of a subclass to the super class. The superclass knows nothing of the additional information in the subclass, and hasn't got room to store it, so the additional information gets "sliced off".
If those links don't give enough info for a "good answer" please edit your question to let us know what more you're looking for.


q: What the minimum basic setup required to begin developing a Firefox extension?

[A]
Precaution: In order to prevent messing with your default Firefox experience, try the tip below on a newly created disposable test account.
Step 1: Create a new Firefox profile. For this you need to invoke the Profile Manager via command line option:
```
```
firefox.exe -profilemanager
```
```
Click on the 'Create Profile' button of the Profile Manager, which will invoke a wizard. Give the profile a name. Use the 'Choose Folder' button and save the profile in a appropriately named folder. This folder is where we are going to create our quick and dirty Firefox extension.
Step 2: Change directory to 'extensions' folder within the profile folder created in Step 1. Now we need to give the Firefox extension a globally unique name. Email-like names are good enough for that. For example, OneMinuteFirefoxExtension@ec29.com will be good enough name for the extension. Under the 'extensions' folder, create a folder with its name as the just chosen unique name.
Step 3: Create files chrome.manifest and install.rdf. You can copy paste the sample here with the names, description altered appropriately.
chrome.manifest:
```
```
content 1mffext chrome/
```
```
and install.rdf:
```
```
<?xml version="1.0"?>
<RDF:RDF xmlns:em="http://www.mozilla.org/2004/em-rdf#"
         xmlns:NC="http://home.netscape.com/NC-rdf#"
         xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <RDF:Description RDF:about="rdf:#$Fsv+Z3"
                   em:id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"
                   em:minVersion="2.0"
                   em:maxVersion="3.0.*" />
  <RDF:Description RDF:about="urn:mozilla:install-manifest"
                   em:id="1m-ff-ext@ec29.com"
                   em:type="2"
                   em:name="OneMinuteFirefoxExtension@ec29.com"
                   em:version="0.0.1"
                   em:description="One Minute FireFox extension"
                   em:creator="labsji "
                   em:homepageURL="http://labsji.wordpress.com">
    <em:contributor>Venkat83</em:contributor>
    <em:targetApplication RDF:resource="rdf:#$Fsv+Z3"/>
  </RDF:Description>
```
```
Step 4 Create folder called chrome and create a text file called test.txt within the folder. files in the folder will be accessible via chrome url like chrome://1mffext/content/test.txt
Now the bare minimum extension is ready. Regular html/javascript files can be used to create the functionality desired.
Testing the Extension:
Invoke firefox to use the profile created above.
```
```
firefox.exe -profile <path of the newly created profile> -no-remote
```
```
I have created a googlecode project to share the resultant code created following the steps above. The code along with run scripts are available at
Just a Minute Firefox Extension
Sim-OnDemand- personal virtual world as a Service's
launcher application
is an example of an application packaged and distributed using this method.


q:
I want to write an Add-In for Visual Studio that provides instant search for the solution explorer. So you press a key combination and while you are typing a list first containing all files of the solution explorer gets narrowed down.

But how can I get access to the solution explorer using C#? Does anyone have some good resources?

Edit: I edited the title, so that it more relates to the content, since all of you posted already made plug-ins.

[A]
Why re-invent the wheel? DevExpress + Microsoft tied up to offer
CodeRush Express
for free @ PDC2008 that does just that if I understand you correctly.
AFAIR I think the magic key combo for Jump to File is Ctrl+Alt+F and it does substring matches too. I tried it and it worked for me. Pretty nifty. Here's
the link
to a recording in case I goofed up on the actual keystroke... some really nice tips in it.
Update
: Wrote
a blog post
for those who're short of time.


q:
I am getting the following error while loading a page.

[HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.]

No idea what to do ? Can anyone help me  ?

[A]
I'm guessing you have done something like this:
```
```
Response.Redirect("../SomePage.aspx");
```
```
When using relative paths, you can only navigate to pages that are in the same Virtual Directory as the one the page making the request is in. What you have done is called this from a page that is at the top of the Virtual Directory tree. So you have some options:
Correct your url so that it does not point to a higher level. ie: remove the
```
../
```
Use a full url. ie:
```
http://www.example.com/SomePage.aspx
```
Use IIS to set the Virtual Directory at a higher level.
For Option 3:
Open up IIS manager.
Go to the directory that the page is in and right click/properties.
On the Virtual Directory tab select Remove.
Close the dialogue and right click/properties on the directory you do want to be the root.
On the Virtual Directory tab select Add


q:
When I try to create a Excel 2007 Workbook project, in Visual Studio 2008, I get the following errormessage:

Project cannot be created because the "Excel Visual Studio Design-Time Adaptor Add-in" is not working correctly. Excel might have disabled the add-in or made it inactive, or all add-ins might be disabled in your Trust Center settings. Check the add-in status in Excel Options. If the add-in is active and enabled, reinstall or repair Visual Studio Tools for Office.

I have verified that the add-in is not inactive or disabled and I have tried to repair and uninstall/reinstall VSTO several times.

What to do?

[A]
Just in case you haven't checked the trust settings, this
MSDN page
describes how to.
I came across this on a MSDN forum:
For the repair to work, you'll have to
  run the VS Command Prompt with Admin
  Priviledges (right click, run as
  administrator). Then run this command
  line:
C:>AddinUtil
  -AddInRoot:"%CommonProgramFiles%\Microsoft
  Shared\VSTA\AppInfoDocument" -Rebuild
If it still doesn't work, you may also
  have a corrupt pipleline store, which
  can be fixed like this:
C:>AddinUtil
  -PipelineRoot:"%CommonProgramFiles%\Microsoft
  Shared\VSTA\Pipeline" -Rebuild
You'll get one warning from that
  command but that is expected.
Failing that, I think you will have to run a repair on the Visual Studio 2008 installation (put the installation DVD in a drive, and select the repair option).


q:
I want to be able to change the status message for Live Messenger, but everything I've found only works for the music message (see this screenshot to see the difference between the two).

It is possible to do this, as there are programs that have the ability to change it, and some alternate clients for Live Messenger can also set the status message themselves. I just need to know how to do this myself.

Clarification: The solution needs to work with the latest versions of Live Messenger (i.e. the wave 3 beta). Working with older versions is good too, but it's the 14.x versions that I'm working with.

[A]
Of course, from any conversation windows, a simple "
```
/psm new message
```
" would update the message status field.
But
programmatically
:
You will find here a
VB source file
which sent a new message to the PSM (Personal Satus Message) of your Live Messenger windows. May be that would help.
extract:
```
```
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Const WM_COMMAND = &H111
Private Const WM_CHAR = &H102
Private Const VK_RETURN = &HD

Private Function SetPSM(ByVal text As String) As Boolean
   Dim hParentWnd, hChildWnd As Long
   SetPSM = False
   hParentWnd = FindWindow("MSBLWindowClass", vbNullString)
   If hParentWnd <> 0 Then
      hChildWnd = FindWindowEx(hParentWnd, 0, "DirectUIHWND", vbNullString)
      If hChildWnd <> 0 Then
         PostMessage hParentWnd, WM_COMMAND, 56606, 0
         Dim i As Integer
         For i = 1 To Len(text)
            Call PostMessage(hChildWnd, WM_CHAR, Asc(Mid$(text, i, 1)), 0)
         Next i
         PostMessage hChildWnd, WM_CHAR, VK_RETURN, 0
         SetPSM = True
      End If
   End If
End Function

Private Sub cmdSetPSM_Click()
   SetPSM txtPSM.text
End Sub
```
```


q: Can we programatically login to Yahoo services with our ID, send instant message, use webcam service and so on directly from our program?

[A]
Yahoo Messenger has a
plug-in SDK
. It is hard to know if this meets your needs, since you are not very clear.
If you are looking to access Yahoo messenger services through Java for instance, you could try an
API
.


q: Are there any obvious productivity gains in developing using webforms or MVC?

[A] No. Personally, I find MVC works much more like my brain does with pretty clear separation of what goes where and why. I banged out a complete prototype commerce site with MVC in a few weeks that would've taken me, I'm sure, at least double that using webforms.


q:
Are there anyone with experiences/examples on releasing early/releasing often for commercial software? Does it work?

I was thinking of VMware where they have a lot of revisions release between each major version. And the installation experience was awful, sometimes they would break the existing VMs and other times the VMware Tools inside guest OSes would malfunction/not install. It's just horrible.

And I was thinking of ClickOnce deployments as well, since with ClickOnce when you update your software, all clients automatically gets notified of the release, and with one-click they're updated to the new version. If your software has bugs, then they'll automatically "upgraded" to get those bugs as well.

Do you have experience\example\suggestion to applying the release early/release often principle to commercial software?

I'm looking to apply it to one.

[A]
I think it always will depend on your market or customer base. Changing/upgrading software is always painful and even more painful in some environments and companies. Fast release cycles can be disruptive. These disruptions often extend to your internal operations too, depending on how well feature creep is managed by marketing/management.
So, the classic ever true 'it depends' answer rings again.
If you are really adding value to the product, then customers especially new ones will want it. The best case, is to remove the upgrade change pain, as in, it works the same, but better in obvious ways. Great.


q:
What benchmark would test how well my hardware rates, for my ASP.NET, SQL Server, IIS product?

I have two servers, one runs my code much faster than the other and I believe their configurations are close to equivalent and therefore I want to benchmark the two.

I do not want this question to become one about the hardware.

This question is asking how I would test how good my hardware rates, for my software.

In other words, a 3D benchmark doesn't accurately rate my system for an ASP.NET/SQL Server app.

[A]
After clarification, then I think you are looking for a
stress testing application
:
You can host your application on the two boxes, and then use another box to mass-send requests to it with a stress test app.
Then you can look at the statistics, e.g. Hits per seconds. Responses per second, etc.
I have never used one myself before but
Google knows some
.
What do you mean? Could you clarify?
PCMark benchmarks the hardware, not the software.
Are you looking for a Profiler?
The company that build Resharper and Teamcity,
has one
.
It is a kind of software benchmark.


q:
There seem to be 3 ways of telling GCC to weak link a symbol:

__attribute__((weak_import))

__attribute__((weak))

#pragma weak symbol_name

None of these work for me:

#pragma weak asdf
extern void asdf(void) __attribute__((weak_import, weak));
...
{
    if(asdf != NULL) asdf();
}

I always get a link error like this:

Undefined symbols:
  "_asdf", referenced from:
      _asdf$non_lazy_ptr in ccFA05kN.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

I am using GCC 4.0.1 on OS X 10.5.5. What am I doing wrong?

[A]
From the gcc doc manual:
weak
The weak attribute causes the declaration to be emitted as a weak
  symbol rather than a global.  This is primarily useful in defining
  library functions which can be overridden in user code, though it
  can also be used with non-function declarations.  Weak symbols are
  supported for ELF targets, and also for a.out targets when using
  the GNU assembler and linker.
which means that an object is legitimated to overwrite a weak symbol (defined in another object/library) without getting errors at link time. What is unclear is whether you are linking the library with the
weak
symbol or not. It's seems that both you have not defined the symbol and the library is not properly linked.


q:
I read somewhere in the Microsoft documentation that the content of the ASP.NET's web.config is cached. If that is true, where is it cached - in memory or on disk?

And a follow-up question: are there any performance considerations I have to make, if I have to access the web.config intensively?

[A]
I think that the web.config is cached in memory (in object instances from System.Web.Configuration). Those are reloaded when the .config file is changed (and thus reloading your web app).
Hitting those objects is unlikely to give you a performance bottleneck. But if you have to do parsing etc, you might want to hold on the the parsed objects.
[Extra] I good practice (I think at least) is to create static properties in your global.asax.cs file for you appsettings. You can instantiate those properties in the application_start method and use them through out your web app. This prevents you from using hard-coded string (configuration keys) throughout your code.


q:
Duplicate of How do you make sure email you send programmatically is not automatically marked as spam?

Initially I planned to send emails from my website as html (i.e. content-type: text/html;) but I just thought about something today, won't it better to send emails as plain text, i.e. content-type: text/plain;, so that the chances of my mail messages ending up in the spam/junk folder become less, I was thinking that this must be one the rules used by spam filters on popular webmail services like gmail, yahoo and hotmail, what do you think?

[A]
In my experience, most anti-spam systems will score HTML's Hamminess slightly below plaintext, but there are much more important things to consider that affect deliverability:
make sure you have a valid Reverse DNS configuration for your mail server, or you will be undeliverable to many domains.
investigate adding an
SPF
record to your DNS zone file. This helps, particularly with GMail.
Look into
DomainKeys
, if it's available on your platform. This is essentially a cryptographic signature attached to your outbound mail, so it proves that you are the person who sent it.
Review your message content and make sure you aren't using any words (particularly in the subject line) that are obvious spam indicators.


q: After logging in using the Login control the browser loses the session.  This only occurs in Internet Explorer 7.  Has anyone else run into this problem?  If so, do you know a work around?

[A]
I would suggest downloading a tool like
ieHTTPHeaders
to trace the request/respnonse headers in IE and seeing at what point either IE stops sending the cookie or the server clears it.
You should see a POST to your login page and the server should respond with a Set-Cookie:, and that cookie should be in every subsequent request.


q: How do I get a list of all the headings in a word document by using VBA?

[A]
You mean like this
createOutline
function (which actually copy all headings from a source word document into a new word document):
(I believe the
```
astrHeadings = docSource.
GetCrossReferenceItems
(wdRefTypeHeading)
```
function is the key in this program, and should allow you to retrieve what you are asking for)
```
```
Public Sub CreateOutline()
    Dim docOutline As Word.Document
    Dim docSource As Word.Document
    Dim rng As Word.Range

    Dim astrHeadings As Variant
    Dim strText As String
    Dim intLevel As Integer
    Dim intItem As Integer

    Set docSource = ActiveDocument
    Set docOutline = Documents.Add

    ' Content returns only the main body of the document, not the headers/footer.
    Set rng = docOutline.Content
    ' GetCrossReferenceItems(wdRefTypeHeading) returns an array with references to all headings in the document
    astrHeadings = docSource.GetCrossReferenceItems(wdRefTypeHeading)

    For intItem = LBound(astrHeadings) To UBound(astrHeadings)
        ' Get the text and the level.
        strText = Trim$(astrHeadings(intItem))
        intLevel = GetLevel(CStr(astrHeadings(intItem)))

        ' Add the text to the document.
        rng.InsertAfter strText & vbNewLine

        ' Set the style of the selected range and
        ' then collapse the range for the next entry.
        rng.Style = "Heading " & intLevel
        rng.Collapse wdCollapseEnd
    Next intItem
End Sub

Private Function GetLevel(strItem As String) As Integer
    ' Return the heading level of a header from the
    ' array returned by Word.

    ' The number of leading spaces indicates the
    ' outline level (2 spaces per level: H1 has
    ' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.

    Dim strTemp As String
    Dim strOriginal As String
    Dim intDiff As Integer

    ' Get rid of all trailing spaces.
    strOriginal = RTrim$(strItem)

    ' Trim leading spaces, and then compare with
    ' the original.
    strTemp = LTrim$(strOriginal)

    ' Subtract to find the number of
    ' leading spaces in the original string.
    intDiff = Len(strOriginal) - Len(strTemp)
    GetLevel = (intDiff / 2) + 1
End Function
```
```
UPDATE by @kol on March 6, 2018
Although
```
astrHeadings
```
is an array (
```
IsArray
```
returns
```
True
```
, and
```
TypeName
```
returns
```
String()
```
) I get a
```
type mismatch
```
error when I try to access its elements in VBScript (v5.8.16384 on Windows 10 Pro 1709 16299.248). This must be a VBScript-specific problem, because I can access the elements if I run the same code in Word's VBA editor. I ended up iterating the lines of the TOC, because it works even from VBScript:
```
```
For Each Paragraph In Doc.TablesOfContents(1).Range.Paragraphs
  WScript.Echo Paragraph.Range.Text
Next
```
```


q:
How do I check for an open connection in jdbc for oracle database?

Note: conn.isClosed() cannot be used for this.

[A]
Something like:
```
```
Statement stmt = null;
ResultSet rs =null;
try {
   stmt = conn.createStatement();
   // oracle
   rs = stmt.executeQuery("SELECT 1 FROM Dual");
   // others
   // rs = stmt.executeQuery("SELECT 1");
   if (rs.next())
      return true; // connection is valid
}
catch (SQLException e) {
   // TODO : log the exception ...
   return false;
}
finally {
   if (stmt != null) stmt.close();
   if (rs != null) rs.close();
}
```
```
Note that if the connection is coming from a Connection Pool (in a Application Server for example) then the Pool may have a mechanism to check if a connection is valid or not. With BEA, you specify the SELECT in the "test-on-reserve" property.
If you are developing your own pool then you may want to take a look at how others are doing it (ex.
Proxool
).


q: I have some elements on a page which are draggable. These same elements have a click event which navigates to another page. I'm trying to determine the best way of preventing the click event from firing if the user is dragging but still allow the click event if not dragging. Anyone have any ideas of the best way to accomplish this?

[A]
Something like the following might do the trick (and prevent the click event to be fired up)
```
```
new Draggable('tag',
    {
        revert:function()
        {
            $('tag').onclick = function(){return false;};
            setTimeout('$(\'tag\').onclick = function(){return true;}','500');
            return true;
        }
    }
);
```
```


q:
I'm listening to podcast #19 and Joel and Jeff are arguing about running SQL Server on the same machine as your IIS installation. I have to say that it sounds like Jeff folded to Joel, but then again I am only guessing which one is which. ;)

What are the pros and cons of each? Which is better?

I typically run them separately (Joel's preference) but I can see Jeff's point where the two are closer to each other.

[A]
For
security purposes
it is good to separate web and database machines, preferably having a firewall between the two. A web server is exposed to the world at large. Unfortunately there are people who take pleasure in stealing or damaging the information contained on those servers.
Then there is the
performance aspect
. It's common knowledge that SQL Server loves memory. So does IIS, particularly if the web-site makes extensive use of caching and session information. So you have a potential conflict here as well. Having a dedicated machine for SQL Server is clearly better than having a single machine doing all the load.
Then, separation allows
easier identification of the need to tune
and the ability to tune individual hardware components.
To sum up, a machine powerful enough to cope with the demands of both IIS and SQL Server in a live environment
won't necessarily be cheaper than two machines
specced for the specific requirements of each server.
(Jeff Atwood mentioned in one of the podcasts, that upgrading the one machine would have cost the same as getting a second machine)
.


q: is there an easy way to reset ALL text fields in an asp.net form - like the reset button for html controls?

[A]
Some solutions are listed here:
Clear a form in ASP.Net
I was looking for the same solution in ASP.Net to clear my form on the click and I landed on this post. I looked at all the comments and replies. I decided to use the plain old input tag and created a HTML reset button .It worked like a charm, no postbacks, not javascripts. If there is any catch, I couldn't find it...


q:
If I have a date, how do I calculate the week number for that date within that year?

For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.

An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.

Related:

Getting week number off a date in MS SQL Server 2005?

[A]
Pseudocode:
```
```
int julian = getDayOfYear(myDate)  // Jan 1 = 1, Jan 2 = 2, etc...
int dow = getDayOfWeek(myDate)     // Sun = 0, Mon = 1, etc...
int dowJan1 = getDayOfWeek("1/1/" + thisYear)   // find out first of year's day
// int badWeekNum = (julian / 7) + 1  // Get our week# (wrong!  Don't use this)
int weekNum = ((julian + 6) / 7)   // probably better.  CHECK THIS LINE. (See comments.)
if (dow < dowJan1)                 // adjust for being after Saturday of week #1
    ++weekNum;
return (weekNum)
```
```
To clarify, this algorithm assumes you number your weeks like this:
```
```
S  M  T  W  R  F  S
            1  2  3    <-- week #1
4  5  6  7  8  9 10    <-- week #2
[etc.]
```
```
getDayOfWeek() and getDayOfYear() are standard date-object operations in most languages.  If yours doesn't have them, you can count-forward from some known date (Jan 1, 1970 is a common one), after looking up to see what day of the week it was.
If you're going to implement your own date counting routines, remember that years that are divisible by 100 are
NOT
leap years, unless they are also divisible by 400.  So 1900 was not a leap year, but 2000 was.  If you're going to work far back in time, you have to mess with Gregorian vs Julian calendars, etc., see
Wikipedia
for loads of info on that.
This link
talks about date/time functions in Windows/C++ in greater detail.


q:
I am modifying some code and came across a declaration that I am having trouble understanding:

int *userMask[3][4] = {0};

What exactly is this pointing to?  Is it a matrix where every element is a pointer?  Or is it pointing to a matrix of size [3][4]?

Thanks

I guess my question is how userMask[2][maskElement][user] can work when it is declared as int.  Wouldn't userMask have to be int[] for that to work properly?  I must not be understanding this right...

On a side note, thanks for your suggestion about cdecl Robert.  However, does anyone know how to use it in an XP command prompt?  All I can get is syntax error :(

[A]
This is a two-dimensional array where each element is a pointer to an
```
int
```
, and all the pointers are initialised to zero.
In your follow-up, you show that the array is used like this:
```
```
if(userMask[2][maskElement][user] && blah)
    result = true;
```
```
In this case, each element in
```
userMask
```
should actually point to an array of
```
int
```
s. (An
```
int*
```
can point to a single
```
int
```
or an array of
```
int
```
s). To determine this, check the code that assigns values to
```
userMask
```
. For example, it is possible to write:
```
```
int userArray[2] = { 10, 20 };

userMask[0][0] = userArray; // userMask[0][0] points to the
                            // first element of userArray.
```
```
Then the following code indexes into
```
userArray
```
:
```
```
int value = userMask[0][0][1]; // sets value = userArray[1], giving 20.
```
```


q:
How have you guys handled working with jQuery includes

<script type="text/javascript" src="jquery.js"></script>

in Asp.Net MVC when working with partial views/view controls?  Basically, I don't want to make the jquery include in the master page because I am not using jquery in all of my views, but I also want an easy way for a user control to be able to create the jquery include in the right location ('head') without creating duplicate jquery includes.

The best way would be to use a ScriptManaager, but I do not want to rely on ASP.Net Ajax for this in my application.  Is there a 'lightweight' ScriptManager that I could use that would also allow the newly released intellisense for jquery?

I've created a WebControl that provides this functionality, but I don't get the intellisense support for VS2008, which I would really like.

Hope this makes sense.

[A]
You could always do this:
make a lightweight util.js that is in every page, in it you could put various common stuff, plus this:
```
```
function loadJSInclude(scriptPath, callback)
{
    var scriptNode = document.createElement('SCRIPT');
    scriptNode.type = 'text/javascript';
    scriptNode.src = scriptPath;

    var headNode = document.getElementsByTagName('HEAD');
    if (headNode[0] != null)
        headNode[0].appendChild(scriptNode);

    if (callback != null)
    {
        scriptNode.onreadystagechange = callback;
        scriptNode.onload = callback;
    }
}
```
```
Then, in your view, just place:
```
```
<script type='text/javascript'>
    if(typeof(someJqueryObject) == "undefined")
        loadJSInclude('jquery.js', doYourStuff);
    else
        doYourStuff();

    function doYourStuff()
    {
        // jQuery will be loaded now, so you can do your stuff here.
    }
</script>
```
```


q:
The CSS Friendly Control Adapters for ASP.NET are great for creating markup that is easy to style.  A big benefit of the GridView adapter is that it generates THEAD, TBODY, and TFOOT tags, which allow you to do some really great things with libraries like jQuery - for instance, Tablesorter for client-side table sorting.

The problem is that it seems to be a global on/off for the adapters through the CSSFriendlyAdapters.browser file.  What do I do if I already have a slew of GridViews currently in production and only want to use the CSS Friendly Adapters for a new one?

So I would be interested in two types of solutions:

1) A way to extend or modify GridView (a new tag is acceptable) to output THEAD and TBODY tags.

2) A way to conditionally apply or disable CSS Friendly Control Adapters.

[A]
CSS Friendly...
Disabling Adapters
If you explicitly add
  AdapterEnabled="false" to your
  server-side tag, these sample adapters
  will attempt to use the ASP.NET
  framework's native rendering for the
  control. Beware: this is not supported
  and often does not work well.
  Fundamentally, the framework does not
  support disabling adapters on a per
  control basis. The AdapterEnabled
  attribute is only intended to be used
  experimentally.
Source
Alternatively, you can create a class that derives from GridView and overrides the RenderChildren method.  It may take some experimentation to figure out how to make this work.  I haven't looked at how the controls are presented in the GridView to give you any ideas in this regard.  Presumably, you'll just need to figure out which rows are header/foot and render / around them and  around the others.


q:
According to this page, it's possible to use TClientDataset as an in-memory dataset, completely independent of any actual databases or files.  It describes how to setup the dataset's table structure and how to load data into it at runtime.  But when I tried to follow its instructions in D2009, step 4 (table.Open) raised an exception.  It said that it didn't have a provider specified.

The entire point of the example on that page is to build a dataset that doesn't need a provider.  Is the page wrong, is it outdated, or am I missing a step somewhere?  And if the page is wrong, what do I need to use instead to create a completely independent in-memory dataset?  I've been using TJvMemoryData, but if possible I'd like to reduce the amount of extra dependencies that my dataset adds into my project.

[A]
You can use
```
table.CreateDataSet
```


q:
I know we are really behind the times here, but we are just about to upgrade from .NET 1.1 to .NET 2.0.

Thank you for your sympathy.

Anyhow,  are there any gotchas we should look out for?

Do you have any general advice before we jump in?

Please do not post telling me to go straight to 3.5:  2.0 is all we're allowed!

We're using mostly C#.

[A]
Yes.  The most important thing for you to know is to use a Web Application Project, not a Web Site.  Web Sites use a totally different compilation model and migration is pretty much a disaster.  Web Application Projects are much more similar to how things worked in 1.1.
We also had an intermittent problem with redirecting from the login screen, but according to Google, we were basically the only ones who had that problem - we've since resolved it.
Most of the other problems we ran into were small and easy to navigate, and the overall experience was a net improvement.


q:
I wish to calculate the time it took for an API to return a value.
The time taken for such an action is in the space of nanoseconds. As the API is a C++ class/function, I am using the timer.h to calculate the same:

  #include <ctime>
  #include <iostream>

  using namespace std;

  int main(int argc, char** argv) {

      clock_t start;
      double diff;
      start = clock();
      diff = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
      cout<<"printf: "<< diff <<'\n';

      return 0;
  }

The above code gives the time in seconds. How do I get the same in nano seconds and with more precision?

[A]
In general, for timing how long it takes to call a function, you want to do it many more times than just once. If you call your function only once and it takes a very short time to run, you still have the overhead of actually calling the timer functions and you don't know how long that takes.
For example, if you estimate your function might take 800 ns to run, call it in a loop ten million times (which will then take about 8 seconds). Divide the total time by ten million to get the time per call.


q:
How do I remove the last character of a string if it is a newline?

"abc\n"  -->  "abc"

[A]
Try the method
```
rstrip()
```
(see doc
Python 2
and
Python 3
)
```
```
>>> 'test string\n'.rstrip()
'test string'
```
```
Python's
```
rstrip()
```
method strips
all
kinds of trailing whitespace by default, not just one newline as Perl does with
```
chomp
```
.
```
```
>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'
```
```
To strip only newlines:
```
```
>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '
```
```
In addition to
```
rstrip()
```
, there are also the methods
```
strip()
```
and
```
lstrip()
```
. Here is an example with the three of them:
```
```
>>> s = "   \n\r\n  \n  abc   def \n\r\n  \n  "
>>> s.strip()
'abc   def'
>>> s.lstrip()
'abc   def \n\r\n  \n  '
>>> s.rstrip()
'   \n\r\n  \n  abc   def'
```
```


q:
With squid, we can cache webpages. I am not sure if it provides the same number of caching methods as ASP.NET caching (I primarily use ASP.NET), but it's a tool to cache webpages.

Then we have memcached, which can cache database tables. I believe this is correct, and it is like SqlCacheDependency (correct me if I am wrong).

However, is there any situation in a large web application where one would find room to use memcached, squid, AND ASP.NET (or PHP, JSP - application framework-level) caching.

Thanks!


q:
Usually, we install VS.NET on our production server, to solve problems easily with our product, if necessary.

Is this a good or bad idea?

[A]
Both.  One of the upsides is that it can sometimes make diagnosing problems easier.  One of the downsides is that sometimes the install can break a working web application.  I would only do it if I had to.
Edit: another potential downside to this occurs when a co-worker decides to debug a live process on the production server, stops the app on a breakpoint, and then goes to bed without realizing he has left the app unavailable.  Yes, this has happened to me.


q:
I read a properties-file at the webapplication startup phase (contextInitialized()) and I started to think about how to make these settings 'visible' to the servlets. Do I need to loop through the keys and add each and every one to the context, like this

Iterator i = settings.keySet().iterator();
while (i.hasNext()) {
    key = (String) i.next();
    value = (String) settings.get(key);
    context.setAttribute(key, value);
}

or are there better methods?

Thank you!

/Adam

[A]
Have you considered the possibility of defining the settings in web.xml?
Also, if that's not possible, use generics if possible:
```
```
String key = null;
Iterator<String> i = settings.keySet().iterator();
while (i.hasNext())
 context.setAttribute(key = i.next(), settings.get(key));
```
```


q:
We have a JavaScript function named "move" which does just "windows.location.href = any given anchor".

This function works on IE, Opera and Safari, but somehow is ignored in Firefox. Researching on Google doesn't produce a satisfactory answer why it doesn't work.

Does any JavaScript guru knows about this behavior, and what would be the best practice to jump to an anchor via JavaScript?

[A]
Have you tried just using
```
```
window.location = 'url';
```
```
In some browsers,
```
window.location.href
```
is a read-only property and is not the best way to set the location (even though technically it should allow you to). If you use the
```
location
```
property on its own, that should redirect for you in all browsers.
Mozilla's documentation has a pretty detailed explanation of how to use the
```
window.location
```
object.
https://developer.mozilla.org/en/DOM/window.location


q:
If the Mono project is successful it will pave the way for commercial software on non-Windows platforms.

I am interested in the prospect of writing and selling commercial software for the Mono platform along the lines of our existing Smoke Vector Graphics (OCaml) and F# for Visualization (.NET) products. Are any commercial library developers already building upon Mono and, if so, are they turning a profit from it?

Also, will it be feasible to write the software in Microsoft's F# language or will Mono have trouble with ILX?

[A]
Linux people are notoriously thrifty, so I'd consider the ROI.
Do you really want to spend your resources to target a group that has less than 10% market adoption, and out of that 10%, only 1% would be interested in your product, and only %0.01 percent would pay for it?


q:
I'm writing a url rewrite in django that when a person goes to http://mysite.com/urlchecker/http://www.google.com   it sends the url: http://ww.google.com to a view as a string variable.

I tried doing:

(r'^urlchecker/(?P<url>\w+)/$', 'mysite.main.views.urlchecker'),

But that didn't work. Anyone know what I'm doing wrong?

Also, generally is there a good resource to learn regular expressions specifically for python/django?

Thanks guys!

[A]
Try this instead:
```
(r'^urlchecker/(?P<url>.+)$', 'mysite.main.views.urlchecker'),
```
This differs from yours in that:
It will take anything after 'urlcheck/', not just "word" characters.
It does not force the url to end in a slash.


q:
Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)

#include <iostream>

int main() {
  int a = 4;
  int b = 5;
  a, b = b, a;
  std::cout << "a: " << a << endl
            << "b: " << b << endl;

  return 0;
}

and prints:

a: 4
b: 5

What I'd like it to print ... if it weren't obvious, is:

a: 5
b: 4

As in, say, ruby, or python.

[A]
Or Perl. But no, it's not possible (as far as I'm aware), you need to use a temporary variable, as in:
```
```
int a = 4;
int b = 5;

{
    int tmp = a;
    a = b;
    b = tmp;
}
```
```
FYI, internally those languages (or Perl atleast) create a temporary list
```
{ a, b }
```
, then assign the list to the two variables. In other words, this is atleast as performant, if only a little more messy.


q:
I found this site

http://www.shutterfly.com/documentation/api_OrderImage.sfly

but there are no examples of actually walking through the whole process.  Does anyone have any good documentation on using this API to take a local photo and allow someone to order a print via shutterfly?

[A]
I went through these steps:
Sign up for an account
Sign up as a developer
Create an application (I called mine Test). Note the generated
Application Id
and
Shared Secret
The
Shutterfly API page
has a list of references for various Domain-specific APIs:
Address Book
Album Data
Folder Data
Go To Shutterfly UE
Image Upload
Interactive Sign-in
Image Request
Order
Pricing
Seamless Sign-in
User Data
User Authentication
Each uses RESTful principles. The documentation looks pretty comprehensive to me, if you need some background, here's links for
RESTful
APIs and
ROME
you may find useful
There is also an
API Explorer
section on the same page that allows you to test the methods via a form on their site. For example this form for
CRUD operations on the album data
.
Based on your comment, for your requirements, you would:
Use the
Album GET
to list albums, then get the data for a specific album.
Use the
Image Get
request to retrieve the image data, so your friend can verify the image(s) they want to purchase.
Authenticate the user
Use the
Pricing POST
request to get the estimated pricing for the image.
User the
Order POST
to submit the order over https
Update: Found a page
describing
using a Greasemonkey script which adds Shutterfly print ordering capability to Flickr. This might provide the basis for a solution.


q:
We happily use SVN for SCM at work.  Currently I've got our binary assets in the same SVN repository as our code.  SVN supports very large files (it transmits them 'streamily' to keep memory usage sane), but it makes everything SLOOWWWWW.  I'm ok with slow asset versioning, but slow text operations isn't really acceptable.

Right now assets are under /trunk/release (side by side with a dozen /trunk/projects).  Should we keep them in a separate repository?  What other optimizations can we do?  We have about a GB of assets and growing.

[A] You didn't say what optimizations you use already. If you are using bsdfs, see whether switching to fsfs improves performance. If you have a large number of revisions, switch to a more recent version on the server, and convert the repository to the 1.5 format.


q:
I'm having a problem adding a reference to a .NET assembly I built. Here's what I did.

I created a .NET assembly (testlib.dll).

I made sure it had a strong name (added a keyfile).

I creates a WiX installation project for that assembly.

I added Assembly='.net' and KeyPath='yes' to the File property for the assembly.

The installation works fine. I can see testlib in the GAC (C:\Windows\assembly).

I create a new .NET project and try to add a reference to testlib, but I don't see it in the .NET tab of the Add Reference dialog. How do I get it to show up there?

[A]
The assemblies that are in the .NET tab have no connection to the GAC.
In order to see the assemblies in the .NET tab your installer will have to write to the
following registry path:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework\AssemblyFolders
The entry should create a new key usually the application name and than set the default
value to the path that the assemblies are installed.
For example assuming the application name is MyApp and it is installed to:
C:\Program Files\MyApp
The registry full path will be
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework\AssemblyFolders\MyApp
And the default value will be:
C:\Program Files\MyApp


q:
Basically I have a website.  I have a properly setup sitemap so I assume Google knows about all of my pages.  And I've seen on some sites, the search form leads to a page with the shell of the original site but the results are clearly provided by Google.  Similar to codinghorror.com's search, however his results aren't shown within his website's layout.

Any idea what I'm talking about or how to achieve this?

[A]
Nov. 2008: Like
this
(but you will find a more
up-to-date 2012 example here
)
```
```
<form method="get" action="http://www.google.com/search">

<input type="text"   name="q" size="25"
 maxlength="255" value="" />
<input type="submit" value="Google Search" />

<input type="checkbox"  name="sitesearch"
 value="askdavetaylor.com" checked /> only search Ask Dave Taylor

</form>
```
```
For displaying the results in a separate frame, you have
this site
as an example.
That would be something along the lines of:
```
```

    <meta http-equiv="Content-Language" content="en-gb">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

    Search

        Your browser does not support inline frames or is currently configured not to display inline frames.

```
```


q:
I have 2 files:

/****demo.cpp****/
#include <iostream.h>
#include "gc.h"

class foo{};

int main(){
    gc<foo> x1;
    cout<<x1;
}

/*****gc.h*****/
template <class T> class gc
{
    T* ptr;
public:
    operator T*(){}
};

If I don't write operator T*(){} then I get a lot of compiler errors.

So plz tell me what is operator T*(void) and when it is invoked?

[A]
operator
```
T*(){}
```
is a
cast operator
.  You are providing a function that can be used to convert from a
```
gc<T>
```
to a
```
T*
```
... though it should require that you actually return something, presumably
```
ptr
```
in this case.
The problem is that the compiler doesn't know how to format your gc object to the output stream.
By providing a cast from gc to foo* it is able to output the object as just a pointer value ... probably not what you want.
You likely want to define a custom overload for the << operator to dump out your class:
```
```
template <class T>
std::ostream& operator<<( std::ostream& os, const gc<T>& x)
{
    // os << .. something useful here ..
    return os;
}
```
```


q:
We are using IIS 6 and ASP.Net, When users make secure page requests using

https://somesite.com/securePage.aspx

the user gets an error:

Error code: ssl error bad cert domain

The certificate was issued to www.somesite.com and indicates that somesite.com uses an invalid security certificate.

I was hoping to be able to catch the request in the Application BeginRequest event but the SSL error occurs before this. In order to invoke the Application BeginRequest event the user needs to click through the certificate error message. Is it possible to redirect in code or does this fix need to occur within IIS?

[A]
In Apache this is usually done with mod_rewrite:
```
```
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
```
```
Google for "rewrite URL IIS", you'll find some equivalents for IIS.


q: i.e. I just want them to be permanently accepted all the time.

[A]
I think you need to get the certificate issued by a "root certificate authority" that the browser will know in advance, e.g. Verisign.
http://www.verisign.co.uk/ssl/ssl-information-center/
There's other suppliers too.  Trail ones available here....
http://www.geotrust.com/
Good description of the issue and what might work best for you depending on your requirements here...
http://www.boutell.com/newfaq/creating/whichcert.html


q:
I'm writing some disposable Haskell scripts to solve some of the Project Euler problems. I don't really want to have to compile them because of the number of changes I'm constantly having to make, but in a few cases I've found that I've run out of stack space.

The documentation for runhaskell says that the following syntax should increase the stack space:

runhaskell +RTS -K5M -RTS Script.hs

This never, ever works (in any permutation I've tried). The stack size always remains 8,388,608. This is maddening, and I haven't found much help on Google.

Any suggestions? What am I doing wrong?

[A]
I'm guessing you're using GHC.  Chapter 4 of the User's Guide of the newly released 6.10.1 says:
The only runghc flag currently is -f
  /path/to/ghc, which tells runghc which
  GHC to use to run the program.
I don't see a bug logged at
http://hackage.haskell.org/trac/ghc
.  Seems pretty lame to me.  I'd suggest asking on irc #ghc, or the cvs-ghc mailing list.
Of the other Haskell compilers/interpreters, only nhc98 seems allow you to set the max stack size.  Depending on your OS, nhc98 could be an option.


q: Is there a trade off in respect to performance, trade off in respect to memory consumption?

[A]
Yes, absolutely a DataTable consumes more memory than a List.
The DataTable class has lots of objects for column definitions, the table info (name, etc), collections of row objects, the "item arrays" for each row (which is basically all the List would have), etc.
EDIT: Also, List is more performant for adding items, itterating through, etc. (reflect the code for "Add" for generic lists, and for data tables to see more detail).


q:
I recently downloaded PLT Scheme and DrScheme. When I open DrScheme, I am told to choose a language. However, I'm not familiar with any of my options, and the help guides don't really break it down to help me easily choose which choice.

So, first - is DrScheme and PLT Scheme really the tools I need to learn Lisp and/or Scheme? If so, what are the different languages and which one(s) should I be using?

[A]
Standard (R5RS) is the actual thing so that would be your best bet
i learnt it from
http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/
used MIT Scheme while doing that
but otherwise i find plt a lot nicer to work with


q:
another request sorry..
Right now I am reading the tokens in one by one and it works, but I want to know when there is a new line..

if my file contains

Hey Bob
Now

should give me

Hey
Bob
[NEW LINE]
NOW

Is there a way to do this without using getline?

[A]
Yes the operator>> when used with string read 'white space' separated words. A 'White space' includes space tab and new line characters.
If you want to read a line at a time use std::getline()
The line can then be tokenized separately with a string stream.
```
```
std::string   line;
while(std::getline(std::cin,line))
{

    // If you then want to tokenize the line use a string stream:

    std::stringstream lineStream(line);
    std::string token;
    while(lineStream >> token)
    {
        std::cout << "Token(" << token << ")\n";
    }

    std::cout << "New Line Detected\n";
}
```
```
Small addition:
Without using getline()
So you really want to be able to detect a newline. This means that newline becomes another type of token. So lets assume that you have words separated by 'white spaces' as tokens and newline as its own token.
Then you can create a Token type.
Then all you have to do is write the stream operators for a token:
```
```
#include <iostream>
#include <fstream>

class Token
{
    private:
        friend std::ostream& operator<<(std::ostream&,Token const&);
        friend std::istream& operator>>(std::istream&,Token&);
        std::string     value;
};
std::istream& operator>>(std::istream& str,Token& data)
{
    // Check to make sure the stream is OK.
    if (!str)
    {   return str;
    }

    char    x;
    // Drop leading space
    do
    {
        x = str.get();
    }
    while(str && isspace(x) && (x != '\n'));

    // If the stream is done. exit now.
    if (!str)
    {
        return str;
    }

    // We have skipped all white space up to the
    // start of the first token. We can now modify data.
    data.value  ="";

    // If the token is a '\n' We are finished.
    if (x == '\n')
    {   data.value  = "\n";
        return str;
    }

    // Otherwise read the next token in.
    str.unget();
    str >> data.value;

    return str;
}
std::ostream& operator<<(std::ostream& str,Token const& data)
{
    return str << data.value;
}

int main()
{
    std::ifstream   f("PLOP");
    Token   x;

    while(f >> x)
    {
        std::cout << "Token(" << x << ")\n";
    }
}
```
```


q:
I currently have 2 domain names that I want to setup different websites for. I am currently looking at using some free hosting that works well for my current needs but doesn't give me any way to point "mydomain.com" to the actual site. Instead I have to give users a longer, harder to remember url.

My proposed solution is to point my domains to my home ip and host a small ASP.NET app through IIS consisting of a redirect page that simply redirects to the appropriate site. Is there a way in ASP.NET to recognize which domain url was requested in order to know where to redirect the page to?

[A]
From asp.net code you can access the host from the request object:
```
```
if(Request.Url.Authority == "www.site1.com")
    Response.Redirect(...);
```
```
If you have access to the IIS server you can also set up two sites with different binding host names and have each redirect as you like.


q: How do you split a string into tokens in C++?

[A] It depends on how complex the token delimiter is and if there are more than one.  For easy problems, just use std::istringstream and std::getline.  For more complex tasks or if you want to iterate the tokens in an STL-compliant way, use Boost's Tokenizer.  Another possibility (although messier than either of these two) is to set up a while loop that calls std::string::find and updates the position of the last found token to be the start point for searching for the next.  But this is probably the most bug-prone of the 3 options.


q: By this, I don't mean PC-based development environments (like Visual Studio) for developing and deploying Windows Mobile applications.  Rather, I mean an IDE that runs on Windows Mobile devices and lets you write and test code there.

[A]
I know of no such thing, and I doubt it would be a good idea; as such I don't think any such thing exists.
It would be a cool project for you to write though, I can't imagine it would be that hard. You would just need a compiler that runs on the WM platform.
Wait; I found this:
http://www.freewarepocketpc.net/ppc-download-c-ide-mobile-v9-0.html


q:
I want to display the "infinity" symbol using

CGContextSelectFont(context, "HelveticaNeue", textSize, kCGEncodingMacRoman);
CGContextShowTextAtPoint(context, myCenter.x, myCenter.y + textHeight, [sName     cStringUsingEncoding:NSMacOSRomanStringEncoding], [sName length]);

It is displayed as a square box, or a circle. I have found out this symbol is in decimal 176 and 221E in Hexadecimal format. I am using Helvetica as my font, and have tried others with no luck. Is this a problem with the encoding I am using?

[A]
It turns out that CGContextSelectFont only supports MacRoman encoding, which is basically has only a small set of characters. In order to display Unicode characters in a string, you have to use CGSetFont or the Cocoa drawing system. CGSetFont requires that you use Cocoa anyway to map characters to glyphs and then draw the glyphs using CGContextShowGlyphsAtPoint. I recommend that you look into other ways to draw these strings if you really need to display Unicode characters.
This code basically will display the infinity symbol:
```
```
- (void)drawRect:(CGRect)rect {
    unichar inf = 0x221E; // infinity symbol
    NSString* sName = [[NSString alloc] initWithCharacters:&inf length:1];
    UIFont* font = [UIFont fontWithName:@"Helvetica" size:32.0];
    [sName drawInRect:CGRectMake(20, 20, 40, 40)
             withFont:font];
    [sName release];
}
```
```
Also note that on the iPhone (and on the Mac) Helvetica Neue actually does not exist... its name just maps back to standard Helvetica. See the table at
http://daringfireball.net/misc/2007/07/iphone-osx-fonts
for more information on available fonts on the iPhone.


q: What are the things that Medium Trust stops you from doing?  For example, I've already learned that Medium Trust stops you from using System.IO.Path.GetTempPath().   What other things like that?

[A]
Who can be sure? That's why you should develop with a trust level of medium set in your web.config.
```
```
<trust level="Full|High|Medium|Low|Minimal" />
```
```


q: I can't seem to get a scrollbar to work in an inner stack/flow.  Does anyone know how to?

[A] I'm not sure what exactly you mean by "an inner stack/flow", but we use iframes for our subpane windows which has a scrolling attribute you can set. Otherwise you can use a javascript framework like YUI to get subpane windows that can allow scrolling capabilities.


q:
I'm pretty sure this is a simple question in regards to formatting but here's what I want to accomplish:

I want to output data onto the screen using cout.  I want to output this in the form of a table format.  What I mean by this is the columns and rows should be properly aligned.  Example:

Test                 1
Test2                2
Iamlongverylongblah  2
Etc                  1

I am only concerned with the individual line so my line to output now (not working) is

cout << var1 << "\t\t" << var2 << endl;

Which gives me something like:

Test                 1
Test2                  2
Iamlongverylongblah         2
Etc                  1

[A]
I advise using
Boost Format
. Use something like this:
```
```
cout << format("%|1$30| %2%") % var1 % var2;
```
```


q:
I'm using a RichTextBox in WinForms 3.5 and I found that when I programmatically edit the contained text, those changes are no longer available to the built in undo functionality.

Is there a way to make it so these changes are available for undo/redo?

[A]
Here's just some code I decided to mess around with:
```
```
string buffer = String.Empty;
        string buffer2 = String.Empty;
        public Form3()
        {
            InitializeComponent();
            this.richTextBox1.KeyDown += new KeyEventHandler(richTextBox1_KeyDown);
            this.richTextBox1.TextChanged += new EventHandler(richTextBox1_TextChanged);
        }

        void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            buffer2 = buffer;
            buffer = richTextBox1.Text;
        }

        void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.Z)
            {
                this.richTextBox1.Text = buffer2;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "Changed";
        }
```
```
It's basically me writing my own Undo feature. All I'm doing is storing the old value in one buffer variable, and the new value in a second buffer variable. Every time the text changes, these values get update. Then, if the user hits "CTRL-Z" it replaces the text with the old value. Hack? A little. But, it works for the most part.


q:
Something is eluding me ... it seems obvious, but I can't quite figure it out.

I want to add/remove a couple of HTML controls to a page (plain old html) when a user changes value of a dropdown list.  An example is to add or remove a "number of guests in this room" textbox for each (of a number) of rooms requested ...

So if a user selects:

1 room, there is one text box

2 rooms, there are two text boxes

3 rooms, three text boxes

back to 2 rooms, two text boxes

and so on ...

[A]
for your select list of rooms, add an onchange event handler that will show/hide the text boses.
```
```

<select name="rooms" onchange="adjustTexts(this);">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</select>

  Room 1:<input type="text" name="room1text"/>

  Room 2:<input type="text" name="room2text"/>

  Room 3:<input type="text" name="room3text"/>

  Room 4:<input type="text" name="room4text"/>

```
```


q:
I am working on a form, which I would like to validation features like This. Should this all be done on clientside? or server side? I am aware of using some of MS ajax controld, however, at what point do I display the message at the top?

I hope I explained myself.

[A]
You
should
validate at both ends.
Client side to make sure feedback is immediate so users can complete it fast (a bonus for them) and you save server resources (bonus for you).
Server side to make sure that any user-agents not using JS can check the incoming data. This is essential to stop malicious/corrupt data entering your system.
If you were only going to do one, make it server side, but there are considerable benefits to the user by implementing a dual-system.


q: Where would the physical files be?

[A]
It depends on the OS and whether or not roaming user profiles are enabled.
For example, on XP, with non-roaming profiles, the location is
```
```
<SYSTEMDRIVE>\Documents and Settings\<user>\Local Settings\Application Data\Microsoft\IsolatedStorage
```
```
On Vista with roaming profile storage,
```
```
<SYSTEMDRIVE>\Users\<user>\AppData\Roaming\Microsoft\IsolatedStorage
```
```
See an
Introduction to Isolated Storage
for more info.


q:
I know in a lot of asynchronous communication, the packet begins starts with a start bit.

But a start bit is just a 1 or 0.  How do you differentiate a start bit from the end bit from the last packet?

Ex.
If I choose my start bit to be 0 and my end bit to be 1.
and I receive 0 (data stream A) 1 0 (data stream B) 1,
what's there to stop me from assuming there is a data stream C which contains the same contents of "(data stream A) 1 0 (data stream B)" ?

Isn't it more convenient to have a start BYTE and then check the data stream for that combination of bits? That will reduce the possibility of a confusing between the start/end bit.

[A]
Great question!  Most asynchronous communication also specifies a
stop
bit, which is the complement of the start bit, ensuring each new symbol begins with a stop-to-start transition.
Example:  let's transmit the characters
```
ABC
```
, which are ASCII 65, 66, and 67:
```
```
A = 65 = 0x41 = 0100 0001
B = 66 = 0x42 = 0100 0010
C = 67 = 0x43 = 0100 0011
```
```
Let's also assume (arbitrarily) that the start bit is
```
0
```
and the stop bit is
```
1
```
, and the data is transmitted from MSB to LSB.  The transmitter will be in the stop (
```
1
```
) state when no data is transmitted.  So the receiver might see this:
```
```
Data:   ....1111 0010000011 111 0010000101 0010000111 11111....
         (quiet) ^   A    $     ^    B   $ ^    C   $ (quiet)
```
```
With apologies for the ASCII graphics, the data consists of a series of stop (
```
1
```
) bits while the channel is idle.  When the transmitter is ready to send a character, it sends a start (
```
0
```
) bit (marked with
```
^
```
), followed by the character code, and ending with a stop (
```
1
```
) bit (marked with
```
$
```
).  It continues to send stop bits until the next character is transmitted, beginning with another start bit.
The reason we use start
bits
instead of
bytes
is efficiency.  The scheme above requires 10 bits (1
start
+ 8
data
+ 1
stop
) to transmit 8 bits of data, resulting in an
overhead
of (10 - 8) / 8 = 1/4 = 25%.  If we used start and stop
bytes
, we'd need to transmit 3 bytes for each byte of data, which would be an overhead of (3 - 1)/1 = 2 = 200%.  If the start, data, and stop bytes were each 8 bits, we'd have to transmit 24 bits instead of 10 for each character, so it would take almost 2 1/2 times as long to send the data!


q:
I know how to include files that are in folders further down the heirachy but I have trouble finding my way back up.
I decided to go with the set_include_path to default all further includes relative to a path 2 levels up but don't have the slightest clue how to write it out.

Is there a guide somewhere that details path referencing for PHP?

[A]
it's probably easier to just use an absolute path to reference:
```
```
set_include_path('/path/to/files');
```
```
this way you have a reference point for all your future includes. includes are handled relative to the point they were called, which can cause a bit of confusion in certain scenarios.
as an example, given a sample folder structure (
```
/home/files
```
):
```
```
index.php
test/
  test.php
test2/
  test2.php

// /home/files/index.php
include('test/test.php');

// /home/files/test/test.php
include('../test2/test2.php');
```
```
if you call index.php, it will try to include the following files:
```
```
/home/files/test/test.php // expected
/home/test2/test2.php // maybe not expected
```
```
which may not be what you expect. calling test.php will call
```
/home/files/test2/test.php
```
as expected.
the conclusion being, the includes will be relative to the original calling point. to clarify, this affects
```
set_include_path()
```
if it is relative as well. consider the following (using the same directory structure):
```
```
<?php
// location: /home/files/index.php
   set_include_path('../'); // our include path is now /home/

   include('files/test/test.php'); // try to include /home/files/test/test.php
   include('test2/test2.php'); // try to include /home/test2/test2.php
   include('../test3.php'); // try to include /test3.php
?>
```
```


q:
What is the difference between a Snapshot Repository and Release Repository?

This is with reference to setting up Repositories (like Artifactory, Nexus etc)

[A] Release repositories hold releases and Snapshot repositories hold snapshots. In maven a snapshot is defined as an artifact with a version ending in -SNAPSHOT. When deployed, the snapshot is turned into a timestamp. By definition, snapshots are mutable, releases are immutable. This is why Nexus makes you store them separately because usually you don't care if you lose snapshots, but you will care if you lose releases. It makes snapshot cleanup much easier to deal with that way.


q:
I'm starting a web project that likely should be fine with SQLite.  I have SQLObject on top of it, but thinking long term here -- if this project should require a more robust (e.g. able to handle high traffic), I will need to have a transition plan ready.  My questions:

How easy is it to transition from one DB (SQLite) to another (MySQL or Firebird or PostGre) under SQLObject?

Does SQLObject provide any tools to make such a transition easier?  Is it simply take the objects I've defined and call createTable?

What about having multiple SQLite databases instead?  E.g. one per visitor group?  Does SQLObject provide a mechanism for handling this scenario and if so, what is the mechanism to use?

Thanks,
Sean

[A]
I'm not sure I understand the question.
The
SQLObject documentation
lists six kinds of connections available.  Further, the database connection (or scheme) is specified in a connection string.  Changing database connections from SQLite to MySQL is trivial.  Just change the connection string.
The
documentation
lists the different kinds of schemes that are supported.


q:
If I have a char which holds a hex value such has 0x53, (S), how can I display this as "S"?

Code:

char test = 0x53;
cout << test << endl;

Thanks!

[A]
There's no such thing as a variable that stores a hex value, or a decimal or octal value. Hex, octal, and decimal are just different ways of representing numbers to the compiler. The compiled code will represent everything in binary.
These statements all have the
exact
same effect (assuming the charset is ASCII):
```
```
test = 0x53; // hex
test = 'S';  // literal constant
test = 83;   // decimal
test = 0123; // octal
```
```
So print the character the same way you would with any character, no matter how you assign it a value.


q:
While developing products, we often need to create proprietary tools to test some of their unique features or diagnose problems.  In fact the tools can be at lest as interesting as the products themselves, and some of our internal groups have asked for copies of them.

So, aside from the obvious business-driven rules (e.g. don't retrieve sensitive data), what do you differently when you build personal or internal tools, as opposed to for-sale products, and why?

What's more (or less) important to you in internal tools, and do you consider overall value to the company when you build them?

Thanks for your thoughts!

[A]
From an engineering perspective, I wouldn't do anything differently:
Both internal and for-sale tools need to be well-written and well-documented
Both need to be created given a set of requirements, deadlines, budgetary restraints, etc.
Both need to be tested or validated
The one big difference I see would apply to the for-sale products as opposed to the internal tools:
for-sale products need marketing, support, etc
that internal tools can do without.
Additionally, since internal tools will be used in a somewhat more controlled environment, they don't need to be tested against different computer systems, Internet browsers, etc.


q:
I'm trying to automate some stuff in MS Excel. When I try to set the Calculation property I get the following error message: 'Unable to set the Calculation property of the Application class'

I believe this property should be settable.

Any advice appreciated!

[A]
Make sure you are setting it to a proper value.
```
```
Application.Calculation = xlCalculationManual
```
```
or one of the following values:
xlCalculationAutomatic: Excel controls recalculation.
xlCalculationManual: Calculation is done when the user requests it.
xlCalculationSemiautomatic: Excel controls recalculation but ignores changes in tables.


q:
Using IMDbPy it is painfully easy to access movies from the IMDB site:

import imdb

access = imdb.IMDb()
movie = access.get_movie(3242) # random ID

print "title: %s year: %s" % (movie['title'], movie['year'])

However I see no way to get the picture or thumbnail of the movie cover. Suggestions?

[A]
Note:
Not every movie has a cover url. (The random ID in your example doesn't.)
Make sure you're using an up-to-date version of IMDbPy. (IMDb changes, and IMDbPy with it.)
...
```
```
import imdb

access = imdb.IMDb()
movie = access.get_movie(1132626)

print "title: %s year: %s" % (movie['title'], movie['year'])
print "Cover url: %s" % movie['cover url']
```
```
If for some reason you can't use the above, you can always use something like BeautifulSoup to get the cover url.
```
```
from BeautifulSoup import BeautifulSoup
import imdb

access = imdb.IMDb()
movie = access.get_movie(1132626)

page = urllib2.urlopen(access.get_imdbURL(movie))
soup = BeautifulSoup(page)
cover_div = soup.find(attrs={"class" : "photo"})
cover_url = (photo_div.find('img'))['src']
print "Cover url: %s" % cover_url
```
```


q:
I'm playing around with CodeIgniter; hoping to convert some of my old, ugly PHP into a more maintainable framework. However, I've come across a rather frustrating roadblock - I can't seem to define methods in my views. Any time I try I get a completely blank page, and when I look in the debug log the processing seemed to stop after the view was loaded. Can I define methods within views? If not, why, and what workarounds would you suggest?

Note: The method has to do with formatting output strings.

[A]
I'm not familiar with CodeIgnitor, but it could be including your templates multiple times. Try wrapping your function in a check:
```
```
if (!function_exists('myfunc'))
{
    function myfunc() {}
}
```
```
CodeIgnitor is probably swallowing errors, so you could also try flushing buffers immediately before your function:
```
```
while(ob_end_flush()){}
error_reporting(E_ALL);
ini_set('display_errors', 1);
```
```
In reality though, you should probably make your string formatting code a bit more general. Your template is not really a good place to start adding functions. You'll begin duplicating code, and it defeats the purpose of having templates at all. I'd suggest experimenting with CodeIgnitor's
Helpers
and
Plugins


q:
Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)

static String intToString(int num, int digits) {
    StringBuffer s = new StringBuffer(digits);
    int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1;
    for (int i = 0; i < zeroes; i++) {
        s.append(0);
    }
    return s.append(num).toString();
}

[A]
String.format (
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
)
In your case it will be:
```
```
String formatted = String.format("%03d", num);
```
```
0 - to pad with zeros
3 - to set width to 3