instruction stringlengths 0 30k ⌀ |
|---|
To get a rough estimate, you could always run `find . -type f -exec cat {} \; | wc -l` in the project directory if you're using Mac OS X. |
Zoom for a form in C# |
|c#|vba| |
Is there an easy way to set the zoom level for a form in C#? In VBA there was a zoom property of the form. |
Zoom for a windows form in C# |
|c#|winforms|vba| |
Is there an easy way to set the zoom level for a windows form in C#? In VBA there was a zoom property of the form. |
Stack Overflow
This Week in Tech
Security Now
As I learn more about programming I'll add more to my list.
Adding 43 folders now. |
<p>A "race condition" exists when multithreaded (or otherwise parallel) code that would access a shared resource could do so in such as way as to cause to unexpected results.</p>
Take this example:
<pre><code>
for ( int i = 0; i < 10000000; i++ )
{
x = x + 1;
}
</code></pre>
<p>If you had 5 threads executing this code at once, the value of x WOULD NOT end up being 50,000,000. It would in fact vary with each run.</p>
<p>This is because, in order for each thread to increment the value of x, they have to do the following: (simplified, obviously)</p>
<pre>
Retrieve the value of x
Add 1 to the value of x
Store the value of x
</pre>
<p>Any thread can be at any step in this process at any time, and they can step on each other when a shared resource is involved. The state of x can be changed by another thread during the time between x being read and when it is written back.</p>
<p>Let's say a thread retrieves the value of x, but hasn't stored it yet. Another thread can also retrieve the <b>same</b> value of x and then they would both be storing the <b>same</b> value (x+1) back!</p>
Example:
<pre>
Thread 1: reads x, value is 7
Thread 1: add 1 to x, value is now 8
Thread 2: reads x, <b>value is 7</b>
Thread 1: stores 8 in x
Thread 2: adds 1 to x, value is now 8
Thread 2: <b>stores 8 in x</b>
</pre>
<p>Race conditions can be avoided by employing some sort of <b>locking</b> mechanism before the code that accesses the shared resource:
<pre><code>
for ( int i = 0; i < 10000000; i++ )
{
//lock x
x = x + 1;
//unlock x
}
</code></pre>
<p>Here, the answer comes out as 50,000,000 every time.</p>
<p>For more on locking, search for: mutex, semaphore, critical section, shared resource.</p>
|
Don't you just want:
",".join(l)
Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:
[http://docs.python.org/lib/module-csv.html][1]
[1]: http://docs.python.org/lib/module-csv.html |
Maybe something like this?
const std::vector<mydata>& getData()
{
return _myPrivateData;
} |
Maybe something like this?
const std::vector<mydata>& getData()
{
return _myPrivateData;
}
The benefit here is that it's very, very simple, and as safe as you getin C++. You can cast this, like RobQ suggests, but there's nothing you can do that would prevent someone from that if you're not copying. Here, you would have to use `const_cast`, which is pretty easy to spot if you're looking for it.
Iterators, alternatively, might get you pretty much the same thing, but it's more complicated. The only added benefit of using iterators here (that I can think of) is that you can have better encapsulation. |
How can I determine whether a given date is in Daylight Saving Time for a given timezone in .NET 2.0? |
|.net-2.0|timezone|medium-trust| |
I'm on .NET 2.0, running under Medium Trust (so [TimeZoneInfo][1] and the Registry are not allowed options). I'm asking the user for two dates and a time zone, and would really love to be able to automatically determine whether I need to adjust the time zone for DST.
This probably isn't even a valid scenario unless I have some _very_ robust support, a la [TimeZoneInfo][1], to differentiate between all of the different varieties of Time Zones in the first place.
[1]: http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx |
What you want is read-only access without copying the entire blob of data. You have a couple options.
Firstly, you could just return a const refererence to whatever your data container is, like suggested above:
const std::vector<T>& getData() { return mData; }
This has the disadvantage of concreteness: you can't change how you store the data internally without changing the interface of your class.
Secondly, you can return const-ed pointers to the actual data:
const T* getDataAt(size_t index)
{
return &mData[index];
}
This is a bit nicer, but also requires that you provide a getNumItems call, and protect against out-of-bounds indices. Also, the const-ness of your pointers is easily cast away, and your data is now read-write.
Another option is to provide a pair of iterators, which is a bit more complex. This has the same advantages of pointers, as well as not (necessarily) needing to provide a getNumItems call, and there's considerably more work involved to strip the iterators of their const-ness.
Probably the easiest way to manage this is by using a Boost Range:
typedef vector<T>::const_iterator range_iterator_type;
boost::iterator_range< range_iterator_type >& getDataRange()
{
return boost::iterator_range(mData.begin(), mData.end());
}
This has the advantages of ranges being composable, filterable, etc, as you can see on the [website][1].
[1]: http://www.boost.org/doc/libs/1_36_0/libs/range/index.html
|
With a six word character password, he may have been brute forced. That is more likely than his ftp being intercepted, but it could be that too. |
With a six word character password, he may have been brute forced. That is more likely than his ftp being intercepted, but it could be that too.
Start with a stronger password. (8 characters is still fairly weak)
See if this link to an internet [security blog][1] is helpful.
[1]: http://blog.modsecurity.org/2008/01/is-your-website.html |
> And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.
If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection.
If you do the connection right in your script, not in a called file, do you get the same error? |
Try and gather as much information as you can. See if the host can give you a log showing all the FTP connections that were made to your account. You can use those to see if it was even an FTP connection that was used to make the change and possibly get an IP address.
If you're using a prepacked software like Wordpress, Drupal, or anything else that you didn't code there may be vulnerabilities in upload code that allows for this sort of modification. If it is custom built, double check any places where you allow users to upload files or modify existing files.
The second thing would be to take a dump of the site as-is and check everything for other modifications. It may just be one single modification they made, but if they got in via FTP who knows what else is up there.
Revert your site back to a known good status and, if need be, upgrade to the latest version.
There is a level of return you have to take into account too. Is the damage worth trying to track the person down or is this something where you just live and learn and use stronger passwords? |
Is the site just plain static HTML? i.e. he hasn't managed to code himself an upload page that permits anyone driving by to upload compromised scripts/pages?
Why not ask webhost4life if they have any FTP logs available and report the issue to them. You never know, they may be quite receptive and find out for you exactly what happened?
I work for a shared hoster and we always welcome reports such as these and can usually pinpoint the exact vector of attack based and advise as to where the customer went wrong. |
I use pico or nano as my "casual" text editor in Linux/Solaris/etc. It's easy to come to grips with, and whilst you lose a couple of rows of text to the menu, at least it's easy to see how to exit, etc.
You can even extend nano, I think, and add syntax highlighting. |
Since python is installed on nearly every non-Windows OS by default now, the only thing you really need to make sure of is that all of the non-standard libraries you use are installed.
Having said that, it is possible to build executables that include the python interpreter, and any libraries you use. This is likely to create a large executable, however.
MacOS X even includes support in the Xcode IDE for creating full standalone GUI apps. These can be run by any user running OS X. |
One advantage of both @Shog9's and @RichQ's solutions is that they de-couple the client from the collection implementation.
If you decide th change your collection type to something else, your clients will still work. |
Traditionally, JS was intended for short, quick-running pieces of code. If you had major calculations going on, you did it on a server - the idea of a JS+HTML *app* that ran in your browser for long periods of time doing non-trivial things was absurd.
Of course, now we have that. But, it'll take a bit for browsers to catch up - most of them have been designed around a single-threaded model, and changing that is not easy. Google Gears side-steps a lot of potential problems by requiring that background execution is isolated - no changing the DOM (since that's not thread-safe), no accessing objects created by the main thread (ditto). While restrictive, this will likely be the most practical design for the near future, both because it simplifies the design of the browser, and because it reduces the risk involved in allowing inexperienced JS coders mess around with threads... |
Traditionally, JS was intended for short, quick-running pieces of code. If you had major calculations going on, you did it on a server - the idea of a JS+HTML *app* that ran in your browser for long periods of time doing non-trivial things was absurd.
Of course, now we have that. But, it'll take a bit for browsers to catch up - most of them have been designed around a single-threaded model, and changing that is not easy. Google Gears side-steps a lot of potential problems by requiring that background execution is isolated - no changing the DOM (since that's not thread-safe), no accessing objects created by the main thread (ditto). While restrictive, this will likely be the most practical design for the near future, both because it simplifies the design of the browser, and because it reduces the risk involved in allowing inexperienced JS coders mess around with threads...
[@marcio][1]:
> Why is that a reason not to implement multi-threading in Javascript? Programmers can do whatever they want with the tools they have.
So then, let's not give them tools that are so easy to **misuse** that every other website i open ends up crashing my browser. A naive implementation of this would bring you straight into the territory that caused MS so many headaches during IE7 development: add-on authors played fast and loose with the threading model, resulting in hidden bugs that became evident when object lifecycles changed on the primary thread. BAD. If you're writing multi-threaded ActiveX add-ons for IE, i guess it comes with the territory; doesn't mean it needs to go any further than that.
[1]: http://stackoverflow.com/questions/39879/why-doesnt-javascript-support-multithreading#40058 |
You'll have to hide the last value in a HiddenField or ViewState or somewhere like that... |
If you need to change images to the next in the sequence if you hit the F5 or similar refresh button, then you need to store the last image id or something in a server-side storage, or in a cookie. Use a Session variable or similar. |
Is this an intranet environment? If so they shouldn't have to login anyways. If sharepoint is setup using "Integrated Authentication" and the site is listed as a trusted site in IE, the browser will use there network cred for auto login. This can be setup on [firefox][1] as well.
[1]: http://www.cauldwell.net/patrick/blog/CommentView,guid,c7f1e799-c4ae-4758-9de7-5c3e7a16f3da.aspx |
I've always wondered how costly it is to *always* assume that invoke is required...
private void OnCoolEvent(CoolObjectEventArgs e)
{
BeginInvoke((o,e) => /*do work here*/, new object[] {this, e});
} |
I've always wondered how costly it is to *always* assume that invoke is required...
private void OnCoolEvent(CoolObjectEventArgs e)
{
BeginInvoke((o,e) => /*do work here*/,this, e);
} |
Doing anything with RTF is pretty difficult unless you're using the windows forms. As stated above, using forms is the easiest way to go.
You could write something yourself, but the RTF spec is pretty complicated.
http://www.biblioscape.com/rtf15_spec.htm
Or you could use a conversion DLL / ActiveX object of which there is a large number available.
http://www.sautinsoft.com/
Or - If you're doing this from Linux, there are also tools available. A cursory glance throws up UnRTF
http://www.gnu.org/software/unrtf/unrtf.html
I haven't included stuff to turn text back to RTF because I think the RTF specification treats and formats text correctly. |
[jQuery inline search plugin][1]
[1]: http://vision-media.ca/resources/jquery/jquery-inline-search-plugin |
If I understand your question, you are asking if it is possible to allow a user to type in a query that will search the text of page they are on?
You can certainly do that. I would suggest looking into one of the javascript libraries, [jQuery][1] is my library of choice, for your functionality. It has a rich selector syntax that allows you to search various parts of the page easily and without worrying about cross-browser coding yourself.
[1]: http://jquery.com |
Are you sure you need do this mail queuing yourself?
Just deliver all mail to the local machine's mail transfer agent (sendmail...) and let that take care of the queuing and sending. After all, that's what was designed for.
In other words: don't worry about it! |
Use the read(1) command to read one line at a time from standard input, then output the line prepended with the date in the format of your choosing using date(1).
$ cat timestamp
#!/bin/sh
while read line
do
echo `date` $line
done
$ cat somefile.txt | ./timestamp
|
Python is easy for new developers to learn. You don't get tangled up in the specifics of memory management and type definition. [Dive Into Python][1] is a good beginners guide to python programming. When my sister wanted to learn programing I pointed her to the "Head Start" line of books which she found very easy to read and understand. I find it's hard to just start teaching someone because you don't have a lexicon to use with them. First have him read a few books or tutorials and ask you for questions. From there you can assign projects and grade them. I find it hard to teach programming because I learned it over nearly 15 years of tinkering around.
[1]: http://diveintopython.org/ "Dive Into Python" |
My regex is matching too much. How do I make it stop? |
|regex| |
I have to second the comment by @Phil Bennett as I try to approach these integration tests with a rollback solution.
I have a very detailed post about integration testing your data access layer [here][1]
I show not only the sample data access class, base class, and sample DB transaction fixture class, but a full CRUD integration test w/ sample data shown. With this approach you don't need multiple test databases as you can control the data going in with each test and after the test is complete the transactions are all rolledback so your DB is clean.
About unit testing business logic inside your app, I would also second the comments by @Phil and @Mark because if you mock out all the dependencies your business object has, it becomes very simple to test your application logic one entity at a time ;)
Edit: So are you looking for one huge integration test that will verify everything from logic pre-data base / stored procedure run w/ logic and finally a verification on the way back? If so you could break this out into 2 steps:
- 1 - Unit test the logic that happens before the data is pushed
into your data access code. For
example, if you have some code that
calculates some numbers based on
some properties -- write a test that
only checks to see if the logic for
this 1 function does what you asked
it to do. Mock out any dependancy
on the data access class so you can
ignore it for this test of the
application logic alone.
- 2 - Integration test the logic that happens once you take your
manipulated data (from the previous
method we unit tested) and call the
appropriate stored procedure. Do
this inside a data specific testing
class so you can rollback after it's
completed. After your stored
procedure has run, do a query
against the database to get your
object now that we have done some
logic against the data and verify it
has the values you expected
I(post-stored procedure logic /etc )
[1]: http://stackoverflow.com/questions/12374/has-anyone-had-any-success-in-unit-testing-sql-stored-procedures#25204 |
I have to second the comment by @Phil Bennett as I try to approach these integration tests with a rollback solution.
I have a very detailed post about integration testing your data access layer [here][1]
I show not only the sample data access class, base class, and sample DB transaction fixture class, but a full CRUD integration test w/ sample data shown. With this approach you don't need multiple test databases as you can control the data going in with each test and after the test is complete the transactions are all rolledback so your DB is clean.
About unit testing business logic inside your app, I would also second the comments by @Phil and @Mark because if you mock out all the dependencies your business object has, it becomes very simple to test your application logic one entity at a time ;)
Edit: So are you looking for one huge integration test that will verify everything from logic pre-data base / stored procedure run w/ logic and finally a verification on the way back? If so you could break this out into 2 steps:
- 1 - Unit test the logic that happens before the data is pushed
into your data access code. For
example, if you have some code that
calculates some numbers based on
some properties -- write a test that
only checks to see if the logic for
this 1 function does what you asked
it to do. Mock out any dependancy
on the data access class so you can
ignore it for this test of the
application logic alone.
- 2 - Integration test the logic that happens once you take your
manipulated data (from the previous
method we unit tested) and call the
appropriate stored procedure. Do
this inside a data specific testing
class so you can rollback after it's
completed. After your stored
procedure has run, do a query
against the database to get your
object now that we have done some
logic against the data and verify it
has the values you expected
I(post-stored procedure logic /etc )
If you need an entry in your database for the stored procedure to run, simply insert that data before you run the sproc that has your logic inside it. For example, if you have a product that you need to test, it might require a supplier and category entry to insert so before you insert your product do a quick and dirty insert for a supplier and category so your product insert works as planned.
[1]: http://stackoverflow.com/questions/12374/has-anyone-had-any-success-in-unit-testing-sql-stored-procedures#25204 |
int num = 1;
if(Session["ImageNumber"] != null)
{
num = Convert.ToInt32(Session["ImageNumber"]) + 1;
}
Session["ImageNumber"] = num; |
You can store data in your page's `ViewState` dictionary
So in your Page_Load you could write something like...
var lastPicNum = (int)ViewState["lastPic"];
lastPicNum++;
MainPic.ImageUrl = string.Format("{0}.jpg", lastPicNum);
ViewState["lastPic"] = lastPicNum;
you should get the idea. |
You can store data in your page's [`ViewState`][1] dictionary
So in your Page_Load you could write something like...
var lastPicNum = (int)ViewState["lastPic"];
lastPicNum++;
MainPic.ImageUrl = string.Format("~/Images/{0}.jpg", lastPicNum);
ViewState["lastPic"] = lastPicNum;
you should get the idea.
And if you're programming ASP.NET and still does not understands how ViewState and web forms work, you should read [this MSDN article][2]
Understanding ViewState from the beginning will help with a lot of ASP.NET gotchas as well.
[1]: http://msdn.microsoft.com/en-us/library/4yfdwycw(VS.71).aspx
[2]: http://msdn.microsoft.com/en-us/library/ms972976.aspx |
It depends on how long you want it to persist (remember) the last viewed value. My preferred choice would be the SESSION. |
I do a lot of simplifying of configuration. That is I wrap the generation/management of configuration values inside a UI. The primary benefit is I can control work flow and presentation to make it simpler for non-techie users to configure apps/sites/services. |
Well, if you can invoke the tools programmatically without the command line, that would probably be your best option. Otherwise, you could potentially execute the command line tool via a user that has absolutely no access to do anything (except perhaps a single directory that they can't do any harm with)... though that may end up breaking the tool, depending on what the tool does.
Just note, I have never had to face this problem, because I have never actually had to invoke a command line tool from an externally facing application where the tool requires input from the user. |
I have one setup using the Ruby Tinder library that I send to a campfire room, if anyone wants the script I can post or send the code to you.
Other common ones I've seen are posts to bug tracking systems and email notifications. |
I must say i find the other question very interesting. There is one serious problem though - parse this: 08/07/06! If you limit yourself on a subset of expected formats, you could probably solve problem by playing around with regexps, you could build up bunch of expected patterns, and then break Strings on spaces or whatever, and match part by part. |
Flex and ADO.NET Data Services...anyone done it? |
|apache-flex|ado.net| |
Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications? If so, any success stories or tragedies to avoid? If you did use it, how did you handle security? |
In Python, there is a difference between functions and bound methods.
>>> def foo():
... print "foo"
...
>>> class A:
... def bar( self ):
... print "bar"
...
>>> a = A()
>>> foo
<function foo at 0x00A98D70>
>>> a.bar
<bound method A.bar of <__main__.A instance at 0x00A9BC88>>
>>>
Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.
Callables that are properties of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:
>>> def fooFighters( self ):
... print "fooFighters"
...
>>> A.fooFighters = fooFighters
>>> a2 = A()
>>> a2.fooFighters
<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>
>>> a2.fooFighters()
fooFighters
Previously defined instances are updated as well (as long as they haven't overridden the property themselves):
>>> a.fooFighters()
fooFighters
The problem comes when you want to attach a method to a single instance:
>>> def barFighters( self ):
... print "barFighters"
...
>>> a.barFighters = barFighters
>>> a.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: barFighters() takes exactly 1 argument (0 given)
The function is not automatically bound when it's assigned as a property:
>>> a.barFighters
<function barFighters at 0x00A98EF0>
To bind it, we can use the [instancemethod function in the new module](http://www.python.org/doc/lib/module-new.html):
>>> import new
>>> a.barFighters = new.instancemethod( barFighters, a, A )
>>> a.barFighters
<bound method A.barFighters of <__main__.A instance at 0x00A9BC88>>
>>> a.barFighters()
barFighters
This time other instances of the class have not been affected:
>>> a2.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'barFighters'
More information can be found by reading about [descriptors](http://users.rcn.com/python/download/Descriptor.htm) and [metaclass](http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html) [programming](http://www.gnosis.cx/publish/programming/metaclass_2.html). |
I've heard good things about [clang static analyzer][1], which IIRC uses LLVM as it's backend. If that's implemented on your platform, that might be a good choice.
From what I understand, it does a bit more than just syntax analysis. "Automatic Bug Finding", for instance.
[1]: http://clang.llvm.org/StaticAnalysis.html |
I assume you're trying to make the command interface as forgiving as possible. If this is the case, I suggest you use an algorithm similar to this:
1. Read in the string
- Split the string into tokens
- Use a dictionary to convert synonyms to a common form
- For example, convert "hit", "punch", "strike", and "kick" all to "hit"
- Perform actions on an unordered, inclusive base
- **Unordered** - "punch the monkey in the face" is the same thing as "the face in the monkey punch"
- **Inclusive** - If the command is supposed to be "punch the monkey in the face" and they supply "punch monkey", you should check how many commands this matches. If only one command, do this action. It might even be a good idea to have command priorities, and even if there were even matches, it would perform the top action. |
In our databases we use an enum that ensures we pass it either TRUE or FALSE. If you do it either of the first two ways it is too easy to either start adding new meaning to the integer without going through a proper design, or ending up with that char field having Y, y, N, n, T, t, F, f values and having to remember which section of code uses which table and which version of true it is using. |
I found [this][1] link useful.
[1]: http://articles.techrepublic.com.com/5100-10878_11-5229553.html |
Monitoring files - how to know when a file is complete |
|.net|filesystems| |
We have several .NET applications that monitor a directory for new files, using FileSystemWatcher. The files are copied from another location, uploaded via FTP, etc. When they come in, the files are processed in one way or another. However, one problem that I have never seen a satisfactory answer for is: for large files, how does one know when the files being monitored are still being written to? Obviously, we need to wait until the files are complete and closed before we begin processing them. The event args in the FileSystemWatcher events do not seem to address this.
|
Have discovered that this only occurs when the script is run on a different drive to the one where the EXE is located. As a work around for this I have simply moved the scripts execution.
Apparently the DLL relates to SSL, which isn't relevant to what I'm doing, so this is a suitable workaround. I'm guessing that the problem is caused by changes in the EXE for how it determines relative paths (unlikley as nothing (AFAICT) has changed). Or the %PATH% environmental variable has changed (more likely).
Hope this helps someone in the future. |
Unless the developers you are working with are familiar with MVC pattern I wouldn't. At a minimum I'd talk with them first before making such a big change. |
I believe UIApplication has an openURL method, that will perform the normal iPhone magical URL reinterpretation. so
[someUIApplication openURL:[[NSURL alloc] initWithString: @"http://maps.google.com/maps?g=London"]]
should invoke the Google maps app.
(This info is available from the unoffical SDK documentation, so no Apple NDA required). I refuse to confirm if I checked that the same methods exist in UIApplication for the formal SDK). |
How to know if a line intersects a plane in C#? - Basic 2D geometry |
|c#|2d| |
my school maths are very rusty and I think this is a good opportunity to take advance of this community :D
I have two points (a line) and a rectangle, I would like to know how to calculate if the line intersects the rectangle, my first approach had so many "if" statements that the compiler sent me a link to this site.
Thanks for your time! |
Sacha Barber has a great series of articles on WPF for Beginners over at Codeproject that you can check out.
- [An Introduction to the WPF Layout System][1]
- [An introduction into XAML / code and WPF resources][2]
- [An introduction into RoutedEvents / RoutedCommands][3]
- [An introduction into WPF Dependancy Properties][4]
- [An introduction into WPF Styles And Templates][5]
[1]: http://www.codeproject.com/KB/WPF/BeginWPF1.aspx
[2]: http://www.codeproject.com/KB/WPF/BeginWPF2.aspx
[3]: http://www.codeproject.com/KB/WPF/BeginWPF3.aspx
[4]: http://www.codeproject.com/KB/WPF/BeginWPF4.aspx
[5]: http://www.codeproject.com/KB/WPF/BeginWPF6.aspx |
I have to second the comment by @Phil Bennett as I try to approach these integration tests with a rollback solution.
I have a very detailed post about integration testing your data access layer [here][1]
I show not only the sample data access class, base class, and sample DB transaction fixture class, but a full CRUD integration test w/ sample data shown. With this approach you don't need multiple test databases as you can control the data going in with each test and after the test is complete the transactions are all rolledback so your DB is clean.
About unit testing business logic inside your app, I would also second the comments by @Phil and @Mark because if you mock out all the dependencies your business object has, it becomes very simple to test your application logic one entity at a time ;)
Edit: So are you looking for one huge integration test that will verify everything from logic pre-data base / stored procedure run w/ logic and finally a verification on the way back? If so you could break this out into 2 steps:
- 1 - Unit test the logic that happens before the data is pushed
into your data access code. For
example, if you have some code that
calculates some numbers based on
some properties -- write a test that
only checks to see if the logic for
this 1 function does what you asked
it to do. Mock out any dependancy
on the data access class so you can
ignore it for this test of the
application logic alone.
- 2 - Integration test the logic that happens once you take your
manipulated data (from the previous
method we unit tested) and call the
appropriate stored procedure. Do
this inside a data specific testing
class so you can rollback after it's
completed. After your stored
procedure has run, do a query
against the database to get your
object now that we have done some
logic against the data and verify it
has the values you expected
(post-stored procedure logic /etc )
If you need an entry in your database for the stored procedure to run, simply insert that data before you run the sproc that has your logic inside it. For example, if you have a product that you need to test, it might require a supplier and category entry to insert so before you insert your product do a quick and dirty insert for a supplier and category so your product insert works as planned.
[1]: http://stackoverflow.com/questions/12374/has-anyone-had-any-success-in-unit-testing-sql-stored-procedures#25204 |
Any way to have an ActionScript 3 (Flex/AIR) project print to standard output? |
|apache-flex|flash|actionscript-3|adobe| |
Is there any way to have a binary compiled from an ActionScript 3 project print stuff to *stdout* when executed?
From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe.
Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality? |
Struct like objects in Java |
I like Justin's suggestion, but I'll add to it: this solution is great for learning a language. If you don't rely on something like code-completion, then it forces you to learn the language better. (If you are working with something with a huge API, like Java or Cocoa, then you'll want the code completion, however!)
It's also language-agnostic, and in the case of an interpreted language, particularly one that has an interactive interpreter, you'll probably spend just as much time in the shell/interpreter typing in commands. Even in a large-ish python project, I still work in an editor and 4 or 5 terminal windows.
So, the trick is more about getting an editor which works for you. I'm not about to suggest one, as that's heading towards evangelism! |
Bringing Window to the Front in C# using Win32 API |
|c#|winapi| |
I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus).
What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not consistenly work.
What is the best way to go about this? Any thoughts? |
SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail.
> The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window
Try capturing the focus with [SetCapture](http://msdn.microsoft.com/en-us/library/ms646262.aspx) prior to making the call. Also look into different ways of bringing the window to the front: SetForeGroundWindow, SetActiveWindow, even simulating a mouse click can do this. |
Reverse DNS in Ruby? |
|ruby|sockets|dns|nslookup| |
I'm in an environment with a lot of computers that haven't been
properly inventoried. Basically, no one knows which IP goes with which
mac address and which hostname. So I wrote the following:
# This script goes down the entire IP range and attempts to
# retrieve the Hostname and mac address and outputs them
# into a file. Yay!
require "socket"
TwoOctets = "10.26"
def computer_exists?(computerip)
system("ping -c 1 -W 1 #{computerip}")
end
def append_to_file(line)
file = File.open("output.txt", "a")
file.puts(line)
file.close
end
def getInfo(current_ip)
begin
if computer_exists?(current_ip)
arp_output = `arp -v #{current_ip}`
mac_addr = arp_output.to_s.match(/..:..:..:..:..:../)
host_name = Socket.gethostbyname(current_ip)
append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n")
end
rescue SocketError => mySocketError
append_to_file("unknown - #{current_ip} - #{mac_addr}")
end
end
(6..8).each do |i|
case i
when 6
for j in (1..190)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 7
for j in (1..255)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 8
for j in (1..52)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
end
end
Everything works except it does not find a Reverse DNS.
Sample output that I'm getting is this:
10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F
10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3
10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2
If I do `nslookup 10.26.6.12` then I get the correct reverse DNS so
that shows that my machine is seeing the dns server.
I have tried Socket.gethostbyname, gethostbyaddr, but it doesn't work :
(
Any guidance will be much appreciated. Thanks! |
<p>A "race condition" exists when multithreaded (or otherwise parallel) code that would access a shared resource could do so in such as way as to cause unexpected results.</p>
Take this example:
<pre><code>
for ( int i = 0; i < 10000000; i++ )
{
x = x + 1;
}
</code></pre>
<p>If you had 5 threads executing this code at once, the value of x WOULD NOT end up being 50,000,000. It would in fact vary with each run.</p>
<p>This is because, in order for each thread to increment the value of x, they have to do the following: (simplified, obviously)</p>
<pre>
Retrieve the value of x
Add 1 to the value of x
Store the value of x
</pre>
<p>Any thread can be at any step in this process at any time, and they can step on each other when a shared resource is involved. The state of x can be changed by another thread during the time between x is being read and when it is written back.</p>
<p>Let's say a thread retrieves the value of x, but hasn't stored it yet. Another thread can also retrieve the <b>same</b> value of x (because no thread has changed it yet) and then they would both be storing the <b>same</b> value (x+1) back in x!</p>
Example:
<pre>
Thread 1: reads x, value is 7
Thread 1: add 1 to x, value is now 8
Thread 2: reads x, <b>value is 7</b>
Thread 1: stores 8 in x
Thread 2: adds 1 to x, value is now 8
Thread 2: <b>stores 8 in x</b>
</pre>
<p>Race conditions can be avoided by employing some sort of <b>locking</b> mechanism before the code that accesses the shared resource:
<pre><code>
for ( int i = 0; i < 10000000; i++ )
{
//lock x
x = x + 1;
//unlock x
}
</code></pre>
<p>Here, the answer comes out as 50,000,000 every time.</p>
<p>For more on locking, search for: mutex, semaphore, critical section, shared resource.</p>
|
You've probably got the right code, but you also need to add CODE_ANALYSIS as a precompiler defined symbol in the project properties. I think those SuppressMessage attributes are only left in the compiled binaries if CODE_ANALYSIS is defined. |
Excluding FxCop rule in source. |
|fxcop|initializecomponent|suppression| |
In a project I'm working on FxCop shows me lots of (and I mean more than 400) errors on the InitializeComponent() methods generated by the Windows Forms designer. Most of those errors are just the assignment of the Text property of labels.
I'd like to suppress those methods in source, so I copied the suppression code generated by FxCop into AssemblyInfo.cs, but it doesn't work.
This is the attribute that FxCop copied to the clipboard.
[module: SuppressMessage("Microsoft.Globalization",
"CA1303:DoNotPassLiteralsAsLocalizedParameters",
Scope = "member",
Target = "WindowsClient.MainForm.InitializeComponent():System.Void",
MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
Anyone knows the correct attribute to suppress this messages?
Thanks.
PS: I'm using Visual Studio 2005, C#, FxCop 1.36. |
In a project I'm working on FxCop shows me lots of (and I mean more than 400) errors on the InitializeComponent() methods generated by the Windows Forms designer. Most of those errors are just the assignment of the Text property of labels.
I'd like to suppress those methods in source, so I copied the suppression code generated by FxCop into AssemblyInfo.cs, but it doesn't work.
This is the attribute that FxCop copied to the clipboard.
[module: SuppressMessage("Microsoft.Globalization",
"CA1303:DoNotPassLiteralsAsLocalizedParameters",
Scope = "member",
Target = "WindowsClient.MainForm.InitializeComponent():System.Void",
MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
Anyone knows the correct attribute to suppress this messages?
Thanks.
PS: I'm using Visual Studio 2005, C#, FxCop 1.36 beta. |
Well, since `TimeZoneInfo` is excluded, you're probably not going to find a solution in the framework itself (but don't quote me on that).
In which case, have you considered reflectoring the `TimeZoneInfo` class and using what you find there? |
General programming translates terribly to GPUs. GPUs are dedicated to performing fairly simple tasks on streams of data at a massive rate, with massive parallelism. They do not deal well with the rich data and control structures of general programming, and there's no point trying to shoehorn that into them. |
Well, I think the reason this is the case is because "qwerty = 4" is ambiguous. Are you defining a new variable called "qwerty" or calling the accessor? Ruby resolves this ambiguity by saying it will create a new variable, thus the "self." is required.
Here is another case where you need "self.":
class A
def test
4
end
def use_variable
test = 5
test
end
def use_method
test = 5
self.test
end
end
a = A.new
a.use_variable # returns 5
a.use_method # returns 4
As you can see, the access to "test" is ambiguous, so the "self." is required.
EDIT: Also, this is why the C# example is actually not a good comparison, because you define variables in a way that is unambiguous from using the setter... if you had defined a variable in C# that was the same name as the accessor, you would need to qualify calls to the accessor with "this." just like the ruby case. |
Well, I think the reason this is the case is because "qwerty = 4" is ambiguous... are you defining a new variable called "qwerty" or calling the setter? Ruby resolves this ambiguity by saying it will create a new variable, thus the "self." is required.
Here is another case where you need "self.":
class A
def test
4
end
def use_variable
test = 5
test
end
def use_method
test = 5
self.test
end
end
a = A.new
a.use_variable # returns 5
a.use_method # returns 4
As you can see, the access to "test" is ambiguous, so the "self." is required.
EDIT: Also, this is why the C# example is actually not a good comparison, because you define variables in a way that is unambiguous from using the setter... if you had defined a variable in C# that was the same name as the accessor, you would need to qualify calls to the accessor with "this." just like the ruby case. |
Hmmm...
It sounds like you have a list of valid commands that the users are able to execute. But you don't want them to execute them all.
You could try to take the actual command line and verify the file exists in the "safe" location at least.
You could also solve the problem with more interface, provide a drop down of commands and parameters they could use. It's more work on your end, but it ultimately helps the users. |
Here's an (untested) theory, the details of which will greatly depend on what types of authentication the Sharepoint site will accept. I'll tackle [Basic][1], since it's the easiest.
You'll write out some JavaScript that uses XMLHttpRequest to submit a request to the Sharepoint site, and add their username and password to the request headers. Their browser will run that JavaScript, and get logged into the Sharepoint site.
Now, when they click the link, the client's browser should have the cached credentials to send to the Sharepoint site.
Possible issues:
- XMLHttpRequest does not allow cross domain auth
- Browser and XHR don't share auth info
- Sharepoint and XHR can't agree on auth method
Another option is to proxy the connection to Sharepoint, which allows you to login server side (bypassing XHR limitations and browser security) - but requiring load on your server and possibly some URL target issues.
[1]: http://en.wikipedia.org/wiki/Basic_access_authentication |
|java|design|struct| |
Is it completely against the Java way to create struct like objects?
class SomeData1 {
public int x;
public int y;
}
I can see a class with accessors and mutators being more Java like.
class SomeData2 {
int getX();
void setX(int x);
int getY();
void setY(int y);
private int x;
private int y;
}
The class from the first example is notationally convenient.
// a function in a class
public int f(SomeData1 d) {
return (3 * d.x) / d.y;
}
This is not as convenient.
// a function in a class
public int f(SomeData2 d) {
return (3 * d.getX()) / d.getY();
} |
|java|design|oop|struct| |
Using Django time/date widgets in custom form |
|django| |
How can i use the nifty js date and time widgets that the default admin uses with my custom view?
I have looked through http://www.djangoproject.com/documentation/forms/ , and it brefly mentions django.contrib.admin.widgets, but i don't know how to use it?
Here is my template that i want it applied on.
<form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
Also, i think it should be noted that i havnt really written a view up myself for this form, i am using a generic view. Here is the entry from the url.py
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
And i am relevantly new to the whole Django/MVC/MTV thing, so please go easy...
|
|python|django| |
I solved this exact same problem just two days ago. First, I moved the code that set the SelectedValue to a PreRender handler for the DropDownList. Then, I add logic to first check to see if the value is in the drop down list. If not, I add it.
Here's my code. ddSpecialty is my drop-down list, populated with "specialties" from the database. registration.Specialty is the specialty that the user chose, which may or may not be in the drop down, since that particular specialty may have been deleted since they last chose it.
protected void ddSpecialty_PreRender(object sender, EventArgs e)
{
if (!ddSpecialty.Items.Contains(new ListItem(registration.Specialty)))
ddSpecialty.Items.Add(registration.Specialty);
ddSpecialty.SelectedValue = registration.Specialty;
} |