instruction stringlengths 0 30k ⌀ |
|---|
> Should I build a C# pre-processor? Is there one available that does the simple things I want to do?
You can always use the C pre-processor -- C# is close enough, syntax-wise. M4 is also an option. |
A neato trick with groupby is run length encoding in one line:
[(c,len(list(cgen))) for c,cs in groupby(some_string)]
will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.
|
If you are running in Vista, you may find that the elevation is getting in the way. You may need to ensure your task runs as a proper administrator, not as a restricted user. |
The obvious solution to developers familiar to Java is to use the LinkedList class already provided in java.util. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. Enhancements to this implementation include making it a double-linked list, adding methods to insert and delete from the middle or end, and by adding get and sort methods as well.
**Note**: In the example, the Link object doesn't actually contain another Link object - _nextLink_ is actually only a reference to another link.
class Link {
public int data1;
public double data2;
public Link nextLink;
//Link constructor
public Link(int d1, double d2) {
data1 = d1;
data2 = d2;
}
//Print Link data
public void printLink() {
System.out.print("{" + data1 + ", " + data2 + "} ");
}
}
class LinkList {
private Link first;
//LinkList constructor
public LinkList() {
first = null;
}
//Returns true if list is empty
public boolean isEmpty() {
return first == null;
}
//Inserts a new Link at the first of the list
public void insert(int d1, double d2) {
Link link = new Link(d1, d2);
link.nextLink = first;
first = link;
}
//Deletes the link at the first of the list
public Link delete() {
Link temp = first;
first = first.nextLink;
return temp;
}
//Prints list data
public void printList() {
Link currentLink = first;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
class LinkListTest {
public static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1, 1.01);
list.insert(2, 2.02);
list.insert(3, 3.03);
list.insert(4, 4.04);
list.insert(5, 5.05);
list.printList();
while(!list.isEmpty()) {
Link deletedLink = list.delete();
System.out.print("deleted: ");
deletedLink.printLink();
System.out.println("");
}
list.printList();
}
} |
Extending the User model with custom fields in Django |
|authentication|django| |
What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes).
I've already seen a [few][1] [ways][2] to do it, but can't decide on which one is the best.
[1]: http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
[2]: http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/ |
You can also use the GetGenericParameters() method on that type. myNullableObject.GetType().GetGenericParameters()[0] should give you the type of nullable it is (so Guid, Int32, etc.) |
In theory, HTML should be as "semantic" as possible - meaning that every element should indicate something about its content. <h1>s should enclose the most important headline; <p>s should surround paragraphs; <em> should indicate emphasis, etc.
That way the code makes sense when you - or a screen reader, or whatever - look at it. |
In theory, HTML should be as "semantic" as possible - meaning that every element should indicate something about its content. <h1>s should enclose the most important headline; <p>s should surround paragraphs; <em> should indicate emphasis, etc.
That way the code makes sense when you - or a screen reader, or whatever - look at it. This also helps for devices that don't understand all (or any) of your CSS rules. |
* The **Delphi 7 IDE** for Delphi projects
* **VS2005** for .net projects
* **Notepad** for any quick stuff (I know it sucks, but it's quick) |
I agree with @Glenn for a purely nit-picky point of view. The answer is whatever works for you. All this code takes place in 10 lines (if you include the omitted last curly brace). Nobody is going to get lost and the chance of mistyping is pretty slim (not impossible but very slim). On the other hand, if you used the key somewhere else, then DEFINATELY go with the constant.
Personally, I would go off on you about your curly brace style. :) Just kidding! It really is a matter of style. |
IE6 and XML prolog |
|internet-explorer-6|standards| |
With an XML prolog like
<?xml version="1.0" encoding="iso-8859-1"?>
and a Doctype like
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
I can get my page to render as expected. However, in IE7 the same page does not render correctly. (a span inside a div does not align vertically) Articles on the web suggest that XML prolog + doctype will throw IE6 into quirks mode. However the article below seems to suggest otherwise, although it does not mention the version (is it 6 or 7) it applies to
http://blogs.msdn.com/ie/archive/2005/09/15/467901.aspx
The article is dated sep 2005 which makes me believe it applies to IE6
Question: Does XML Prolog + doc type throw IE6 into quirks mode? What about IE7?
Any recommendations on for or against using the prolog + doctype
TIA
|
Cool, thank you Mark, I had forgotten that CreateFile opens things too. I was looking at the volume management API and not seeing how to open things.
Here is a little class that wraps things up. It might also be possible/correct to just pass the SafeFileHandle into a FileStream.
using System;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Win32.SafeHandles;
namespace ReadFromDevice
{
public class DeviceStream : Stream, IDisposable
{
public const short FILE_ATTRIBUTE_NORMAL = 0x80;
public const short INVALID_HANDLE_VALUE = -1;
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
// Use interop to call the CreateFile function.
// For more information about CreateFile,
// see the unmanaged MSDN reference library.
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool ReadFile(
IntPtr hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToRead, // number of bytes to read
ref int lpNumberOfBytesRead, // number of bytes read
IntPtr lpOverlapped
//
// ref OVERLAPPED lpOverlapped // overlapped buffer
);
private SafeFileHandle handleValue = null;
private FileStream _fs = null;
public DeviceStream(string device)
{
Load(device);
}
private void Load(string Path)
{
if (string.IsNullOrEmpty(Path))
{
throw new ArgumentNullException("Path");
}
// Try to open the file.
IntPtr ptr = CreateFile(Path, GENERIC_READ, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
handleValue = new SafeFileHandle(ptr, true);
_fs = new FileStream(handleValue, FileAccess.Read);
// If the handle is invalid,
// get the last Win32 error
// and throw a Win32Exception.
if (handleValue.IsInvalid)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
return;
}
public override long Length
{
get { return -1; }
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <summary>
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and
/// (offset + count - 1) replaced by the bytes read from the current source. </param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream. </param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns></returns>
public override int Read(byte[] buffer, int offset, int count)
{
int BytesRead =0;
var BufBytes = new byte[count];
if (!ReadFile(handleValue.DangerousGetHandle(), BufBytes, count, ref BytesRead, IntPtr.Zero))
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
for (int i = 0; i < BytesRead; i++)
{
buffer[offset + i] = BufBytes[i];
}
return BytesRead;
}
public override int ReadByte()
{
int BytesRead = 0;
var lpBuffer = new byte[1];
if (!ReadFile(
handleValue.DangerousGetHandle(), // handle to file
lpBuffer, // data buffer
1, // number of bytes to read
ref BytesRead, // number of bytes read
IntPtr.Zero
))
{ Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); ;}
return lpBuffer[0];
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override void Close()
{
handleValue.Close();
handleValue.Dispose();
handleValue = null;
base.Close();
}
private bool disposed = false;
new void Dispose()
{
Dispose(true);
base.Dispose();
GC.SuppressFinalize(this);
}
private new void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
if (disposing)
{
if (handleValue != null)
{
_fs.Dispose();
handleValue.Close();
handleValue.Dispose();
handleValue = null;
}
}
// Note disposing has been done.
disposed = true;
}
}
}
}
And an example of using the class
static void Main(string[] args)
{
var reader = new BinaryReader(new DeviceStream(@"\\.\PhysicalDrive3"));
var writer = new BinaryWriter(new FileStream(@"g:\test.dat", FileMode.Create));
var buffer = new byte[MB];
int count;
int loopcount=0;
try{
while((count=reader.Read(buffer,0,MB))>0)
{
writer.Write(buffer,0,count);
System.Console.Write('.');
if(loopcount%100==0)
{
System.Console.WriteLine();
System.Console.WriteLine("100MB written");
writer.Flush();
}
loopcount++;
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
reader.Close();
writer.Flush();
writer.Close();
}
Standard disclaimers apply, this code may be hazardous to your health.
|
While studying for my degree, my dissertation project was the creation of a Java based modular synthesizer, and the University at which I studied saw fit to make my report publicly available:
[A Software Based Modular Synthesiser in Java][1]
[1]: http://www.dcs.shef.ac.uk/intranet/teaching/projects/archive/ug2004/pdf/u1nh.pdf |
Note that you don't want to persist their session, just their identity. You'll create a fresh session for them when they return to your site. Generally you just assign a GUID to the user, write that to their cookie, then use it to look them up when they come back. Don't use their login name or user ID for the token as it could easily be guessed and allow crafty visitors to hijack other users' accounts. |
Make a recursive function that takes the string and an integer offset, and "reads" out an array. That is, have it return an array or string (that it has read) and an integer offset pointing after the array. For example:
s = "[[this, is],[a, nested],[array]]"
yourFunc(s, 1) # returns ['this', 'is'] and 11.
yourFunc(s, 2) # returns 'this' and 6.
Then you can call it with another function that provides an offset of 0, and makes sure that the finishing offset is the length of the string. |
#Java 1.6: recursive, memoized (for subsequent calls)
private static Map<BigInteger, BigInteger> _results = new HashMap()
public static BigInteger factorial(BigInteger n){
if (0 >= n.compareTo(BigInteger.ONE))
return BigInteger.ONE.max(n);
if (_results.containsKey(n))
return _results.get(n);
BigInteger result = factorial(n.subtract(BigInteger.ONE)).multiply(n);
_results.put(n, result);
return result;
} |
I still write WS-*–based services. Somewhat surprisingly, I've had less trouble with them when trying to inter-operate with less capable developers. This is because if I send them a WSDL file, they know how to crank it through their tool and get an API they can call, while being blissfully unaware what is happening under the hood. To give customers a REST-ful service, I have to start talking to them about HTTP and XML, which they really don't understand as well as they think they do, and then I start getting a headache.
In other words, to be successful with REST, both the service provider and consumer have to know what they're doing (and they can keep things simple and come up with a great, non–WS-* solution). With WS-* technologies, it can still succeed even if only one party has a clue.
I think, however, that REST-oriented standards that are much less complicated than current WS standards, will eventually emerge, and when that happens, comparable tools will be available too. |
I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes.
<br/>
**Versioning.** One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers built against the old version of the library. Instead, a new version of the interface with the new members needs to be created, and the library will have to work around or limit access to legacy objects only implementing the original interface.
As a concrete example, the first version of a library might define an interface like so:
public interface INode {
INode Root { get; }
List<INode> GetChildren( );
}
Once the library has released, we cannot modify the interface without breaking current users. Instead, in the next release we would need to define a new interface to add additional functionalty:
public interface IChildNode : INode {
INode Parent { get; }
}
However, only users of the new library will be able to implement the new interface. In order to work with legacy code, we need to adapt the old implementation, which an extension method can handle nicely:
public static class NodeExtensions {
public INode GetParent( this INode node ) {
// If the node implements the new interface, call it directly.
var childNode = node as IChildNode;
if( !object.ReferenceEquals( childNode, null ) )
return childNode.Parent;
// Otherwise, fall back on a default implementation.
return FindParent( node, node.Root );
}
}
Now all users of the new library can treat both legacy and modern implementations identically.
<br/>
**Overloads.** Another area where extension methods can be useful is in providing overloads for interface methods. You might have a method with several parameters to control its action, of which only the first one or two are important in the 90% case. Since C# does not allow setting default values for parameters, users either have to call the fully parameterized method every time, or every implementation must implement the trivial overloads for the core method.
Instead extension methods can be used to provide the trivial overload implementations:
public interface ILongMethod {
public bool LongMethod( string s, double d, int i, object o, ... );
}
...
public static LongMethodExtensions {
public bool LongMethod( this ILongMethod lm, string s, double d ) {
lm.LongMethod( s, d, 0, null );
}
...
}
<br/>
Please note that both of these cases are written in terms of the operations provided by the interfaces, and involve trivial or well-known default implementations. That said, you can only inherit from a class once, and the targeted use of extension methods can provide a valuable way to deal with some of the niceties provided by base classes that interfaces lack :)
|
When making and processing requests with JavaScript, I live and breath [JSON](http://json.org/). It's easy to build on the client side and there are tons of parsers for the server side, so both ends get to use their native tongue as much as possible. |
Is cron sending emails with logs?
If not, pipe the output of cron to a log file.
Make sure to redirect STDERR to the log. |
I would get the SQL result set to return the list in the first place, you can easily just take the first letter of the required item, and a count. The quickest way would be to do a join on a table of 26 characters (less string manipulation that way).
In CF use the count value to ensure that if there is no result you either only display the letter (as standard text) or dont display it at all.
How many rows are you going to be working on as there may be better ways of doing this. For example, storing the first letter of your required link field in a separate column on insert would reduce the overhead when selecting. |
What's the best way to get started with OSGI? |
|osgi|java|spring| |
I'm interested in using [OSGi][1] in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using [Spring Dynamic Modules for OSGi(tm) Service Platforms][2]. I'm looking for a good way to incorporate a little bit of OSGi into an application as a trial. What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module? Has anyone here used this or a similar OSGi technology? Are there any pitfalls?
[1]: http://en.wikipedia.org/wiki/OSGi
[2]: http://www.springframework.org/osgi |
I'm interested in using [OSGi][1] in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using [Spring Dynamic Modules for OSGi(tm) Service Platforms][2]. I'm looking for a good way to incorporate a little bit of OSGi into an application as a trial. What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module? Has anyone here used this or a similar OSGi technology? Are there any pitfalls?
@Nicolas - Thanks, I've seen that one. It's a good tutorial, but I'm looking more for ideas on how to do my first "real" OSGi bundle, as opposed to a Hello World example.
[1]: http://en.wikipedia.org/wiki/OSGi
[2]: http://www.springframework.org/osgi |
|java|spring|osgi| |
What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module?
I'm interested in using [OSGi][1] in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using [Spring Dynamic Modules for OSGi(tm) Service Platforms][2]. I'm looking for a good way to incorporate a little bit of OSGi into an application as a trial. Has anyone here used this or a similar OSGi technology? Are there any pitfalls?
@Nicolas - Thanks, I've seen that one. It's a good tutorial, but I'm looking more for ideas on how to do my first "real" OSGi bundle, as opposed to a Hello World example.
@david - Thanks for the link! Ideally, with a greenfield app, I'd design the whole thing to be dynamic. What I'm looking for right now, though, is to introduce it in a small piece of an existing application. Assuming I can pick any piece of the app, what are some factors to consider that would make that piece better or worse as an OSGi guinea pig?
[1]: http://en.wikipedia.org/wiki/OSGi
[2]: http://www.springframework.org/osgi |
|c#|string| |
In C# what is the difference between String and string? (note the case)
Also, what are the guidelines for the use of each? |
Is your scripting language bytecode generating? Does it generate debug metadata? If so, bytecode instrumentation is probably the way to go. In fact existing tools like will probably work; perhaps with minimal modification (the typical problem is the tools are written to work with Java and assume com.foo.Bar.class corresponds to com/foo/Bar.java. Unwinding that assumption can be tedious.) [EMMA][1] is a ClassLoader that does byte-code re-writing for code-coverage collection in Java. The coding style is a little funky, but I recommend reading the source for some ideas.
If your scripting language is interpreted then you will need something higher-level (source level) that hooks into the interpreter.
[1]: http://emma.sourceforge.net/ |
If you are interested in DSLs, [Jeff Moser][1] has written some great articles about them (and the 'meta' frame of mind you need) [here,][2] [here,][3] and [here][4] on his blog.
[1]: http://www.moserware.com/
[2]: http://www.moserware.com/2008/04/towards-moores-law-software-part-3-of-3.html
[3]: http://www.moserware.com/2008/06/ometa-who-what-when-where-why.html
[4]: http://www.moserware.com/2008/07/building-object-oriented-parasitic.html |
'System.String' is THE .net string class - in C# 'string' is an alias for System.String - so in use they are the same.
As for guidelines I wouldn't get too bogged down and just use whichever you feel like - there are more important things in life and the code is going to be the same anyway.
If you find yourselves building systems where it is necessary to specify the size of the integers you are using and so tend to use Int16, Int32, UInt16, UInt32 etc. then it might look more natural to use String - and when moving around between different .net languages it might make things more understandable - otherwise I would use string and int. |
Following up on [svrist's answer,][1] depending on your shell, the 2>&1 should go *after* > /dev/null or you will still see the output from stderr.
The following will silence both stdout and stderr:
59 23 * * * /usr/sbin/myscript > /dev/null 2>&1
The following silences stdout, but stderr will still appear (via stdout):
59 23 * * * /usr/sbin/myscript 2>&1 > /dev/null
[The Advanced Bash Scripting Guide's chapter on IO redirection][2] is a good reference--search for 2>&1 to see a couple of examples.
[1]: http://stackoverflow.com/questions/3136/help-with-cronjobs#3145
[2]: http://tldp.org/LDP/abs/html/io-redirection.html |
Lower case string is an alias for System.String.
They are the same in C#.
There's a debate over whether you should use the System types (System.Int32, System.String, etc.) types or the C# aliases (int, string, etc). I personally believe you should use the C# aliases, but that's just my personal preference. |
you will with the above response recieve email with any text written to stderr. Some people redirect that away too, and make sure that the script writes a log instead.
> ... 2>&1 ... |
you will with the above response recieve email with any text written to stderr. Some people redirect that away too, and make sure that the script writes a log instead.
... 2>&1 .... |
You have an ascending list of numbers, what is the most efficient algorithm you can think of to get the list of sums of every two numbers in that list. Duplicates in the resulting list are irrelevant, you can remove them or avoid them if you like. |
|language-agnostic|algorithm| |
You have an ascending list of numbers, what is the most efficient algorithm you can think of to get the ascending list of sums of every two numbers in that list. Duplicates in the resulting list are irrelevant, you can remove them or avoid them if you like.
To be clear, I'm interested in the algorithm. Feel free to post code in any language and paradigm that you like. |
I've seen it done in a kind of iffy, but pretty reliable way. Basically, an element is set to use a specific font and a string is set to that element. If the font set for the element does not exist, it takes the font of the parent element. So, what they do is measure the width of the rendered string. If it matches what they expected for the desired font as opposed to the derived font, it's present.
Here's where it came from:
[ajaxian.com][1]
[1]: http://ajaxian.com/archives/javascriptcss-font-detector |
How do I most elegantly express left join with aggregate SQL as LINQ query |
|linq|c#| |
SQL:
select
u.id,
u.name,
isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault
from universe u
left join history h
on u.id=h.id
and h.dateCol<GETDATE()-1
group by u.Id, u.name |
|c#|linq| |
A solution (albeit one that defers handling of the null value to the code) could be
DateTime yesterday = DateTime.Now.Date.AddDays(-1);
var collection=
from u in db.Universe
select new
{
u.id,
u.name,
MaxDate =(DateTime?)
(
from h in db.History
where u.SecurityId == h.SecurityId
&& h.dateCol < yesterday
select h.dateCol
).Max()
}; |
A solution (albeit one that defers handling of the null value to the code) could be:
DateTime yesterday = DateTime.Now.Date.AddDays(-1);
var collection=
from u in db.Universe
select new
{
u.id,
u.name,
MaxDate =(DateTime?)
(
from h in db.History
where u.Id == h.Id
&& h.dateCol < yesterday
select h.dateCol
).Max()
};
This does not produce exactly the same SQL, but does provide the same logical result. Translating "complex" SQL queries to LINQ is not allways straightforward. |
You're looking for Sandcastle
Project Page: <http://www.codeplex.com/Sandcastle/Release/ProjectReleases.aspx>
Blog: <http://blogs.msdn.com/sandcastle/default.aspx>
NDoc (<http://ndoc.sourceforge.net/>) used to be the tool of choice, but support has all but stopped. |
Have a look at [Sandcastle][1], which does exactly that.
[1]: http://blogs.msdn.com/sandcastle/ |
The obvious solution to developers familiar to Java is to use the **LinkedList** class already provided in **java.util**. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. Enhancements to this implementation include making it a double-linked list, adding methods to insert and delete from the middle or end, and by adding get and sort methods as well.
**Note**: In the example, the Link object doesn't actually contain another Link object - _nextLink_ is actually only a reference to another link.
class Link {
public int data1;
public double data2;
public Link nextLink;
//Link constructor
public Link(int d1, double d2) {
data1 = d1;
data2 = d2;
}
//Print Link data
public void printLink() {
System.out.print("{" + data1 + ", " + data2 + "} ");
}
}
class LinkList {
private Link first;
//LinkList constructor
public LinkList() {
first = null;
}
//Returns true if list is empty
public boolean isEmpty() {
return first == null;
}
//Inserts a new Link at the first of the list
public void insert(int d1, double d2) {
Link link = new Link(d1, d2);
link.nextLink = first;
first = link;
}
//Deletes the link at the first of the list
public Link delete() {
Link temp = first;
first = first.nextLink;
return temp;
}
//Prints list data
public void printList() {
Link currentLink = first;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
class LinkListTest {
public static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1, 1.01);
list.insert(2, 2.02);
list.insert(3, 3.03);
list.insert(4, 4.04);
list.insert(5, 5.05);
list.printList();
while(!list.isEmpty()) {
Link deletedLink = list.delete();
System.out.print("deleted: ");
deletedLink.printLink();
System.out.println("");
}
list.printList();
}
} |
The obvious solution to developers familiar to Java is to use the **LinkedList** class already provided in **java.util**. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. **Enhancements** to this implementation include making it a **double-linked list**, adding methods to **insert** and **delete** from the middle or end, and by adding **get** and **sort** methods as well.
**Note**: In the example, the Link object doesn't actually contain another Link object - _nextLink_ is actually only a reference to another link.
class Link {
public int data1;
public double data2;
public Link nextLink;
//Link constructor
public Link(int d1, double d2) {
data1 = d1;
data2 = d2;
}
//Print Link data
public void printLink() {
System.out.print("{" + data1 + ", " + data2 + "} ");
}
}
class LinkList {
private Link first;
//LinkList constructor
public LinkList() {
first = null;
}
//Returns true if list is empty
public boolean isEmpty() {
return first == null;
}
//Inserts a new Link at the first of the list
public void insert(int d1, double d2) {
Link link = new Link(d1, d2);
link.nextLink = first;
first = link;
}
//Deletes the link at the first of the list
public Link delete() {
Link temp = first;
first = first.nextLink;
return temp;
}
//Prints list data
public void printList() {
Link currentLink = first;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
class LinkListTest {
public static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1, 1.01);
list.insert(2, 2.02);
list.insert(3, 3.03);
list.insert(4, 4.04);
list.insert(5, 5.05);
list.printList();
while(!list.isEmpty()) {
Link deletedLink = list.delete();
System.out.print("deleted: ");
deletedLink.printLink();
System.out.println("");
}
list.printList();
}
} |
This seems like a perfect scenario for using JSON as a serialization format for the server. If you study a few [examples][1] it is not too difficult to understand. E.g.
[1]: http://www.json.org/example.html |
The unit tester for VS2008 is only for .NET code as far as I know.
I used CppUnit on Vs2005 and found it to be pretty good.
As far as I remember, the setup was relatively painless, just make sure that in your testing projects the linker (Linker->Input->Additional Dependencies) includes cppunitd.lib.
Then, `#include <cppunit/extensions/HelperMacros.h>` in your header
You can then follow the steps in <http://cppunit.sourceforge.net/doc/1.11.6/cppunit_cookbook.html> to get your test class working. |
Best practice on this dictates that if you are not planning to use the stored data for anything other than recreating the form then the best method is to send it back in some sort of native format (As mentioned above) With this then you can just load the data back in and requires the least processing of any method. |
There's a lot of people who will push JSON. It's a lot lighter weight than XML. Personally, I find XML to be a little more standard though. You'll have trouble finding a server side technology that doesn't support XML. And Javascript supports it just fine also. You could also go a completely different route. Since you'll only be sending information back when the form design is complete, you could do it with a form submit, for a bunch of hidden fields. Create your hidden fields using javascript and set the values as needed. This would probably be the best solution if didn't want to deal with JSON/XML at all. |
My RSS feeds have served me well- I found that Javascript roguelike!
It's called [The Tombs of Asciiroth](http://www.icculus.org/asciiroth/). |
when you throw the error your error handler can then email the user, or better if the list is massive, add the error state to the workflow item - i think this is default functionality though as the error would be mentioned there.
http://www.sharepointsecurity.com/blog/sharepoint/sharepoint-2007-development/fault-handling-in-sharepoint-workflows/
|
To generate the navigation bar, you could do something like this:
<cfoutput>
<cfloop from="#asc('A')#" to="#asc('Z')#" index="i">
<a href="###chr(i)#">#chr(i)#</a>
<cfif asc('Z') neq i>|</cfif>
</cfloop>
</cfoutput>
(CFLOOP doesn't work on characters, so you have to convert to ascii codes and back.)
----------
To display the items in your query you could do something like this.
<cfset currentLetter = "">
<cfoutput query="data">
<cfif currentLetter neq left(data.name, 1)>
<h3><a name="#ucase(left(data.name, 1))#">#ucase(left(data.name, 1))#</a></h3>
</cfif>
<cfset currentLetter = left(data.name, 1)>
#name#<br>
</cfoutput>
|
The Red Gate product is good...but not perfect.
I found that I did better when I wrote my own tools to generate the data. I use it when I want to generate say Customers...but it's not great if you wanted to simulate randomness that customers might engage in like creating orders...some with one item some with multiple items.
Homegrown tools will provide the most 'realistic' data I think. |
How do I make an HTML page print in landscape when the user selects 'print'? |
|html|print|landscape|portrait| |
We generate web pages that should always be printed in landscape mode. Web browser print dialogs default to portrait, so for every print job the user has to manually select landscape. It's minor, but would be nice for the user if we can remove this unnecessary step.
Thanks in advance to all respondents. |
|html|printing|landscape|portrait| |
In response to [Christian Lescuyer](#37147)'s post, you also need to enable the "svn:keywords" property on the file with that line in it. Subversion won't bother looking in your files for keywords like $Revision$ unless that property is set.
Also, if using PHP like in his example, you may want to put $Revision$ inside a single-quoted string instead of a double quoted string to prevent PHP from trying to parse $Revision as a PHP variable and throwing a warning. :) |
Consider taking a look at an aspect-oriented solution like [PostSharp][1], which injects code after the fact based on custom attributes. It's the opposite of a precompiler but can give you the sort of functionality you're looking for (PropertyChanged notifications etc).
[1]: http://www.postsharp.org/ |
What is the best way to get OS specific information in Java? |
|java| |
Specifically getting on Windows the "..\Documents & Settings/All Users,
the current users My Documents dirctory,
and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. |
1. Specifically getting on Windows the "..\Documents & Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. **(Now I need the answer to this)**
2. the current users My Documents dirctory **(okay this has been answered)**
and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. |
While not an instant answer for you, I found the book [Learning WCF][1] very useful; in it there's a small section on versioning (which is similar to Craig McMurtry's advice posted by Espo). If you're looking for a general intro book, it's very good. Her website has lots of good stuff too: [Das Blonde][2]
[1]: http://www.amazon.com/Learning-WCF-Hands-Michele-Bustamante/dp/0596101627
[2]: http://www.dasblonde.net/ |
While not an instant answer for you, I found the book [Learning WCF][1] very useful; in it there's a small section on versioning (which is similar to Craig McMurtry's advice posted by Espo). If you're looking for a general intro book, it's very good. Her website has lots of good stuff too: [Das Blonde][2]
**Edit:**
No sure why her site isn't responding; it's been a while since I've visited, so maybe she shut it down. No sure.
[1]: http://www.amazon.com/Learning-WCF-Hands-Michele-Bustamante/dp/0596101627
[2]: http://www.dasblonde.net/ |
One other way to do it is to use:
String.valueOf(myInt);
This method is overloaded for every primitive type and `Object`. This way you don't even have to think about the type you're using. Implementations of the method will call the appropriate method of the given type for you, e.g. `Integer.toString(myInt)`.
See <http://java.sun.com/javase/6/docs/api/java/lang/String.html>. |
You can use ImageMagick's convert utility for this, see some examples in http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html |
I think [Modern Compiler Implementation in ML][1] is the best introductory compiler writing text. There's a [Java version][2] and a [C version][3] too, either of which might be more accessible given your languages background. The book packs a lot of useful basic material (scanning and parsing, semantic analysis, activation records, instruction selection, RISC and x86 native code generation) and various "advanced" topics (compiling OO and functional languages, polymorphism, garbage collection, optimization and single static assignment form) into relatively little space (~500 pages).
I prefer Modern Compiler Implementation to the Dragon book because Modern Compiler implementation surveys less of the field--instead it has really solid coverage of all the topics you would need to write a serious, decent compiler. After you work through this book you'll be ready to tackle research papers directly for more depth if you need it.
I must confess I have a serious soft spot for Niklaus Wirth's [Compiler Construction.][4] It is [available online][5] as a PDF. I find Wirth's programming aesthetic simply beautiful, however some people find his style too minimal (for example Wirth favors recursive descent parsers, but most CS courses focus on parser generator tools; Wirth's language designs are fairly conservative.) Compiler Construction is a very succinct distillation of Wirth's basic ideas, so whether you like his style or not or not, I highly recommend reading this book.
[1]: http://www.amazon.com/gp/product/0521607647?ie=UTF8&tag=dcooneycom-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0521607647 "Modern Compiler Implementation in ML"
[2]: http://www.amazon.com/gp/product/052182060X?ie=UTF8&tag=dcooneycom-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=052182060X "Modern Compiler Implementation in Java"
[3]: http://www.amazon.com/gp/product/0521607655?ie=UTF8&tag=dcooneycom-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0521607655 "Modern Compiler Implementation in C"
[4]: http://www.amazon.com/gp/product/0201403536?ie=UTF8&tag=dcooneycom-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0201403536 "Compiler Construction"
[5]: http://www-old.oberon.ethz.ch/WirthPubl/CBEAll.pdf "Compiler Construction (PDF)" |
Regarding security, **you cannot trust what comes from the client**:
- The visitor can see all your code (HTML and Javascript, not PHP) and try stuff
- The visitor may not even use a browser; it's trivially easy to send a request with a script
This means hiding the buttons is good User Interface design (because you can't use them if you are not logged in). But it's not a security feature. The security feature is checking, on the server, that the visitor is logged in before each action that requires it.
If you don't intend to show the buttons, it's not useful to send the HTML and images to the browser and then hide them with Javascript. I would check with PHP. |
You should look at the `<Framework/FrameworkErrors.h>` header for whatever framework the method you're using that's returning an error comes from.
For example, an `NSError` in the Cocoa domain that you get from a method in the Foundation framework will have its `code` property described in the `<Foundation/FoundationErrors.h>` header. Similarly with AppKit and `<AppKit/AppKitErrors.h>` and Core Data and `<CoreData/CoreDataErrors.h>`.
Also, if you print the description of the `NSError` in the debugger, it should include not only the error domain and code, but also the name of the actual error code constant so you can look it up in the API reference. |
What's a good algorithm to generate a maze? |
|algorithm|maze| |
Say you want a simple maze on an N by M grid, with one path through, and a good number of dead ends, but that looks "right" (i.e. like someone made it by hand without too many little tiny dead ends and all that). Is there a known way to do this? |
> It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).
What feature of the system's built-in thread pools make them unsuitable for your task? If you want to target XP and 2003 you can't use the new shiny Vista/2008 pools, but you can still use QueueUserWorkItem and friends. |
Strangely enough, by slightly changing the 'canonical' rules and starting from a random configuration, [Conway's Game of Life][1] (I don't know why my Wikipedia link is not working!) seems to generate pretty nice mazes!
(I don't remember the exact rule, but it's a very simple modification that tends to 'densify' the population of cells...)
[1]: http://en.wikipedia.org/wiki/Conway's_Game_of_Life |
There used to be some relatively cheap developers network which we used to belong to before the Novell questions all whithered and died away (famous last words, now I bet we will get one tomorrow), there is never any substitute for having the software / hardware, the only alternative is to write a test program and get your user to run it.
I am intrigued though as to what problem you are getting, the main ones we got were file locks with Jet databases. |
Returning a tuple is the usual way to do this in Python. |
Return a tuple.
def f(x):
# do stuff
return (True, modified_string)
success, modified_string = f(something) |
A common way to do this is with the **ExternalInterface** class, which you can use to call JavaScript methods.
First define your JavaScript methods, for example:
<script language="JavaScript">
function startsPlaying()
{
// do something when the FLV starts playing
}
</script>
Then modify your ActionScript to call the JavaScript method at the appropriate time:
// inform JavaScript that the FLV has started playing
ExternalInterface.call("startsPlaying");
For more information, see the related Flash CS3 [documentation][1].
[1]: http://livedocs.adobe.com/flash/9.0/main/00000342.html |
def f(in_str):
out_str = in_string.upper()
return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking |
I don't know whether this would work in DB2, but I'll tell you how I'd do this in SQL Server. I *think* the way MSSQL does this is ANSI standard, though the specific collation strings may differ. Anyway, if you can do this without trashing the rest of your application -- are there other places where the "name" column needs to be case-sensitive? -- try making that whole column case-insensitive by changing the collation, then index the column.
ALTER TABLE city ALTER COLUMN name nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS
The "CI" part is what marks it as case-insensitive in MSSQL.
To explain... my understanding is that the index will store values in the order of the indexed column's collation. Making the column's collation be case-insensitive would make the index store 'San Francisco', 'SAN FRANCISCO', and 'san francisco' all together. Then you should just have to remove the "UPPER()" from your query, and DB2 should know that it can use your index.
Again, this is based solely on what I know about SQL Server, plus a couple minutes looking at the SQL-92 spec; it may or may not work for DB2. |
I don't know whether this would work in DB2, but I'll tell you how I'd do this in SQL Server. I *think* the way MSSQL does this is ANSI standard, though the specific collation strings may differ. Anyway, if you can do this without trashing the rest of your application -- are there other places where the "name" column needs to be case-sensitive? -- try making that whole column case-insensitive by changing the collation, then index the column.
ALTER TABLE city ALTER COLUMN name nvarchar(200)
COLLATE SQL_Latin1_General_CP1_CI_AS
...where "nvarchar(200)" stands in for whatever's your current column data type. The "CI" part of the collation string is what marks it as case-insensitive in MSSQL.
To explain... my understanding is that the index will store values in the order of the indexed column's collation. Making the column's collation be case-insensitive would make the index store 'San Francisco', 'SAN FRANCISCO', and 'san francisco' all together. Then you should just have to remove the "UPPER()" from your query, and DB2 should know that it can use your index.
Again, this is based solely on what I know about SQL Server, plus a couple minutes looking at the SQL-92 spec; it may or may not work for DB2. |
I've been working in the address processing domain for about 5 years now, and there really is no silver bullet. The correct solution is going to depend on the value of the data. If it's not very valuable, throw it through a parser as the other answers suggest. If it's even somewhat valuable you'll definitely need to have a human evaluate/correct all the results of the parser. If you're looking for a fully automated, repeatable solution, you probably want to talk to a address correction vendor like Group1 or Trillium. |
The Equals method is intended to compare references. So it should not be overriden to change its behaviour.
You should create a new method to test for equivalence in different instances if you need to (or use the CompareTo method in some .NET classes) |
Need help writing a regex statement. [PHP] |
|php|regex|regularexpression|regular-expression| |
With an XML prolog like
<pre>
? xml version="1.0" encoding="iso-8859-1"? >
</pre>
and a Doctype like
<pre>
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
</pre>
I can get my page to render as expected. However, in IE7 the same page does not render correctly. (a span inside a div does not align vertically) Articles on the web suggest that XML prolog + doctype will throw IE6 into quirks mode. However the article below seems to suggest otherwise, although it does not mention the version (is it 6 or 7) it applies to
http://blogs.msdn.com/ie/archive/2005/09/15/467901.aspx
The article is dated sep 2005 which makes me believe it applies to IE6
Question: Does XML Prolog + doc type throw IE6 into quirks mode? What about IE7?
Any recommendations on for or against using the prolog + doctype
TIA
|
<(?!\/?a(?=>|\s.*>))\/?.*?>
Try this. Had something similar for p tags. Worked for them so don't see why not. Uses negative lookahead to check that it doesn't match a (prefixed with an optional / character) where (using positive lookahead) a (with optional / prefix) is followed by a > or a space, stuff and then >. This then matches up until the next > character. Put this in a subst with
s/<(?!\/?a(?=>|\s.*>))\/?.*?>//g;
This should leave only the opening and closing a tags |
This isn't answering your question, but I don't think "DefaultValue" means what you think it means. It doesn't set a default value for your property.
See [MSDN][1] and [this question][2] for more details.
[1]: http://support.microsoft.com/kb/311339
[2]: http://stackoverflow.com/questions/43738/defaultvalue-for-systemdrawingsystemcolors#44073 |
Ok, so let me see if I got this straight. You want to take a column that is currently computed and make it a plain-jane data column. Normally this would drop the column but you want to keep the data in the column.
1. Make a new table with the primary key columns from your source table and the generated column.
2. Copy the data from your source table into the new table.
3. Change the column on your source table.
4. Copy the data back.
No matter what you do I am pretty sure changing the column will drop it. This way is a bit more complex but not that bad and it saves your data.
[Edit: @SqlMenace's answer is much easier. :) Curse you Menace!! :)] |
Not that I know of but here is something you can do
add another column to the table
update that column with the values of the computed column then drop the computed column |