instruction stringlengths 0 30k ⌀ |
|---|
At a previous job, I used a Java obfuscator that as well as obfuscating the code, also removed classes and methods that weren't being used. If you were doing "Class.byName" or any other type of reflection stuff, you needed to tell the obfuscator because it couldn't tell by inspecting the code what classes or methods called by reflection.
The problem, of course, is that you don't know if other parts of the third party library are doing any reflection, and so removing an "unused" class might cause things to break in an obscure case that you haven't tested. |
My problem with Hyper-V is that it kills performance on some things on the host OS, especially A/V stuff. Whenever I would be playing music on the host OS and do something that hits the disk hard (like compiling), the music would begin skipping. Similarly, playing streaming video, you'd have to wait until it was completely downloaded before it would play without skipping.
I've since switched back to VMware and couldn't be happier. |
> Seriously speaking, LINQ to SQL had it's support for n-tier architecture see DataContext.Update method
Some of what I've read suggests that the business logic wraps the DataContext - in other words you wrap the update in the way that you suggest.
The way i traditionally write business objects i usually encapsulate the "Load methods" in the BO as well; so I might have a method named LoadEmployeesAndManagers that returns a list of employees and their immediate managers (this is a contrived example) . Now if I use LINQ it would probably look something like this (not checked for syntax correctness):
var emps = from e in Employees
join m in Employees
on e.ManagerEmpID equals m.EmpID
select new
{ e,
m.FullName
};
Now if I understand things correctly, if I put this in say a class library and call it from my front end, the only way I can return this is as an IEnumerable, so I lose my strong typed goodness. The only way I'd be able to return a strongly typed object would be to create my own Employees class (plus a string field for manager name) and fill it from the results of my LINQ to SQL statement and then return that. But this seems counter intuitive... what exactly did LINQ to SQL buy me if I have to do all that?
I think that I might be looking at things the wrong way; any enlightenment would be appreciated. |
> Seriously speaking, LINQ to SQL had it's support for n-tier architecture see DataContext.Update method
Some of what I've read suggests that the business logic wraps the DataContext - in other words you wrap the update in the way that you suggest.
The way i traditionally write business objects i usually encapsulate the "Load methods" in the BO as well; so I might have a method named LoadEmployeesAndManagers that returns a list of employees and their immediate managers (this is a contrived example) . Maybe its just me, but in my front end I'd rather see e.LoadEmployeesAndManagers() than some long LINQ statement.
Anyway, using LINQ it would probably look something like this (not checked for syntax correctness):
var emps = from e in Employees
join m in Employees
on e.ManagerEmpID equals m.EmpID
select new
{ e,
m.FullName
};
Now if I understand things correctly, if I put this in say a class library and call it from my front end, the only way I can return this is as an IEnumerable, so I lose my strong typed goodness. The only way I'd be able to return a strongly typed object would be to create my own Employees class (plus a string field for manager name) and fill it from the results of my LINQ to SQL statement and then return that. But this seems counter intuitive... what exactly did LINQ to SQL buy me if I have to do all that?
I think that I might be looking at things the wrong way; any enlightenment would be appreciated. |
One good way to do this is via fixtures, particularly the `initial_data` fixtures.
A fixture is a collection of files that contain the serialized contents of the database. So it's like having a backup of the database but as it's something Django is aware of it's easier to use and will have additional benefits when you come to do things like unit testing.
You can create a fixture from the data currently in your DB using `django-admin.py dumpdata`. By default the data is in JSON format, but other options such as XML are available. A good place to store fixtures is a `fixtures` sub-directory of your application directories.
You can load a fixure using `django-admin.py loaddata` but more signicantly, if your fixture has a name like `initial_data.json` it will be automatically loaded when you do a `syncdb`, saving the trouble of importing it yourself.
Another benefit is that when you run `manage.py test` to run your Unit Tests the temporary test database will also have the Initial Data Fixture loaded.
Of course, this will work when when you're adding attributes to models and columns to the DB. If you drop a column from the Database you'll need to update your fixture to remove the data for that column which might not be straightforward.
This works best when doing lots of little database changes during development. For updating production DBs a manually generated SQL script can often work best. |
One good way to do this is via fixtures, particularly the `initial_data` fixtures.
A fixture is a collection of files that contain the serialized contents of the database. So it's like having a backup of the database but as it's something Django is aware of it's easier to use and will have additional benefits when you come to do things like unit testing.
You can create a fixture from the data currently in your DB using `django-admin.py dumpdata`. By default the data is in JSON format, but other options such as XML are available. A good place to store fixtures is a `fixtures` sub-directory of your application directories.
You can load a fixure using `django-admin.py loaddata` but more significantly, if your fixture has a name like `initial_data.json` it will be automatically loaded when you do a `syncdb`, saving the trouble of importing it yourself.
Another benefit is that when you run `manage.py test` to run your Unit Tests the temporary test database will also have the Initial Data Fixture loaded.
Of course, this will work when when you're adding attributes to models and columns to the DB. If you drop a column from the Database you'll need to update your fixture to remove the data for that column which might not be straightforward.
This works best when doing lots of little database changes during development. For updating production DBs a manually generated SQL script can often work best. |
Use code.google.com
For example the [search result][1] for "Factory" will get you a lot of cases where the factory Pattern is implemented.
[1]: http://code.google.com/search/#q=Factory |
Here's an example from some actual Python code I wrote:
class Item(Model):
...
@property
def total(self):
if not hasattr(self, "_total"):
self._total = self.quantity \
+ sum(bi.quantity for bi in self.borroweditem_set.all())
return self._total
Basically, I have an Item class which represents an item in our inventory. The total number of items we have is the number that we own plus the sum of all of the items that we're borrowing from various sources. These numbers are all stored in our database, and it would be pointless to calculate this until the total is actually requested (since often Items will be used without the total being requested).
So the total property checks whether the _total field exists. If it doesn't, then the property code queries the database and computes it, then stores the value in the _total field so that it need not be recomputed the next time it's requested. |
What is the role of the buried-buffer-list frame parameter in Emacs |
|emacs|elisp| |
In emacs, I've read the following code snippet in simple.el :
(frame-parameter frame 'buried-buffer-list)
What is the exact meaning of buried-buffer-list parameter ? What it is used for ? |
What I have done in similar situations is put a shortcut in the default folder that takes me straight to where I want to go, although I am not sure I completely understand your question. |
I am not sure I completely understand your question.
* If you are referring to the folder the IDE has as the current folder, then you can just change the shortcut that launches Delphi to set the current directory where ever you want it to be.
|
just make a const string that holds the md5 hash and compile it into your app ... your app can then just refer to this const string when validating the configuration file |
I hear you, I've followed the Pylons mailing list for a while looking for something similar. There have been some attempts in the past (see [AdminPylon][1] and [Restin][2]) but none have really kept up with SQLAlchemy's rapidly developing orm api.
Since DBSprockets is likely to be incorporated into TurboGears it will likely be maintained. I'd bite the bullet and go with that.
[1]: http://adminpylon.devjavu.com/
[2]: http://code.google.com/p/restin/ |
I wish I knew more about your specific situation, but as general piece of advice, you might look into C++/CLI for issues involving unmanaged/managed interoperability:
<a href="http://msdn.microsoft.com/en-us/library/ms379617%28VS.80%29.aspx#vs05cplus_topic12">C++: The Most Powerful Language for .NET Framework Programming</a>
I know from experience that I can "lift" unmanaged code into a C++/CLI project where I can use it from any C#/.NET/managed code, but it sounds like you want to do the opposite: lift managed code into a C++/CLI project, and then link that with some unmanaged code and expose that as a traditional unmanaged DLL (or installer binary). I'm not sure if this is possible in C++/CLI. |
Related thread here, with some good contributions:
[What JavaScript library would you choose for a new project and why?][1]
[1]: http://stackoverflow.com/questions/913/what-javascript-library-would-you-choose-for-a-new-project-and-why |
To answer B:
[**Comparison of JavaScript frameworks**][1]
[1]: http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks |
To answer B:
[**Comparison of JavaScript frameworks**][1]
----------
**EDIT:** Although everyone and their mom is apparently riding the [**jQuery**][2] bandwagon (I use [**MochiKit**][3]), there are many libraries which provide the same functionality - the problem set which most libraries solve (async client-server communication, DOM manipulation, etc.) is the same, and there are few that don't have what you will need to get the job done.
The important thing to determine for yourself is whether or not a library will fit your particular style and sensibilities. Wide-spread ignorance about how [**JavaScript**][4], the language, actually works, coupled with the negative press resulting thereby, coupled with the now-immense popularity of jQuery leads most people down that road. Thankfully, it isn't a bad road to be on as there are a lot of travellers to keep you company when the abstractions leak and you need help. You probably can't go wrong choosing jQuery.
[1]: http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks
[2]: http://jquery.com/
[3]: http://www.mochikit.com
[4]: http://www.ecma-international.org/publications/standards/Ecma-262.htm |
Swtiching to ORMs |
|orm|language-agnostic| |
I'm toying with the idea of phasing in an ORM into an application I support. The app is not very structured with no unit tests. So any change will be risky. I'm obviously concerned that I've got a good enough reason to change. The idea is that there will be less boiler plate code for data access and there for greater productivity.
Do this ring true with your experiences?
Is it possible or even a good idea to phase it in?
What are the downsides of an ORM?
|
Switching to ORMs |
|language-agnostic|orm| |
Firstly, with a complex enough regexp, i beleive this can be impossible. But you should be able to put something together for simple regexps.
If you take a look at the source code of the class java.util.regex.Pattern, you'll see that it uses an internal representation of Node instances. Each of the different pattern components have their own implementation of a Node subclass. These Nodes are organised into a tree.
By producing a visitor that traverses this tree, you should be able to call an overloaded generator method or some kind of Builder that cobbles something together. |
Overview:
A **naïve!!** algorithm keeps track of the frequency of words in a per-column manner, where one can assume that each line can be separated into columns with a delimiter.
Example input:
The dog jumped over the moon
The cat jumped over the moon
The moon jumped over the moon
The car jumped over the moon
Frequencies:
Column 1: {The: 4}
Column 2: {car: 1, cat: 1, dog: 1, moon: 1}
Column 3: {jumped: 4}
Column 4: {over: 4}
Column 5: {the: 4}
Column 6: {moon: 4}
We could partition these frequency lists further by grouping based on the total number of fields, but in this simple and convenient example, we are only working with a fixed number of fields (6).
The next step is to iterate through lines which generated these frequency lists, so let's take the first example.
1. **The**: meets some hand-wavy criteria and the algorithm decides it must be static.
2. **dog**: doesn't appear to be static based on the rest of the frequency list, and thus it must be dynamic as opposed to static text. We loop through a few pre-defined regular expressions and come up with `/[a-z]+/i`.
3. **over**: same deal as #1; it's static, so leave as is.
4. **the**: same deal as #1; it's static, so leave as is.
5. **moon**: same deal as #1; it's static, so leave as is.
Thus, just from going over the first line we can put together the following regular expression:
/The ([a-z]+?) jumps over the moon/
Considerations:
* Obviously one can choose to scan part or the whole document for the first pass, as long as one is confident the frequency lists will be a sufficient sampling of the entire data.
* False positives may creep into the results, and it will be up to the filtering algorithm (hand-waving) to provide the best threshold between static and dynamic fields, or some human post-processing.
* The overall idea is probably a good one, but the actual implementation will definitely weigh in on the speed and efficiency of this algorithm. |
Overview:
A **naïve!!** algorithm keeps track of the frequency of words in a per-column manner, where one can assume that each line can be separated into columns with a delimiter.
Example input:
>The dog jumped over the moon
The cat jumped over the moon
The moon jumped over the moon
The car jumped over the moon
Frequencies:
Column 1: {The: 4}
Column 2: {car: 1, cat: 1, dog: 1, moon: 1}
Column 3: {jumped: 4}
Column 4: {over: 4}
Column 5: {the: 4}
Column 6: {moon: 4}
We could partition these frequency lists further by grouping based on the total number of fields, but in this simple and convenient example, we are only working with a fixed number of fields (6).
The next step is to iterate through lines which generated these frequency lists, so let's take the first example.
1. **The**: meets some hand-wavy criteria and the algorithm decides it must be static.
2. **dog**: doesn't appear to be static based on the rest of the frequency list, and thus it must be dynamic as opposed to static text. We loop through a few pre-defined regular expressions and come up with `/[a-z]+/i`.
3. **over**: same deal as #1; it's static, so leave as is.
4. **the**: same deal as #1; it's static, so leave as is.
5. **moon**: same deal as #1; it's static, so leave as is.
Thus, just from going over the first line we can put together the following regular expression:
/The ([a-z]+?) jumps over the moon/
Considerations:
* Obviously one can choose to scan part or the whole document for the first pass, as long as one is confident the frequency lists will be a sufficient sampling of the entire data.
* False positives may creep into the results, and it will be up to the filtering algorithm (hand-waving) to provide the best threshold between static and dynamic fields, or some human post-processing.
* The overall idea is probably a good one, but the actual implementation will definitely weigh in on the speed and efficiency of this algorithm. |
At my workplace, we have two repositories. One with public read access, and one for everything else. I'd use just one for everything, but we need different access rights for public/private projects.
That said, I personally don't see the problem with the revision numbers incrementing on every update. The revision numbers could skip prime and even numbers and still do what its supposed to do. Make it easy to get to a specific revision. |
The issue is that an element without a namespace is declared to be in the NULL namespace - therefore if //foo matched against the namespace you consider to be the 'default' there would be no way to refer to an element in the null namespace.
Remember as well that the prefix for a namespace is only a shorthand convention, the real element name (Qualified Name, or QName for short) consists of the full namespace and the local name. Changing the prefix for a namespace does not change the 'identity' of an element - if it is in the same namespace and same local name then it is the same kind of element, even if the prefix is different.
XPath 2.0 (or rather XSLT 2.0) has the concept of the 'default xpath namespace'. You can set the xpath-default-namespace attribute on the xsl:stylesheet element. |
It seems that as javascript page-tagging becomes the more popular choice as a way of processing web stats, there's not as much work being done on log-based analysis tools anymore in the marketplace. My office used to use a product called LiveStats.XSP. It wasn't the greatest tool by any means, but it did have some nice features. It was recently bought by Microsoft and is no longer supported however. It abandoned log analysis turned into a proposed Google Analytics killer called [Microsoft Gatineau][1], which supposedly is good at determining the demographics of your visitors, including age and gender (yeah sure...)
When I was looking for log analysis software a while ago, I wanted to avoid anything that looked overly bloated and enterprisey, which is what most stuff seemed to be, focusing more on the marketing and advertising aspects of reports.
One thing you may want to look at is the new version of [Urchin][2] (Urchin6). Urchin I believe was bought by Google a few years ago. It's offered as a locally installed solution, and with it you have the option to use either page-tagging or log file analysis for any site that it monitors. There also seems to be some interface ties between Google's own web-based Google Analytics and Urchin. It's not free though, unfortunately, and I think you can only get it through authorized partners.
It does all the standard logfile analysis stuff, everything is browser-based, the reports it offers are pretty deep and comprehensive, and it also seems to have a few bells and whistles that other services don't offer. For example, I remember it being able to present a view of a web page it tracks with colored hot spots overlayed on top of it, based on how often users click on items on that area of the page. Worth checking out the demo of it anyways.
[1]: http://www.good-together.co.uk/index.php/category/microsoft-gatineau/
[2]: http://www.google.com/urchin/ |
It seems that as javascript page-tagging becomes the more popular choice as a way of processing web stats, there's not as much work being done on log-based analysis tools anymore in the marketplace. My office used to use a product called LiveStats.XSP. It wasn't the greatest tool by any means, but it did have some nice features. It was recently bought by Microsoft and is no longer supported however. It abandoned log analysis turned into a proposed Google Analytics killer called [Microsoft Gatineau][1], which supposedly is good at determining the demographics of your visitors, including age and gender (yeah sure...)
When I was looking for log analysis software a while ago, I wanted to avoid anything that looked overly bloated and enterprisey, which is what most stuff seemed to be, focusing more on the marketing and advertising aspects of reports.
One thing you may want to look at is the new version of [Urchin][2], Urchin6 ([see features here][3]). Urchin I believe was bought by Google a few years ago. It's offered as a locally installed solution, and with it you have the option to use either page-tagging or log file analysis for any site that it monitors. There also seems to be some interface ties between Google's own web-based Google Analytics and Urchin. It's not free though, unfortunately, and I think you can only get it through authorized partners.
It does all the standard logfile analysis stuff, everything is browser-based, the reports it offers are pretty deep and comprehensive, and it also seems to have a few bells and whistles that other services don't offer. For example, I remember it being able to present a view of a web page it tracks with colored hot spots overlayed on top of it, based on how often users click on items on that area of the page. Worth checking out the demo of it anyways.
[1]: http://www.good-together.co.uk/index.php/category/microsoft-gatineau/
[2]: http://www.google.com/urchin/
[3]: http://www.google.com/urchin/features.html |
What is Lazy Loading? |
|data-binding| |
What is Lazy Loading? |
What is Lazy Loading?
[Edit after reading a few answers]
Why do people use this term so often?
Say you just use a ASP/ADO recordset and load it with data or ADO.NET Datasource for a gridview.
I guess I should have asked why people use the term Lazy Loading, what "other" types are their? |
F# language - hints for newbie |
|f#| |
Looks like here in StackOveflow there is a group of **F#** enthusiasts.
I'd like to know better this language, so, apart from the [functional programming theory][1], can you point me to the better starting points to start using the F# language? I mean, tutorials, how-tos, but first of all working samples to have the chance to start doing something and enjoy the language.
Thanks a lot
Andrea
[1]: http://en.wikipedia.org/wiki/Functional_programming |
It's called lazy loading because, like a lazy person, you are putting off doing something you don't want to. The opposite is Eager Loading, where you load something right away, long before you need it.
If you are curious why people might use lazy loading, consider an application that takes a LOOOOONG time to start. This application is probably doing a lot of eager loading... loading things from disk, and doing calculations and whatnot long before it is ever needed.
Compare this to lazy loading, the application would start much faster, but then the first time you need to do something that requires some long running load, there may be a slight pause while it is loaded for the first time. Thus, with lazy loading, you are amortizing the load time throughout the course of running your application... and you may actually save from loading things that the user may never intend to use. |
There's an XNA specific tutorial on [flocking][1].
[1]: http://creators.xna.com/en-us/sample/flocking |
To stop weird russian and chinese spams, I use this procmail configuration.
UNREADABLE='[^?"]*big5|iso-2022-jp|ISO-2022-KR|euc-kr|gb2312|ks_c_5601-1987'
:0:
* ^Content-Type:.*multipart
* B ?? $ ^Content-Type:.*^?.*charset="?($UNREADABLE)
spam-unreadable
|
Well, based on the 332 pattern you pointed out and the fact that the number of numbers is divisible by 3, and that several of the first 3 digit groups have matches... it might be that each 3 digits represents a character. Get a distribution of the number matches for all the 3 digit groups, then see if that distribution looks like the distribution of common letters.
If so, each 3 digit code could then be mapped to a character, and you might get a lot of the characters filled in for you this way, then just see if you can fill in the blanks of the less common letters that may not match the distribution perfectly.
A quick google search revealed [this source for distribution of frequency][1] in the English language.
This of course may not be fruitful, but it's a good first attempt.
[1]: http://www.csm.astate.edu/~rossa/datasec/frequency.html |
**Note:** This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, events on nested members, events on return types, etc, etc, is left as an exercise to the reader ;)
public sealed class EventWatcher : IDisposable {
private readonly object target_;
private readonly string eventName_;
private readonly FieldInfo eventField_;
private readonly Delegate listener_;
private bool eventWasRaised_;
public static EventWatcher Create<T>( T target, Expression<Func<T,Delegate>> accessor ) {
return new EventWatcher( target, accessor );
}
private EventWatcher( object target, LambdaExpression accessor ) {
this.target_ = target;
// Retrieve event definition from expression.
var eventAccessor = accessor.Body as MemberExpression;
this.eventField_ = eventAccessor.Member as FieldInfo;
this.eventName_ = this.eventField_.Name;
// Create our event listener and add it to the declaring object's event field.
this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType );
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Combine( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
}
public void SetEventWasRaised( ) {
this.eventWasRaised_ = true;
}
private Delegate CreateEventListenerDelegate( Type eventType ) {
// Create the event listener's body, setting the 'eventWasRaised_' field.
var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" );
var body = Expression.Call( Expression.Constant( this ), setMethod );
// Get the event delegate's parameters from its 'Invoke' method.
var invokeMethod = eventType.GetMethod( "Invoke" );
var parameters = invokeMethod.GetParameters( )
.Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );
// Create the listener.
var listener = Expression.Lambda( eventType, body, parameters );
return listener.Compile( );
}
void IDisposable.Dispose( ) {
// Remove the event listener.
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Remove( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
// Ensure event was raised.
if( !this.eventWasRaised_ )
throw new InvalidOperationException( "Event was not raised: " + this.eventName_ );
}
}
Usage is slightly different from that suggested, in order to take advantage of type inference:
try {
using( EventWatcher.Create( o, x => x.MyEvent ) ) {
//o.RaiseEvent( ); // Uncomment for test to succeed.
}
Console.WriteLine( "Event raised successfully" );
}
catch( InvalidOperationException ex ) {
Console.WriteLine( ex.Message );
}
|
**Edit:** As [Curt](http://stackoverflow.com/questions/35211/identify-an-event-via-a-linq-expression-tree#36255) has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event :) Instead of "`x => x.MyEvent`" returning the event, it was returning the backing field, which is only accessble by the class.
Since expressions cannot contain assignment statements, a modified expression like "`( x, h ) => x.MyEvent += h`" cannot be used to retrieve the event, so reflection would need to be used instead. A correct implementation would need to use reflection to retrieve the `EventInfo` for the event (which, unfortunatley, will not be strongly typed).
Otherwise, the only updates that need to be made are to store the reflected `EventInfo`, and use the `AddEventHandler`/`RemoveEventHandler` methods to register the listener (instead of the manual `Delegate` `Combine`/`Remove` calls and field sets). The rest of the implementation should not need to be changed. Good luck :)
---
**Note:** This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader ;)
public sealed class EventWatcher : IDisposable {
private readonly object target_;
private readonly string eventName_;
private readonly FieldInfo eventField_;
private readonly Delegate listener_;
private bool eventWasRaised_;
public static EventWatcher Create<T>( T target, Expression<Func<T,Delegate>> accessor ) {
return new EventWatcher( target, accessor );
}
private EventWatcher( object target, LambdaExpression accessor ) {
this.target_ = target;
// Retrieve event definition from expression.
var eventAccessor = accessor.Body as MemberExpression;
this.eventField_ = eventAccessor.Member as FieldInfo;
this.eventName_ = this.eventField_.Name;
// Create our event listener and add it to the declaring object's event field.
this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType );
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Combine( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
}
public void SetEventWasRaised( ) {
this.eventWasRaised_ = true;
}
private Delegate CreateEventListenerDelegate( Type eventType ) {
// Create the event listener's body, setting the 'eventWasRaised_' field.
var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" );
var body = Expression.Call( Expression.Constant( this ), setMethod );
// Get the event delegate's parameters from its 'Invoke' method.
var invokeMethod = eventType.GetMethod( "Invoke" );
var parameters = invokeMethod.GetParameters( )
.Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );
// Create the listener.
var listener = Expression.Lambda( eventType, body, parameters );
return listener.Compile( );
}
void IDisposable.Dispose( ) {
// Remove the event listener.
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Remove( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
// Ensure event was raised.
if( !this.eventWasRaised_ )
throw new InvalidOperationException( "Event was not raised: " + this.eventName_ );
}
}
Usage is slightly different from that suggested, in order to take advantage of type inference:
try {
using( EventWatcher.Create( o, x => x.MyEvent ) ) {
//o.RaiseEvent( ); // Uncomment for test to succeed.
}
Console.WriteLine( "Event raised successfully" );
}
catch( InvalidOperationException ex ) {
Console.WriteLine( ex.Message );
}
|
**Note:** This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader ;)
public sealed class EventWatcher : IDisposable {
private readonly object target_;
private readonly string eventName_;
private readonly FieldInfo eventField_;
private readonly Delegate listener_;
private bool eventWasRaised_;
public static EventWatcher Create<T>( T target, Expression<Func<T,Delegate>> accessor ) {
return new EventWatcher( target, accessor );
}
private EventWatcher( object target, LambdaExpression accessor ) {
this.target_ = target;
// Retrieve event definition from expression.
var eventAccessor = accessor.Body as MemberExpression;
this.eventField_ = eventAccessor.Member as FieldInfo;
this.eventName_ = this.eventField_.Name;
// Create our event listener and add it to the declaring object's event field.
this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType );
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Combine( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
}
public void SetEventWasRaised( ) {
this.eventWasRaised_ = true;
}
private Delegate CreateEventListenerDelegate( Type eventType ) {
// Create the event listener's body, setting the 'eventWasRaised_' field.
var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" );
var body = Expression.Call( Expression.Constant( this ), setMethod );
// Get the event delegate's parameters from its 'Invoke' method.
var invokeMethod = eventType.GetMethod( "Invoke" );
var parameters = invokeMethod.GetParameters( )
.Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );
// Create the listener.
var listener = Expression.Lambda( eventType, body, parameters );
return listener.Compile( );
}
void IDisposable.Dispose( ) {
// Remove the event listener.
var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;
var newEventList = Delegate.Remove( currentEventList, this.listener_ );
this.eventField_.SetValue( this.target_, newEventList );
// Ensure event was raised.
if( !this.eventWasRaised_ )
throw new InvalidOperationException( "Event was not raised: " + this.eventName_ );
}
}
Usage is slightly different from that suggested, in order to take advantage of type inference:
try {
using( EventWatcher.Create( o, x => x.MyEvent ) ) {
//o.RaiseEvent( ); // Uncomment for test to succeed.
}
Console.WriteLine( "Event raised successfully" );
}
catch( InvalidOperationException ex ) {
Console.WriteLine( ex.Message );
}
|
Looks like the docs are wrong (and have continued to be wrong for the last 3+ years!). I found this snippet with [Reflector][1] in [Microsoft.SqlServer.Management.Common.ConnectionManager][2], Microsoft.SqlServer.ConnectionInfo
protected void CheckServerVersion(ServerVersion version) {
if ((version.Major <= 7 || (version.Major > 9)) {
throw new ConnectionFailureException(
StringConnectionInfo.ConnectToInvalidVersion(version.ToString())
);
}
}
So, it looks like only SQL 2000 and SQL 2005 are supported. Presumably, SQL 2008 (version 10) has updated SMO assemblies.
Bummer - guess it's back to [SQL-DMO][3] for this project.
[1]: http://www.red-gate.com/products/reflector/
[2]: http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.common.connectionmanager.connect.aspx
[3]: http://msdn.microsoft.com/en-us/library/ms131540.aspx |
Is this link related?
<http://blenderartists.org/forum/showthread.php?t=77794>
To generate terrain (height map) the algorithm is pretty simple (fractal plasma), something like this algorithm (Java):
<http://www.sinc.stonybrook.edu/stu/jseyster/plasma/>
If you Google search for "fractal plasma python" you might find some example code.
|
Functors are pretty cool. They are pretty close to a function pointer, which everyone is usually quick to say is impossible in Java.
[Functors in Java][1]
[1]: http://chaoticjava.com/posts/functors-in-java-and-beyond/ |
This should do the trick
Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer
Dim jsonString as String = jsonSerialiser.Serialize(yourObject)
|
I think what you're looking for is this class:
System.ServiceModel.Web.DataContractJsonSerializer
Here's an example from Rick Strahl: [DataContractJsonSerializer in .NET 3.5](http://www.west-wind.com/WebLog/posts/218001.aspx) |
I know this doesn't directly answer your question, but what if you do all of the clipping on the client side to crop the image, then send the server the original image and the coordinates for clipping. Then on the server side, which will probably more suited for image manipulation like this (e.g. PHP it's very easy) you'll do the actual cropping of the image and storing the cropped version. |
In the System.Web.Extensions assembly, version 3.5.0.0, there's a [JavaScriptSerializer][1] class that should handle what you want.
[1]: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx |
Try
System.Web.Script.Serialization.JavaScriptSerializer
or Check out [JSON.org][1] there is a whole list of libraries written to do exactly what you want.
[1]: http://www.json.org/ |
Since the JavaScriptSerializer class is technically being deprecated, I believe [DataContractJsonSerializer][1] is the preferable way to go if you're using 3.0+.
[1]: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx |
Well, I am currently using the following extension methods to serialize and deserialize objects:
using System.Web.Script.Serialization;
public static string ToJSON(this object objectToSerialize)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(objectToSerialize);
}
/// <typeparam name="T">The type we are deserializing the JSON to.</typeparam>
public static T FromJSON<T>(this string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Deserialize<T>(json);
}
I use this quite a bit - be forewarned, this implementation is a bit naive (i.e. there are some potential problems with it, depending on what you are serializing and how you use it on the client, particularly with DateTimes). |
This morning, I was reading [Steve Yegge's: When Polymorphism Fails][1], when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.
> As an example of polymorphism in
> action, let's look at the classic
> "eval" interview question, which (as
> far as I know) was brought to Amazon
> by Ron Braunstein. The question is
> quite a rich one, as it manages to
> probe a wide variety of important
> skills: OOP design, recursion, binary
> trees, polymorphism and runtime
> typing, general coding skills, and (if
> you want to make it extra hard)
> parsing theory.
>
> At some point, the candidate hopefully
> realizes that you can represent an
> arithmetic expression as a binary
> tree, assuming you're only using
> binary operators such as "+", "-",
> "*", "/". The leaf nodes are all
> numbers, and the internal nodes are
> all operators. Evaluating the
> expression means walking the tree. If
> the candidate doesn't realize this,
> you can gently lead them to it, or if
> necessary, just tell them.
>
> Even if you tell them, it's still an
> interesting problem.
>
> The first half of the question, which
> some people (whose names I will
> protect to my dying breath, but their
> initials are Willie Lewis) feel is a
> Job Requirement If You Want To Call
> Yourself A Developer And Work At
> Amazon, is actually kinda hard. The
> question is: how do you go from an
> arithmetic expression (e.g. in a
> string) such as "2 + (2)" to an
> expression tree. We may have an ADJ
> challenge on this question at some
> point.
>
> The second half is: let's say this is
> a 2-person project, and your partner,
> who we'll call "Willie", is
> responsible for transforming the
> string expression into a tree. You get
> the easy part: you need to decide what
> classes Willie is to construct the
> tree with. You can do it in any
> language, but make sure you pick one,
> or Willie will hand you assembly
> language. If he's feeling ornery, it
> will be for a processor that is no
> longer manufactured in production.
>
> You'd be amazed at how many candidates
> boff this one.
>
> I won't give away the answer, but a
> Standard Bad Solution involves the use
> of a switch or case statment (or just
> good old-fashioned cascaded-ifs). A
> Slightly Better Solution involves
> using a table of function pointers,
> and the Probably Best Solution
> involves using polymorphism. I
> encourage you to work through it
> sometime. Fun stuff!
So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism?
Feel free to tackle one, two, or all three.
[1]: http://steve.yegge.googlepages.com/when-polymorphism-fails |
This morning, I was reading [Steve Yegge's: When Polymorphism Fails][1], when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.
> As an example of polymorphism in
> action, let's look at the classic
> "eval" interview question, which (as
> far as I know) was brought to Amazon
> by Ron Braunstein. The question is
> quite a rich one, as it manages to
> probe a wide variety of important
> skills: OOP design, recursion, binary
> trees, polymorphism and runtime
> typing, general coding skills, and (if
> you want to make it extra hard)
> parsing theory.
>
> At some point, the candidate hopefully
> realizes that you can represent an
> arithmetic expression as a binary
> tree, assuming you're only using
> binary operators such as "+", "-",
> "*", "/". The leaf nodes are all
> numbers, and the internal nodes are
> all operators. Evaluating the
> expression means walking the tree. If
> the candidate doesn't realize this,
> you can gently lead them to it, or if
> necessary, just tell them.
>
> Even if you tell them, it's still an
> interesting problem.
>
> The first half of the question, which
> some people (whose names I will
> protect to my dying breath, but their
> initials are Willie Lewis) feel is a
> Job Requirement If You Want To Call
> Yourself A Developer And Work At
> Amazon, is actually kinda hard. The
> question is: how do you go from an
> arithmetic expression (e.g. in a
> string) such as "2 + (2)" to an
> expression tree. We may have an ADJ
> challenge on this question at some
> point.
>
> The second half is: let's say this is
> a 2-person project, and your partner,
> who we'll call "Willie", is
> responsible for transforming the
> string expression into a tree. You get
> the easy part: you need to decide what
> classes Willie is to construct the
> tree with. You can do it in any
> language, but make sure you pick one,
> or Willie will hand you assembly
> language. If he's feeling ornery, it
> will be for a processor that is no
> longer manufactured in production.
>
> You'd be amazed at how many candidates
> boff this one.
>
> I won't give away the answer, but a
> Standard Bad Solution involves the use
> of a switch or case statment (or just
> good old-fashioned cascaded-ifs). A
> Slightly Better Solution involves
> using a table of function pointers,
> and the Probably Best Solution
> involves using polymorphism. I
> encourage you to work through it
> sometime. Fun stuff!
So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism?
Feel free to tackle one, two, or all three.
[1]: http://steve.yegge.googlepages.com/when-polymorphism-fails |
Two ways:
Embed *$Id$* or *$Revision$* within the code. Then set *svn:keywords="Id Revision"* property on the file. This will give you the last modified revision of that source file. Good for smaller projects and scripts.
Alternatively, use a Makefile driven process and the command line tool svnversion. (Language specific - this should work for C/C++)
echo -n "#define VERSION 1.0.1-" > version.h
svnversion -n . >> version.h
Or some more complex build script with sed and version.h.in. Then just *#include verison.h*
That will give you the repository version number, which will change with every commit / update, and is probably a more appropriate version number for most projects.
Note: I also used a human readable version string that I manually update. The example would give: **Version: 1.0.1-r13445**
~J |
Two ways:
Embed *$Id$* or *$Revision$* within the code. Then set *svn:keywords="Id Revision"* property on the file. This will give you the last modified revision of that source file. Good for smaller projects and scripts.
Alternatively, use a Makefile driven process and the command line tool svnversion. (Language specific - this should work for C/C++)
echo -n "#define VERSION 1.0.1-" > version.h
svnversion -n . >> version.h
Or some more complex build script with sed and version.h.in. Then just *#include version.h*
That will give you the repository version number, which will change with every commit / update, and is probably a more appropriate version number for most projects.
Note: I also used a human readable version string that I manually update. The example would give: **Version: 1.0.1-r13445**
~J |
You need to be wary of [XSS][1] when doing stuff like this:
document.getElementById('<%= Label1.ClientID %>').style.display
The chances are that no-one will be able to tamper with the ClientID of Label1 in this instance, but just to be on the safe side you might want pass it's value through one of the [AntiXss library's][2] methods:
document.getElementById('<%= AntiXss.JavaScriptEncode(Label1.ClientID) %>').style.display
[1]: http://en.wikipedia.org/wiki/Cross-site_scripting
[2]: http://www.microsoft.com/downloads/details.aspx?familyid=EFB9C819-53FF-4F82-BFAF-E11625130C25&displaylang=en |
@Kev, really like your solution. Thanks for the help.
Using the registry the code would look something like this:
RegistryKey key = Registry
.LocalMachine
.OpenSubKey("Software\\Microsoft\\NET Framework Setup\\NDP\\v3.5");
return (key != null);
I would be curious if either of these would work in a medium trust environment (although I am working in full trust so it doesn't matter to what I am currently working on). |
I have been looking at this kind of functionality myself recently and have decided on using jQuery with the help of [jQuery UI][3]. I came across a large amount of information that also suggested [Yahoo UI][1] (YUI), I had already started learning [jQuery][2] due to the AJAX support that it offers, so I stuck with it.
[jQuery UI Site][3]<br/>
[jQuery UI Documentation][4]<br/>
[Example of a drag and drop screen layout with jQuery UI][5]<br/>
[Introduction to jQuery UI][6]
If you decide to use the YUI javascript library, here is a link to a vast amount of videos to help get you started.
[http://developer.yahoo.com/yui/theater/][7]
[1]: http://developer.yahoo.com/yui/
[2]: http://jQuery.com
[3]: http://ui.jquery.com/
[4]: http://docs.jquery.com/UI
[5]: http://ui.jquery.com/repository/real-world/layout/
[6]: http://www.learningjquery.com/2008/07/introduction-to-jquery-ui#
[7]: http://developer.yahoo.com/yui/theater/ |
I've also since discovered that DXCore from DevExpress is a tool that simplifies plugin development. The default implementation wouldn't let me dock as document (central) but regardless one can still easily generate a plugin with it that can compile a file on the fly and render the contents of it which may well do the job for me. :) |
@Roddy - Synchronous sockets are not what I'm after. Burning a whole thread for the sake of a possibly long-lived connection means you limit the amount of concurrent connections to the number of threads that your process can contain. Since threads use a lot of resources - reserved stack address space, committed stack memory, and kernel transitions for context switches - they do not scale when you need to support hundreds of connections, much less thousands or more.
|
TrueType Fonts (TTF) will generally work on Windows, Mac, and Linux platforms.
[http://en.wikipedia.org/wiki/TrueType][1]
[1]: http://en.wikipedia.org/wiki/TrueType |
@Tynan The system can be described (somewhat over simplified) as a systems of rules describing categorizations. "Things are in category A if they are in B but not in C", "Nodes connected to nodes in Z are also in Z", "Every category in M is connected to a node N and has 'child' categories, also in M for every node connected to N". It's slightly more complicated than this. (I have shown that by creating unstable rules you can model a turning machine but that's beside the point.) It can't explicitly define iteration or recursion but can operate on recursive data with rules like the 2nd and 3rd ones.
@Marcin, Assume that there are an unlimited number of processors. It is trivial to show that the program can be run in O(n^2) for n being the longest cycle. With better data structures, this can be reduced to O(n*O(set lookup function)), I can envision hardware (quantum computers?) that can evaluate all cycles in constant time. giving a O(1) solution to the MST problem. |
@Tynan The system can be described (somewhat over simplified) as a systems of rules describing categorizations. "Things are in category A if they are in B but not in C", "Nodes connected to nodes in Z are also in Z", "Every category in M is connected to a node N and has 'child' categories, also in M for every node connected to N". It's slightly more complicated than this. (I have shown that by creating unstable rules you can model a turning machine but that's beside the point.) It can't explicitly define iteration or recursion but can operate on recursive data with rules like the 2nd and 3rd ones.
@Marcin, Assume that there are an unlimited number of processors. It is trivial to show that the program can be run in O(n^2) for n being the longest cycle. With better data structures, this can be reduced to O(n*O(set lookup function)), I can envision hardware (quantum computers?) that can evaluate all cycles in constant time. giving a O(1) solution to the MST problem.
The [Reverse-delete algorithm][1] seems to provide a partial proof of correctness (that the proposed algorithm will not produce a non-minimal spanning tree) this is derived by arguing that mt algorithm will remove every edge that the Reverse-delete algorithm will. However I'm not sure how to show that my algorithm won't delete more than that algorithm.
Hhmm....
[1]: http://en.wikipedia.org/wiki/Reverse-Delete_algorithm |
I prefer TextMate on OS X. But Netbeans (multi-platform) is coming along quite nicely. Plus it comes with its IDE fully functional debugger. |
I work on a large ASP.net application where we recently started to use NHibernate. We moved a large number of domain objects that we had been persisting manually to Sql Server over to NHibernate instead. It simplified things quite a bit and made it much easier to change things over time. We're glad we made the changes and are using NHibernate where appropriate for a lot of our new work. |
I'd recommend NetBeans 6.1 too. Very nice IDE and makes working with Ruby a pleasure. |
Unicode vs UTF-8 confusion in Python / Django? |
|python|django|unicode| |
I stumbled over this passage in the [Django tutorial][1]:
> Django models have a default __str__() method that calls __unicode__() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.
Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up [this "Python Unicode Tutorial"][2] which boldly states
> Unicode is a two-byte encoding which covers all of the world's common writing systems.
which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?
[1]: http://www.djangoproject.com/documentation/tutorial01/
[2]: http://www.reportlab.com/i18n/python_unicode_tutorial.html |
What is the difference between HttpHandler and a Web User Control and when to use each one? |
|asp.net| |
I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong |
Python stores Unicode as UTF-16. str() will return the UTF-8 representation of the UTF-16 string. |
On stackoverflow podcast 11:
>Spolsky: Yep. There's a new product also, if you don't want to use the Team System there our friends at Redgate have a product called SQL Data Generator [http://www.red-gate.com/products/sql_data_generator/index.htm]. It's $295, and it just generates some realistic test data. And it does things like actually generate real cities in the city column that actually exist, and then when it generates those it'll get the state right, instead of getting the state wrong, or putting states into German cities and stuff like... you know, it generates pretty realistic looking data. I'm not really sure what all the features are.
This is probably not what you are looking for, but it might be a good starting off point, instead of creating your own.
I can't seem to find anything in google, so I would suggest tackling the problem by parsing a given regular expression into the smallest units of work (\w, [x-x], \d, etc) and writing some basic methods to support those regular expression phrases.
So for \w you would have a method getRandomLetter() which returns any random letter, and you would also have getRandomLetter(char startLetter, char endLetter) which gives you a random letter between the two values.
|
I just added RSS feeds to the ticketing system I use at work ([TicketDesk][1]) and that feature should be in the next release of the product.
It's nice because it basically provides me a custom search view of outstanding trouble tickets or work requests that comes to me rather then me having to go to the application. It also allows users to get feeds of issues they may be interested in, but not require them to get emails on each update.
I'm looking at implementing an RSS feed for calls for service that our agency takes, to provide the administrators a quick and easy way to see what has been going on.
[1]: http://www.codeplex.com/ticketdesk |
It sounds like the web server on hosttwo.com doesn't allow undefined domains to be passed through. You also said you wanted to do a redirect, this isn't actually a method for redirecting. If you bought this domain through GoDaddy you may just want to use their redirection service. |
It's probably best/easiest to set up a [301 redirect][1]. No DNS hacking required.
[1]: http://www.webconfs.com/how-to-redirect-a-webpage.php |
Try changing it to sudomain -> subdomain.hosttwo.com
The cname is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the cname alias.
As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs? |
The program probably needs some more info put into its properties. It needs to "Run As", instead of just running.
Maybe this application should be developed as a service, instead of a program to be launched, or you could have service that launches the program when its determined the best window of opportunity. |
Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String.LastIndexOf; for example:
string filename = dialog.Filename;
string path = filename.Substring(0, filename.LastIndexOf("\"));
string file = filename.Substring(filename.LastIndexOf("\") + 1); |
The Path object in System.IO parses it pretty nicely. |
You could construct a FileInfo object. It has a Name, FullName, and DirectoryName property.
var file = new FileInfo(saveFileDialog.FileName);
Console.WriteLine("File is: " + file.Name);
Console.WriteLine("Directory is: " + file.DirectoryName);
|
Creating test data in a database |
|database|integration-testing| |
I'm aware of some of the test data generators out there, but most seem to just fill name and address style databases [feel free to correct me].
We have a large integrated and normalised application - e.g. invoices have part numbers linked to stocking tables, customer numbers linked to customer tables, change logs linked to audit information, etc which are obviously difficult to fill randomly. Currently we obfuscate real life data to get test data (but not very well).
What tools\methods do you use to create large volumes of data to test with? |
If I am not mistaken you need to swap the
mParent.layout();
and
mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
so that you have:
public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout());
ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
scrollBox.setExpandHorizontal(true);
mParent = new Composite(scrollBox, SWT.NONE);
scrollBox.setContent(mParent);
FormLayout layout = new FormLayout();
mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
mParent.layout();
} |
The **Chain of Command** pattern is implemented in the handling of DOM events. For example, (and simplifying slightly) when an element is clicked on, that element gets the first opportunity to handle the event, and then each ancestor in tern until the top level **document** is reached or one of them explicity stops the event "bubbling" any further. |
[I mention some in a review on Boagworld][1], I find the snippets, project manager, columnar editing (hold down option while selecting stuff or push it after having selected stuff) and CSS scopes for syntax.
[1]: http://boagworld.com/podcast/123/ |
Do you want the schema, but have it generated, or do you actually want **NO schema**?
For the former I'd go with nhibernate as @tom-carter said. Have it generate your schema for you, and you are all good (atleast until you roll your app out, then look at something like Tarantino and RedGate SQL Diff or whatever it's called to generate update scripts)
If you want the latter.... google app engine does this, as I've discovered this afternoon, and it's very nice. If you want to stick with code under your control, I'd suggest looking at CouchDB, tho it's a bit of upfront work getting it setup. But once you have it, it's a totally, 100% schema-free database. Well, you have an ID and a Version, but thats it - the rest is up to you. http://incubator.apache.org/couchdb/
But by the sounds of it (N)hibernate would suite the best, but I could be wrong. |
Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following...
diff file1.py file2.py | mate
...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen.
TextMate's SVN integration is great; it also seems to have bundles for some other version control systems as well.
Add GetBundle to browse the bundle repository. I found the jQuery bundle through it and it's very handy.
As others have mentioned, rolling your own bundle for frequently used snippets is very helpful. If you have some snippets that are specific to a project or framework, you might want to prefix all of them with a common letter to keep the namespace tidy. |
Currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments. Here's an example in Scheme
(define (add a b)
(+ a b))
(add 3 4) returns 7
This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:
(define (add a)
(lambda (b)
(+ a b)))
This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their sum.
((add 3) 4)
(define add3 (add 3))
(add3 4)
The first statement returns 7, like the (add 3 4) statement. The second statement defines a new function called add3 that will add 3 to its argument. This is what some people may call a closure. The third statement uses the add3 operation to add 3 to 4, again producing 7 as a result. |
This morning, I was reading [Steve Yegge's: When Polymorphism Fails][1], when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.
> As an example of polymorphism in
> action, let's look at the classic
> "eval" interview question, which (as
> far as I know) was brought to Amazon
> by Ron Braunstein. The question is
> quite a rich one, as it manages to
> probe a wide variety of important
> skills: OOP design, recursion, binary
> trees, polymorphism and runtime
> typing, general coding skills, and (if
> you want to make it extra hard)
> parsing theory.
>
> At some point, the candidate hopefully
> realizes that you can represent an
> arithmetic expression as a binary
> tree, assuming you're only using
> binary operators such as "+", "-",
> "*", "/". The leaf nodes are all
> numbers, and the internal nodes are
> all operators. Evaluating the
> expression means walking the tree. If
> the candidate doesn't realize this,
> you can gently lead them to it, or if
> necessary, just tell them.
>
> Even if you tell them, it's still an
> interesting problem.
>
> The first half of the question, which
> some people (whose names I will
> protect to my dying breath, but their
> initials are Willie Lewis) feel is a
> Job Requirement If You Want To Call
> Yourself A Developer And Work At
> Amazon, is actually kinda hard. The
> question is: how do you go from an
> arithmetic expression (e.g. in a
> string) such as "2 + (2)" to an
> expression tree. We may have an ADJ
> challenge on this question at some
> point.
>
> The second half is: let's say this is
> a 2-person project, and your partner,
> who we'll call "Willie", is
> responsible for transforming the
> string expression into a tree. You get
> the easy part: you need to decide what
> classes Willie is to construct the
> tree with. You can do it in any
> language, but make sure you pick one,
> or Willie will hand you assembly
> language. If he's feeling ornery, it
> will be for a processor that is no
> longer manufactured in production.
>
> You'd be amazed at how many candidates
> boff this one.
>
> I won't give away the answer, but a
> Standard Bad Solution involves the use
> of a switch or case statment (or just
> good old-fashioned cascaded-ifs). A
> Slightly Better Solution involves
> using a table of function pointers,
> and the Probably Best Solution
> involves using polymorphism. I
> encourage you to work through it
> sometime. Fun stuff!
So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism?
Feel free to tackle one, two, or all three.
[update: title modified to better match what most of the answers have been.]
[1]: http://steve.yegge.googlepages.com/when-polymorphism-fails |
This morning, I was reading [Steve Yegge's: When Polymorphism Fails][1], when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.
> As an example of polymorphism in
> action, let's look at the classic
> "eval" interview question, which (as
> far as I know) was brought to Amazon
> by Ron Braunstein. The question is
> quite a rich one, as it manages to
> probe a wide variety of important
> skills: OOP design, recursion, binary
> trees, polymorphism and runtime
> typing, general coding skills, and (if
> you want to make it extra hard)
> parsing theory.
>
> At some point, the candidate hopefully
> realizes that you can represent an
> arithmetic expression as a binary
> tree, assuming you're only using
> binary operators such as "+", "-",
> "*", "/". The leaf nodes are all
> numbers, and the internal nodes are
> all operators. Evaluating the
> expression means walking the tree. If
> the candidate doesn't realize this,
> you can gently lead them to it, or if
> necessary, just tell them.
>
> Even if you tell them, it's still an
> interesting problem.
>
> The first half of the question, which
> some people (whose names I will
> protect to my dying breath, but their
> initials are Willie Lewis) feel is a
> Job Requirement If You Want To Call
> Yourself A Developer And Work At
> Amazon, is actually kinda hard. The
> question is: how do you go from an
> arithmetic expression (e.g. in a
> string) such as "2 + (2)" to an
> expression tree. We may have an ADJ
> challenge on this question at some
> point.
>
> The second half is: let's say this is
> a 2-person project, and your partner,
> who we'll call "Willie", is
> responsible for transforming the
> string expression into a tree. You get
> the easy part: you need to decide what
> classes Willie is to construct the
> tree with. You can do it in any
> language, but make sure you pick one,
> or Willie will hand you assembly
> language. If he's feeling ornery, it
> will be for a processor that is no
> longer manufactured in production.
>
> You'd be amazed at how many candidates
> boff this one.
>
> I won't give away the answer, but a
> Standard Bad Solution involves the use
> of a switch or case statment (or just
> good old-fashioned cascaded-ifs). A
> Slightly Better Solution involves
> using a table of function pointers,
> and the Probably Best Solution
> involves using polymorphism. I
> encourage you to work through it
> sometime. Fun stuff!
So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism?
Feel free to tackle one, two, or all three.
[update: title modified to better match what most of the answers have been.]
[1]: http://steve.yegge.googlepages.com/when-polymorphism-fails |
I'm happy with Oracle XE for development purposes.
I do have this piece of wisdow to share; if you're having problems like ORA-12519: TNS:no appropriate service handler found or ORA-12560: TNS:protocol adapter error from time to time then try to change your PROCESSES parameter, logon to Oracle using sys as sysdba and execute the following:
ALTER SYSTEM SET PROCESSES=150 SCOPE=SPFILE;
After changing the PROCESSES parameter restart your Oracle service. |
> TrueType Fonts (TTF) will generally work on Windows, Mac, and Linux platforms.
Thanks Jason, but this isn't the answer I'm looking for. Many Linux distributions come with their own fonts that are different *in name* to the Mac/Windows versions - presumably because of font licensing issues.
I'd like a response from a Linux user (preferably developer) who has experience with coming up with similar looking fonts. I really don't want to have to give Ubuntu Firefox users 'any sans-serif'. |
Address book DB schema |