instruction stringlengths 0 30k ⌀ |
|---|
Your best bet is to use WCF. You will be able to create a service host in the windows service and expose a well defined interface that the GUI application can consume. WCF will let you communicate via named pipes if you choose, or you can choose any other communication protocal like TCP, HTTP, etc. Using WCF you get great tool support and lots of available information. |
Brian, the classic ASP equivalent of a Perl hash is the [Scripting.Dictionary](http://www.microsoft.com/technet/scriptcenter/guide/sas_scr_ildk.mspx?mfr=true) object. |
Painting javax.microedition.lcdui.Graphics on LWUIT Component |
|java-me|lwuit| |
What would be the best method for getting a custom element (that is using J2ME native Graphics) painted on LWUIT elements?
The custom element is an implementation from mapping library, that paints it's content (for example Google map) to Graphics object. How would it be possible to paint the result directly on LWUIT elements (at the moment I am trying to paint it on a Component).
Is the only way to write a wrapper in LWUIT package, that would expose the internal implementation of it?
/JaanusSiim |
|java|java-me|lwuit| |
What would be the best method for getting a custom element (that is using J2ME native Graphics) painted on LWUIT elements?
The custom element is an implementation from mapping library, that paints it's content (for example Google map) to Graphics object. How would it be possible to paint the result directly on LWUIT elements (at the moment I am trying to paint it on a Component).
Is the only way to write a wrapper in LWUIT package, that would expose the internal implementation of it?
**Edit:**
***John:*** your solution looks like a lot of engineering :P What I ended up using is following wrapper:
package com.sun.lwuit;
public class ImageWrapper {
private final Image image;
public ImageWrapper(final Image lwuitBuffer) {
this.image = lwuitBuffer;
}
public javax.microedition.lcdui.Graphics getGraphics() {
return image.getGraphics().getGraphics();
}
}
Now I can get the 'native' Graphics element from LWUIT. Paint on it - effectively painting on LWUIT image. And I can use the image to paint on a component.
And it still looks like a hack :)
But the real problem is 50kB of code overhead, even after obfuscation. But this is a issue for another post :)
/JaanusSiim |
See the [Database Publishing Wizard][1] which is part of the **SQL Server Hosting Toolkit** which generates a single SQL file for both schema and data.
[1]: http://www.codeplex.com/sqlhost/Wiki/View.aspx?title=Database%20Publishing%20Wizard |
You are correct, if you use BufferedReader for reading HTTP content and headers you will want InputStreamReader so you can read byte for byte.
BufferedReader in this scenario sometimes does weird things...escpecially when it comes to reading HTTP POST headers, sometimes you will be unable to read the POST data, if you use the InputStreamReader you can read the content length and read that many bytes... |
Java: Programatic Way to Determine Current Windows User |
|java|windows| |
I see many similar questions, however I want to find the Username of the currently logged in user using Java.
Its probably something like:
System.getProperty(current.user);
But, I'm not quite sure. |
My gut tells me that since you're already performing buffering by using the byte array, it's redundant to use the BufferedReader. |
Yes because of the Global Interpreter Lock (GIL) there can only run on thread at a time. Here are some links with some insights about this:
* http://blog.snaplogic.org/?p=94
* http://www.artima.com/weblogs/viewpost.jsp?thread=214235
* http://effbot.org/pyfaq/can-t-we-get-rid-of-the-global-interpreter-lock.htm
* http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/
From the last link an intereasting quote:
> Let me explain what all that means.
> Threads run inside the same virtual
> machine, and hence run on the same
> physical machine. Processes can run
> on the same physical machine or in
> another physical machine. If you
> architect your application around
> threads, you’ve done nothing to access
> multiple machines. So, you can scale
> to as many cores are on the single
> machine (which will be quite a few
> over time), but to really reach web
> scales, you’ll need to solve the
> multiple machine problem anyway.
If you want to use multi core, [pyprocessing][1] defines an process based api to do real parallelization. The pep also includes some interesting benchmarks
[1]: http://www.python.org/dev/peps/pep-0371/ |
> Must be a Vista problem. I have XP SP 2 and it looks normal.
So it is.
I tried it on XP and it's fine, and on vista with the theme set to windows classic it's also fine. Must just be a bug in the firefox-vista-aero theme. |
[RedGate SqlCompare][1] is a way to go in my opinion. We do DB deployment on a regular basis and since I started using that tool I have never looked back.
Very intuitive interface and saves a lot of time in the end.
The Pro version will take care of scripting for the source control integration as well.
[1]: http://www.red-gate.com/products/SQL_Compare/index.htm |
You're actually really close. Try this instead:
System.getProperty("user.name") |
You're actually really close. This is what you're looking for:
System.getProperty("user.name") |
There's [Cursed GTK][1], but it seems a bit dated. I found some references to a port of Qt to ncurses called Qt Console, but it seems to have disappeared.
[1]: http://zemljanka.sourceforge.net/cursed/
|
I doubt sh/bash can do it.
ZSH would be a better bet, with its MULTIOS and coproc features. |
The one time I've seen this before, I was working with a library which also defined Exception and the usings I had meant that the actual Catch was referring to a different "Exception" type (if it had been fully qualified it was Company.Lib.Exception but it wasnt because of the using) so when it came to catching a normal exception that was being thrown (some kind of argument exception if I remember correctly) it just wouldn't catch it because the type didn't match.
So in summary, is there another Exception type in a different namespace that is in a using in that class?
EDIT: A quick way to check this is make sure in you catch you fully qualify the Exception type as "System.Exception" and give it a whirl! |
The one time I've seen this before, I was working with a library which also defined Exception and the usings I had meant that the actual Catch was referring to a different "Exception" type (if it had been fully qualified it was Company.Lib.Exception but it wasnt because of the using) so when it came to catching a normal exception that was being thrown (some kind of argument exception if I remember correctly) it just wouldn't catch it because the type didn't match.
So in summary, is there another Exception type in a different namespace that is in a using in that class?
EDIT: A quick way to check this is make sure in your catch clause you fully qualify the Exception type as "System.Exception" and give it a whirl! |
Personally I'm not convinced by the threading theory at all.
The one time I've seen this before, I was working with a library which also defined Exception and the usings I had meant that the actual Catch was referring to a different "Exception" type (if it had been fully qualified it was Company.Lib.Exception but it wasnt because of the using) so when it came to catching a normal exception that was being thrown (some kind of argument exception if I remember correctly) it just wouldn't catch it because the type didn't match.
So in summary, is there another Exception type in a different namespace that is in a using in that class?
EDIT: A quick way to check this is make sure in your catch clause you fully qualify the Exception type as "System.Exception" and give it a whirl! |
Personally I'm not convinced by the threading theory at all.
The one time I've seen this before, I was working with a library which also defined Exception and the usings I had meant that the actual Catch was referring to a different "Exception" type (if it had been fully qualified it was Company.Lib.Exception but it wasnt because of the using) so when it came to catching a normal exception that was being thrown (some kind of argument exception if I remember correctly) it just wouldn't catch it because the type didn't match.
So in summary, is there another Exception type in a different namespace that is in a using in that class?
EDIT: A quick way to check this is make sure in your catch clause you fully qualify the Exception type as "System.Exception" and give it a whirl!
EDIT2: OK I've tried the code and concede defeat for now. I'll have to have another look at it in the morning if no one has come up with a solution. |
.egg files are basically a nice way to deploy your python application. You can think of it as something like .jar files for Java.
More info [here][1].
[1]: http://peak.telecommunity.com/DevCenter/PythonEggs |
Eggs are a pretty good way to distribute python apps. Think of it as a platform independent .deb file that will install all dependencies and whatnot. The advantage is that it's easy to use for the end user. The disadvantage are that it can be cumbersome to package your app up as a .egg file.
You should also offer an alternative means of installation in addition to .eggs. There are some people who don't like using eggs because they don't like the idea of a software program installing whatever software it wants. These usually tend to be sysadmin types. |
Thanks, that helped because it showed what was wrong: My file paths were different. Here's how I fixed it:
1) Load database from SQL 2000 backup
2) Set compatibility mode to SQL 2005
USE mydb
GO
ALTER DATABASE mydb SET COMPATIBILITY_LEVEL = 90
GO
3) Get the filegroup names
SELECT name
FROM sys.master_files mf
WHERE type = 4
AND EXISTS( SELECT *
FROM sys.databases db
WHERE db.database_id = mf.database_id
AND name = 'mydb')
4) Then for each name (I did this in a little script)
ALTER DATABASE mydb
MODIFY FILE( NAME = {full text catalog name}, FILENAME="N:\ew\path\to\wherever")
5) Then collect all the "readable" names of the catalogs:
SELECT name FROM sys.sysfulltextcatalogs
6) Finally, now you can rebuild each one:
ALTER FULLTEXT CATALOG {full text catalog name} REBUILD
|
To answer your additional question:
> [This](http://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data)
> question precipitated my inquiry. The
> tea.h file makes no reference to the
> tea.c file. Does the compiler "know"
> that every .h file has a corresponding
> .c file?
The compiler is not primarily concerned with header files. Each invocation of the compiler compiles a source (.c) file into an object (.o) file. Behind the scenes (i.e. in the `make` file or project file) a command line equivalent to this is being generated:
compiler --options tea.c
The source file `#include`s all the header files for the resources it references, which is how the compiler finds them.
(I'm glossing over some details here. There is a lot to learn about building C projects.)
|
To answer your additional question:
> [This](http://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data)
> question precipitated my inquiry. The
> tea.h file makes no reference to the
> tea.c file. Does the compiler "know"
> that every .h file has a corresponding
> .c file?
The compiler is not primarily concerned with header files. Each invocation of the compiler compiles a source (.c) file into an object (.o) file. Behind the scenes (i.e. in the `make` file or project file) a command line equivalent to this is being generated:
compiler --options tea.c
The source file `#include`s all the header files for the resources it references, which is how the compiler finds header files.
(I'm glossing over some details here. There is a lot to learn about building C projects.)
|
I don't think you have the ASP.Net master pages translated to the *WPF Page* world just yet.
A workaround till MS gets there, I would probably put a Control at the top of the page (or wherever) that just displays a particular User-level "[Application Setting][1]". You can update the string property like
MyAppUserSettings.StatusMessage = "You just deleted the administrator!"
Crude but will get the job done I think!
[1]: http://msdn.microsoft.com/en-us/library/ms171565.aspx |
There is a way to do this that is effective with internal users, but can be hacked. You create two IDs for each user. One is a reporting ID that has read-only access. This is they ID that the user knows about: Fred / mypassword
The second is an ID that can do updates. That id is Fred_app / mypassword_mangled. They log on to your app with Fred. When your application accesses data, it uses the application id.
This can be sniffed, but for many applications it is sufficient.
|
Don't do it!
* Trying to create identifiers that are not valid in your language is not a good idea.
* If you really want to set variables like that, use attribute macros.
attr_writer :bar
attr_reader :baz
attr_accessor :foo
|
Don't do it!
Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:
attr_writer :bar
attr_reader :baz
attr_accessor :foo
|
Don't do it!
Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:
attr_writer :bar
attr_reader :baz
attr_accessor :foo
|
Don't do it!
Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:
attr_writer :bar
attr_reader :baz
attr_accessor :foo
Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.
class SillySetter
def initialize path=nil
@path = path
end
def method_missing name,value=nil
new_path = @path ? "#{@path}.#{name}" : name
if name.to_s[-1] == ?=
puts "setting #{new_path} #{value}"
else
return self.class.new(path=new_path)
end
end
end
s = SillySetter.new
s.foo = 5 # -> setting foo= 5
s.foo.bar.baz = 4 # -> setting foo.bar.baz= 4
I didn't want to encourage ruby sillyness, but I just couldn't help myself! |
Does a language-specific IDE have any advantages over a plugin for a multi-language IDE? |
|ide| |
I do mostly Java and C/C++ development, but I'm starting to do more web development (PHP, Rails) and Eiffel (learning a new language is always good).
Currently, I use Eclipse for Java, C/C++, and Ruby (not Rails). Since I know the environment, I'm thinking that it would be easier for me to find a plugin and use Eclipse for all of my development languages. But are there cases where a language-specific IDE (EiffelStudio for Eiffel, as an example) would be better than Eclipse? |
2.0 Has the `ConvertAll` method where you can pass in a converter function
List<int> l1 = new List<int>(new int[] { 1,2,3 } );
List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });
|
If you can fit the data into memory and you like python then I recommend checking out the UniTable portion of [Augustus][1]. (Disclaimer: Augustus is open source (GPLv2) but I work for the company that writes it.)
It's not very well documented but this should help you get going.
from augustus.kernel.unitable import *
a = UniTable().from_csv_file('filename')
b = a.subtbl(a['key'] == some_value) #creates a subtable
It won't directly give you an excel like interface but with a little bit of work you can get many statistics out quickly.
[1]: http://sourceforge.net/projects/augustus "Augustus" |
The only CIL book on my shelf is [Expert .NET 2.0 IL Assembler][1] by Serge Lidin. In terms of what the individual opcodes do or mean, the Microsoft documentation on System.Reflection.Emit has some pretty good information. And it's always useful to look at existing IL with [Reflector][2].
[1]: http://www.apress.com/book/view/1590596463
[2]: http://www.red-gate.com/products/reflector/ |
The only CIL book on my shelf is [Expert .NET 2.0 IL Assembler][1] by Serge Lidin. In terms of what the individual opcodes do or mean, the Microsoft documentation on System.Reflection.Emit has some pretty good information. And it's always useful to look at existing IL with [Reflector][2].
**Edit:** CIL (and indeed the CLR in general) has not changed at all between .NET 2.0 and .NET 3.5 -- the underlying runtime is basically the same, modulo fixes and performance improvements. So there's nothing newer available on a CIL level than what would be in a book on 2.0
[1]: http://www.apress.com/book/view/1590596463
[2]: http://www.red-gate.com/products/reflector/ |
You wouldn't be able to directly cast it as no explicit or implicit cast exists from int to string, it would *have* to be a method involving .ToString() such as:-
foreach (int i in intList) stringList.Add(i.ToString()); |
You wouldn't be able to directly cast it as no explicit or implicit cast exists from int to string, it would *have* to be a method involving .ToString() such as:-
foreach (int i in intList) stringList.Add(i.ToString());
**Edit** - or as others have pointed out rather brilliantly, use intList.ConvertAll(delegate(int i) { return i.ToString(); });, however clearly you still have to use .ToString() and it's a conversion rather than a cast. |
Is C# 2.0 able to do List`<T`>.Convert? If so, I think your best guess would be to use that with a delegate:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Convert(delegate (int i) { return i.ToString(); });
Something along those lines. |
Is C# 2.0 able to do List`<T`>.Convert? If so, I think your best guess would be to use that with a delegate:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Convert(delegate (int i) { return i.ToString(); });
Something along those lines.
----------
Upvote Glenn's answer, which is probably the correct code ;-) |
Check out Billy McCafferty's [S#arp Architecture][1] project for a great ASP.NET MVC starter project filled with best practices.
If you want something a little simpler, I threw together a rudimentary version of the S#arp Architecture project, called [Blunt Architecturehere][2].
[1]: http://code.google.com/p/sharp-architecture/
[2]: http://code.google.com/p/bluntarchitecture/ |
You can use a [Derived Column Transformation][1] in which you'll create a new output column and set its value to 2. You can then use that column when outputting to SQL.
[1]: http://msdn.microsoft.com/en-us/library/ms141069.aspx |
@Daniel <blockquote>The distinction between fork/exec and dynamic linking, besides being kind of artificial, doesn't carry over to interpreted languages: what about a Python/Perl/Ruby plugin, which gets loaded via import or execfile?</blockquote>
I'm not sure that the distinction **is** artificial. After a dynamic load the plugin code shares an execution context with the GPLed code. After a fork/exec it does not.
In anycase I would guess that `import`ing causes the new code to run in the same execution context as the GPLed bit, and you should treat it like the dynamic link case. No? |
> he distinction between fork/exec and dynamic linking, besides being kind of artificial,
I don't think its artificial at all. Basically they are just making the division based upon the level of integration. If the program has "plugins" which are essentially fire and forget with no API level integration, then the resulting work is unlikely to be considered a derived work. Generally speaking a plugin which is merely forked/exec'ed would fit this criteria, though there may be cases where it does not. This case especially applies if the "plugin" code would work independently of your code as well.
If, on the other hand, the code is deeply dependent upon the GPL'ed work, such as extensively calling APIs, or tight data structure integration, then things are more likely to be considered a derived work. Ie, the "plugin" cannot exist on its own without the GPL product, and a product with this plugin installed is essentially a derived work of the GPLed product.
So to make it a little more clear, the same principles could apply to your interpreted code. If the interpreted code relies heavily upon your APIs (or vice-versa) then it would be considered a derived work. If it is just a script that executes on its own with extremely little integration, then it may not.
Does that make more sense? |
How much info are you sharing between the Plugins and the main program? If you are doing anything more than just executing them and waiting for the results (sharing no data between the program and the plugin in the process) then you could most likely get away with them being proprietary, otherwise they would probably need to be GPL'd. |
NHIbernate: Difference between Restriction.In and Restriction.InG |
|c#|nhibernate|orm| |
When creating a criteria in NHibernate I can use
Restriction.In() or
Restriction.InG()
What is the difference between them? |
The short answer is because I can. The long answer, expanding on what the OP said, is to be more compatible with apache and mysql/postgresql. They are all 64bit (apache is a fat binary with ppc, ppc64 x86 and x86 and x86_64, the others just straight 64bit). **Mysqldb and mod_python wont compile unless they are all running the same architecture.** Yes I could run them all in 32bit (and have in the past) but this is much more work then compiling one program.
EDIT: You pretty much convinced though to just let the installer do its thing and update the PATH to reflect this. |
You can use Windows.Forms.NotifyIcon for this. http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.aspx
Add NotifyIcon to the form, set some properties and you are done.
this.ShowIcon = false;//for the main form
this.ShowInTaskbar = false;//for the main form
this.notifyIcon1.Visible = true;//for notify icon
this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));//set an icon for notifyicon
private void Form1_Shown(object sender, EventArgs e)
{
this.Hide();
} |
Update: Looks like I posted too soon.
I was also using the below hack for a tool of mine. Waiting for the right solution for this..........
You can use Windows.Forms.NotifyIcon for this. http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.aspx
Add NotifyIcon to the form, set some properties and you are done.
this.ShowIcon = false;//for the main form
this.ShowInTaskbar = false;//for the main form
this.notifyIcon1.Visible = true;//for notify icon
this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));//set an icon for notifyicon
private void Form1_Shown(object sender, EventArgs e)
{
this.Hide();
} |
You should implement in your client code javax.jms.ExceptionListener. You will need a method called onException. When the client's connection is lost, you should get an JMSException and this method will be called automatically. The only thing you have to control for is if you are actually trying to disconnect from JBossMQ that will also throw an exception. Some code might look like this:
public void onException (JMSException jsme)
{
if (!closeRequested)
{
this.disconnect();
this.establishConnection(connectionProps, queueName, uname, pword, clientID, messageSelector);
}
else
{
//Client requested close so do not try to reconnect
}
}
In your "establishConnection" code, you would then implement a while(!initialized) construct that contains a try/catch inside of it. Until you are sure you have connected and subscribed properly, stay inside the while loop catching all JMS/Naming/etc exception. We've used this method for years with JBossMQ and it works great and have never had a problem with our JMS clients not reconnecting after bouncing JBossMQ or loosing our network connection.
|
The key to this matter is the historical usage of both systems, I think. Windows (and DOS before that) have originally been single-user systems for _personal_ computers. As such, these systems typically don't have to create a lot of processes all the time; (very) simply put, a process is only created when this one lonely user requests it (and we humans don't operate very fast, relatively speaking).
Unix-based systems have originally been multi-user systems and servers. Especially for the latter it is not uncommon to have processes (e.g. mail or http daemons) that split of processes to handle specific jobs (e.g. taking care of one incoming connection). An important factor in doing this is the cheap `fork` method (that, as mentioned by Rob Walker ([47865](http://stackoverflow.com/questions/47845/why-is-creating-a-new-process-more-expensive-on-windows-than-linux#47865)), initially uses the same memory for the newly created process) which is very useful as the new process immediately has all the information it needs.
It is clear that at least historically the need for Unix-based systems to have fast process creation is far greater than for Windows systems. I think this is still the case because Unix-based systems are still very process oriented, while Windows, due to its history, has probably been more thread oriented (threads being useful to make responsive applications).
Disclaimer: I'm by no means an expert on this matter, so forgive me if I got it wrong. |
As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation:
CASE
WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now() THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago')
WHEN datediff(now(), compare_date) = 1 THEN 'Yesterday'
WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now() THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago')
ELSE concat(datediff(now(), compare_date),' days ago')
END
Based on a similar sample seen on the [MySQL Date and Time](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#c9500) manual pages |
As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation:
CASE
WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now()
THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago')
WHEN datediff(now(), compare_date) = 1
THEN 'Yesterday'
WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now()
THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago')
ELSE concat(datediff(now(), compare_date),' days ago')
END
Based on a similar sample seen on the [MySQL Date and Time](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#c9500) manual pages |
For the mouse you can use [GPM][1].
I'm not sure off the top of my head for keyboard or joystick.
It probably wouldn't be too bad to read directly off there /dev files if need be.
Hope it helps,
Brian Gianforcaro
[1]: http://www.linuxjournal.com/article/4600 |
any issues with using log4net in a multi-threaded environment? |
|log4net| |
Just like the title, I'm wondering if anyone has any experience using log4net in a multi-threaded environment like asp.net. We are currently using log4net and I want to make sure we won't run into any issues. |
Are there any issues with using log4net in a multi-threaded environment? |
How to repeatedly merge branches in Mercurial |
|version-control|mercurial| |
We're using Mercurial where I work and I want to have a setup similar to how I used SVN:
* Trunk
* Tags
* Production
* Branches
Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'.
Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial? |
If Subversion with TortiseSVN is too complex - and it may be, since version control is a whole paradigm different from Open, Modify, Save - then you might start them off with a much simpler hand version control:
myDocument-20080908-beverlyd.doc
It's simple, easy to understand, and you can write a script that every night or week archives all the older versions so they really only see the latest version or two.
If someone wants to see differences, teach them diff.
-Adam |
I think [Redmine][1] can do some of what you're asking for.
[1]: http://www.redmine.org/ |
As mentioned in Arbash's Black Book, one of the most simple and straight forward ways to get a huge speedup is to keep a change list.
Instead of iterating through the entire cell grid each time, keep a copy of all the cells that you change.
This will narrow down the work you have to do on each iteration. |
Best to URL encode those, as they are clearly not supported in all web servers. Sometimes, even when there is a standard, not everyone follows it.
|
What is PI? The circumference of a circle divided by its diameter.
In computer graphics you can plot/draw a circle with its centre at 0,0 from a initial point x,y, the next point x',y' can be found using a simple formula:
x' = x + y / h : y' = y - x' / h
h is usually a power of 2 so that the divide can be done easily with a shift (or subtracting from the exponent on a double). h also wants to be the radius r of your circle. An easy start point would be x = r, y = 0, and then to count c the number of steps until x <= 0 to plot a quater of a circle. PI is 4 * c / r or PI is 4 * c / h
Recursion to any great depth, is usually impractical for a commercial program, but tail recursion allows an algorithm to be expressed recursively, while implemented as a loop. Recursive search algorithms can sometimes be implemented using a queue rather than the process's stack, the search has to backtrack from a deadend and take another path - these backtrack points can be put in a queue, and multiple processes can un-queue the points and try other paths. |
Datetime arithmetic with a string in Ruby |
|ruby|time|datetime| |
In Ruby, I'm trying to do the following.
def self.stats(since)
return Events.find(:all, :select => 'count(*) as this_count', :conditions => ['Date)event_date) >= ?', (Time.now - since)]).first.this_count
end
where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions? |
Try using [Chronic](http://chronic.rubyforge.org/) to parse the date strings into actual datetime objects. |
Two ideas:
(1) Many configurations are mostly empty space. Keep a linked list (not necessarily in order, that would take more time) of the live cells, and during an update, only update around the live cells (this is similar to your vague suggestion, OysterD :)
(2) Keep an extra array which stores the # of live cells in each row of 3 positions (left-center-right). Now when you compute the new dead/live value of a cell, you need only 4 read operations (top/bottom rows and the center-side positions), and 4 write operations (update the 3 affected row summary values, and the dead/live value of the new cell). This is a slight improvement from 8 reads and 1 write, assuming writes are no slower than reads. I'm guessing you might be able to be more clever with such configurations and arrive at an even better improvement along these lines. |
Pretty much the only characters not allowed in pathnames are # and ? as they signify the end of the path.
The uri rfc will have the definative answer:
http://www.ietf.org/rfc/rfc1738.txt
> Unsafe:
> Characters can be unsafe for a number of reasons. The space
> character is unsafe because significant spaces may disappear and
> insignificant spaces may be introduced when URLs are transcribed or
> typeset or subjected to the treatment of word-processing programs.
> The characters "<" and ">" are unsafe because they are used as the
> delimiters around URLs in free text; the quote mark (""") is used to
> delimit URLs in some systems. The character "#" is unsafe and should
> always be encoded because it is used in World Wide Web and in other
> systems to delimit a URL from a fragment/anchor identifier that might
> follow it. The character "%" is unsafe because it is used for
> encodings of other characters. Other characters are unsafe because
> gateways and other transport agents are known to sometimes modify
> such characters. These characters are "{", "}", "|", "\", "^", "~",
> "[", "]", and "`".
> All unsafe characters must always be encoded within a URL. For
> example, the character "#" must be encoded within URLs even in
> systems that do not normally deal with fragment or anchor
> identifiers, so that if the URL is copied into another system that
> does use them, it will not be necessary to change the URL encoding.
The answer is that they *should* be hex encoded, but knowing postel's law, most things will accept them verbatim. |
I'm posting the [OWASP Top 2007 abbreviated list][1] here so people don't have to look through to another link and in case the source goes down.
[Cross Site Scripting (XSS)][2]
--------------------------
- XSS flaws occur whenever an application takes user supplied data and sends it to a web browser without first validating or encoding that content. XSS allows attackers to execute script in the victim's browser which can hijack user sessions, deface web sites, possibly introduce worms, etc.
[Injection Flaws][3]
---------------
- Injection flaws, particularly SQL injection, are common in web applications. Injection occurs when user-supplied data is sent to an interpreter as part of a command or query. The attacker's hostile data tricks the interpreter into executing unintended commands or changing data.
[Malicious File Execution][4]
------------------------
- Code vulnerable to remote file inclusion (RFI) allows attackers to include hostile code and data, resulting in devastating attacks, such as total server compromise. Malicious file execution attacks affect PHP, XML and any framework which accepts filenames or files from users.
[Insecure Direct Object Reference][5]
--------------------------------
- A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. Attackers can manipulate those references to access other objects without authorization.
[Cross Site Request Forgery (CSRF)][6]
---------------------------------
- A CSRF attack forces a logged-on victim's browser to send a pre-authenticated request to a vulnerable web application, which then forces the victim's browser to perform a hostile action to the benefit of the attacker. CSRF can be as powerful as the web application that it attacks.
[Information Leakage and Improper Error Handling][7]
-----------------------------------------------
- Applications can unintentionally leak information about their configuration, internal workings, or violate privacy through a variety of application problems. Attackers use this weakness to steal sensitive data, or conduct more serious attacks.
[Broken Authentication and Session Management][8]
--------------------------------------------
- Account credentials and session tokens are often not properly protected. Attackers compromise passwords, keys, or authentication tokens to assume other users' identities.
[Insecure Cryptographic Storage][9]
------------------------------
- Web applications rarely use cryptographic functions properly to protect data and credentials. Attackers use weakly protected data to conduct identity theft and other crimes, such as credit card fraud.
[Insecure Communications][10]
-----------------------
- Applications frequently fail to encrypt network traffic when it is necessary to protect sensitive communications.
[Failure to Restrict URL Access][11]
------------------------------
- Frequently, an application only protects sensitive functionality by preventing the display of links or URLs to unauthorized users. Attackers can use this weakness to access and perform unauthorized operations by accessing those URLs directly.
[The Open Web Application Security Project][12]
-Adam
[1]: http://www.owasp.org/index.php/Top_10_2007
[2]: http://www.owasp.org/index.php/Top_10_2007-A1
[3]: http://www.owasp.org/index.php/Top_10_2007-A2
[4]: http://www.owasp.org/index.php/Top_10_2007-A3
[5]: http://www.owasp.org/index.php/Top_10_2007-A4
[6]: http://www.owasp.org/index.php/Top_10_2007-A5
[7]: http://www.owasp.org/index.php/Top_10_2007-A6
[8]: http://www.owasp.org/index.php/Top_10_2007-A7
[9]: http://www.owasp.org/index.php/Top_10_2007-A8
[10]: http://www.owasp.org/index.php/Top_10_2007-A9
[11]: http://www.owasp.org/index.php/Top_10_2007-A10
[12]: http://www.owasp.org/index.php/OWASP:About |
I generally prefer to use mocks because of Expectations. When you call a method on a stub that returns a value, it typically just gives you back a value. But when you call a method on a mock, not only does it return a value, it also enforces the expectation that you set up that the method was even called in the first place. In other words, if you set up an expectation and then don't call that method, an exception gets thrown. When you set an expectation, you are essentially saying "If this method doesn't get called, something went wrong." And the opposite is true, if you call a method on a mock and did not set an expectation, it will throw an exception, essentially saying "Hey, what are you doing calling this method when you didn't expect it."
Sometimes you don't want expectations on every method you're calling, so some mocking frameworks will allow "partial" mocks that are like mock/stub hybrids, in that only the expectations you set are enforced, and every other method call is treated more like a stub in that it just returns a value.
One valid place to use stubs I can think of off the top, though, is when you are introducing testing into legacy code. Sometimes it's just easier to make a stub by subclassing the class you are testing than refactoring everything to make mocking easy or even possible.
And to this...
> Avoid using mocks always because they make tests brittle. Your tests now have intricate knowledge of the methods called by the implementation, if the mocked interface changes... your tests break. So use your best judgment..<
...I say if my interface changes, my tests had better break. Because the whole point of unit tests is that they accurately test my code as it exists right now. |
prop and exception are my favorites. |
There's plenty of code snippets within Visual Studio for basic programming structure but I wouldn't necessarily rate one higher than another.
I would definitely say the best ones are the custom snippets you define yourself to accomplish more specific tasks that you may find yourself using on a regular basis. Definitely a big time saver.
A fairly basic intro to creating custom snippets can be found at [http://www.15seconds.com/issue/080724.htm][1] to help with this.
[1]: http://www.15seconds.com/issue/080724.htm |
I saw the onex command, but I couldn't find a break command. The two commands below don't seem to work.
onex break
onex b |
It's not that duck typing is more productive than static typing as much as it is simply different. With static typing you always have to worry that your data is the correct type and in Java it shows up through casting to the right type. With duck typing the type doesn't matter as long as it has the right method, so it really just eliminates a lot of the hassle of casting and conversions between types. |
There is currently no way to compile DirectX code to directly target Linux. You would build your application like you normally would, then run it using a compatibility layer like Wine/Cedega. |
I have created a small static util class just for that purpose
Below code should read like an English sentence.
public static bool DataSetIsEmpty(DataSet ds)
{
return !DataTableExists(ds) && !DataRowExists(ds.Tables[0].Rows);
}
public static bool DataTableExists(DataSet ds)
{
return ds.Tables != null && ds.Tables.Count > 0;
}
public static bool DataRowExists(DataRowCollection rows)
{
return rows != null && rows.Count > 0;
}
I would just put something like below code and be done with it.
Writing a **readable code** does count.
if (DataAccessUtil.DataSetIsEmpty(ds)) {
return null;
}
|
I have used many many IDE's and in most cases to me it breaks down to personal preferences. Sometimes the language specific ones have some addins/addons/features that are nice but unless they are things you can not live without you should go with what is most comfortable for you.
I would think that if you are comfortable with the multi-language IDE it would be better to stick with that one. This way you dont have to memorize multiple IDE layouts, keyboard shortcuts etc. |
#Lambda Expressions
Func<int, int, int> add = (a, b) => (a + b);
#Obscure String Formats
Console.WriteLine("{0:D10}", 2); // 0000000002
Dictionary<string, string> dict = new Dictionary<string, string> {
{"David", "C#"},
{"Johann", "Perl"},
{"Morgan", "Python"}
};
Console.WriteLine( "{0,10} {1, 10}", "Programmer", "Language" );
Console.WriteLine( "-".PadRight( 21, '-' ) );
foreach (string key in dict.Keys)
{
Console.WriteLine( "{0, 10} {1, 10}", key, dict[key] );
} |
**Lambda Expressions**
Func<int, int, int> add = (a, b) => (a + b);
**Obscure String Formats**
Console.WriteLine("{0:D10}", 2); // 0000000002
Dictionary<string, string> dict = new Dictionary<string, string> {
{"David", "C#"},
{"Johann", "Perl"},
{"Morgan", "Python"}
};
Console.WriteLine( "{0,10} {1, 10}", "Programmer", "Language" );
Console.WriteLine( "-".PadRight( 21, '-' ) );
foreach (string key in dict.Keys)
{
Console.WriteLine( "{0, 10} {1, 10}", key, dict[key] );
} |
One thing to watch out for at things that expire (I think httpContext does), if you are using it for operations that are "fire and forget" remember that all of a sudden if the asp.net cleanup code runs before your operation is done, you won't be able to access certain information. |
Does you app allow for linked table updates or does it go through forms? Sounds like your idea of using a centralized user with distinct roles is the way to go. Yes, you could change users but I that may introduce more coding and once you start adding more and more code other solutions (stored procedures, etc) may sound more inviting. |
Not to repeat an answer, but I think I can add a bit more.
[Slickedit][1] is an excellent IDE.
It supports large code-bases well without slowing down or spending all its time indexing. (This is a problem I had with eclipse's cdt). Slickedit's speed is probably the nicest thing about it, actually.<br>
The code completion works well and there are a large amount of options for things like automatic formatting, beautification and refactoring.<br>
It does have integrated debugging.<br>
It has plug-in support and fairly active community creating them.<br>
In theory, you should be able to integrate well with people doing the traditional makefile stuff, as it allows you to create a project directly from one, but that didn't work as smoothly as I would have liked when I tried it.<br>
In addition to Linux, there are Mac and Windows versions of it, should you need them.<br>
[1]: http://www.slickedit.com |
How do you programmatically change the tab order in a Win32 dialog? |
|winapi|dialog| |
I saw this functionality in older versions of VS.Net (2003 I think). It may still exist in current versions, but I haven't encountered it. Seems that files with the same name, even in different directories confuse VS.Net, and it ends up setting a break point in a file with the same name. May only happen if the classes in the file both have the same name also. So much for namespaces I guess.
You also may want to check your build configuration to make sure that all the projects are in fact building in debug mode. I know I've been caught a couple times when the configuration got changed somehow for the solution, and some projects weren't compiling in debug mode. |
Restriction.In definately creates a subquery with whatever criteria you pass to the .In() method, but not sure what InG() does. never seen it. |
> hg: unknown command 'view'
(Maybe I need to install something - but it's not native, nonetheless).
There is one "native" application out there, but it's not especially user-friendly. In fact, I'd go as far as saying that it's harder to use than the command line.
There was some talk a year or so ago about a version of SCPlugin, which puts badges on icons in the Finder that are under SVN control, and gives you a contextual menu (very much like TortoiseSVN on windows), but that seems to have collapsed.
I have been planning to create a mercurial "clone" of Versions (I asked them if they would consider doing a version of it for DVCS, and they said no). |
While performance is an issue, I think modern database designs have made it much less of an issue for small files.
Performance aside, it also depends on just how tightly-coupled the data is. If the file contains data that is closely related to the fields of the database, then it conceptually belongs close to it and may be stored in a blob. If it contains information which could potentially relate to multiple records or may have some use outside of the context of the database, then it belongs outside. For example, an image on a web page is fetched on a separate request from the page that links to it, so it may belong outside (depending on the specific design and security considerations).
Our compromise, and I don't promise it's the best, has been to store smallish XML files in the database but images and other files outside it. |